I am working on code that rotates the camera around a point on the in-game map when dragging the mouse. I understand how to lock it so it stays above the map surface.

However, if I keep rotating the view up, the camera will go "up and over" and be upside-down. How can I fix the camera orientation to make sure my camera stays upright?

A representative bit of code:

x += Input.GetAxis("Mouse X") * xSpeed;
y -= Input.GetAxis("Mouse Y") * ySpeed;

// when mouse moves left and right, rotate around local y axis
transform.RotateAround(target.position,transform.up, x);

// when mouse moves up and down, rotate around the local x axis
transform.RotateAround(target.position,transform.right, y);

You need to clamp the vertical rotation. I don't know off the top of my head the simplest way to adjust that code, but it'll just involve changing a couple lines around the transform.RotateAround() stuff, to use Mathf.Clamp() for the angle around the x-axis.

I think you just need to put in y = Mathf.Clamp(y, -180, 180); right after incrementing y. This way the downward rotation will be limited to straight down and never allowed to go too far.


The key is to analyze how an actual camera would work. If you're pointing it toward, say, a wall in front of you, then you point it toward the ceiling, and then keep turning it "up" you will find that the ground will actually start to come into view from the top. It seems odd at first - but the actual camera configuration you have is already "correct" IMO.

However, I can totally see why you wouldn't want it to be possible to view the map upside down. Even if it's correct - it is quite awkward. I do have a few suggestions to fix it:

  • First, easiest fix. If you keep track of the camera rotation on the X axis (assuming the camera is pointed toward the positive z axis) then you can add some code so that the user can never go past straight down or straight up - which will force them to look at anything behind them by turning the camera left or right.

  • Second, slightly more awkward fix (IMO). If you keep track of the camera rotation on the X axis (assuming the camera is pointed toward the positive z axis) then you can flip the camera when they go past straight down or straight up. Just rotate the camera on it's Z axis (still assuming it's pointed toward the positive z axis) 180 degrees if it passes one of those points, and then if it passes them again, rotate it another 180 degrees on it's Z axis. This is how the C# XNA "look at" matrix works.

Hope this helps! If anything sounds confusing - just ask. :)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.