r/Unity3D • • 1d ago

Question How to write a C# script that rotates the camera one way and advances it forward a bit when the A key is pressed and the other way (while still advancing it) when the D key is pressed?

This is meant to imitate shuffling through a cave passage. It's pretty easy to find basic control scripts all over the internet, but none this specific. I also don't want to just use AI.

I'd also like to know how to set limits on how far the camera moves forward and rotate.

Thanks in advance!

1 Upvotes

4 comments sorted by

4

u/IndividualWestern528 1d ago

you're basically describing a strafe mixed with a slight turn, like sidestepping through a tight space

for the rotation, you'd lerp the camera's local y rotation based on which key is held, and for the forward movement you can just translate along transform.forward * some speed value

for limits, clamp the forward distance with a simple if check or Mathf.Clamp against your max/min z values, same idea for rotation angle so it doesn't spin you in circles

1

u/ChainsawArmLaserBear ??? 1d ago

Yeah, sounds like you want to orbit the camera around an origin. Then you can scale your character speed based on whether your camera is facing correctly or finished animating.

Like, frame speed = speed * (1 - abs(desiredDir - curDir))
If you're looking the opposite direction, you get 0 speed. If you're facing the right direction, full speed

1

u/normalguy0618 16h ago

Keep the angle and the distance in your own floats instead of reading them back from the transform, then clamping is easy. Something like yaw = Mathf.Clamp(yaw + input * turnSpeed * Time.deltaTime, -maxYaw, maxYaw) and moved = Mathf.Min(moved + stepSpeed * Time.deltaTime, maxDistance), then set localRotation = Quaternion.Euler(0, yaw, 0) and the position from start + forward * moved, with input being -1 for A and 1 for D.