Before updating to Windows 10 you may need to return your Pro license. More information here

How to restrict rotation properly

How do I restrict rotation angles? The rotation just keeps slipping through the limit and stopping forever. When I set 355 as a limit, it stops at 354.993 or something. Can something be done about it? Is the problem with Update frequency?

I am using this code:

 if(Input.GetAxis("Mouse X")<0)
     if ((transform.rotation.eulerAngles.y < 4) || (transform.rotation.eulerAngles.y > 355))
         transform.RotateAround(cameraFocus.position, Vector3(0, -1, 0), 5 * Time.deltaTime);
 if(Input.GetAxis("Mouse X")>0)
     if ((transform.rotation.eulerAngles.y < 4) || (transform.rotation.eulerAngles.y > 355))
         transform.RotateAround(cameraFocus.position, Vector3.up, 5 * Time.deltaTime);

I need this for synching cursor movement with camera rotation, obviously.

Please, help.

more ▼

asked Jan 02, 2012 at 03:06 AM

avatar image

23 28 18 21

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Not clear what this code is trying to do. It looks like you're trying to limit the camera rotation to +/- 5 degrees, which seems a bit small.

Personally, I'd insert a dummy GameObject which sits at the cameraFocus position, with the camera parented to that. Then you just set the dummy's transform.rotation.eulerAngles, rather than doing a RotateAround which will gradually accumulate floating point error. You can then easily clamp the Y rotation to exactly what you want.

more ▼

answered Jan 02, 2012 at 03:37 AM

avatar image

489 5 7 14

How do I add those eulerAngles then? What code would you use for that?

Jan 02, 2012 at 09:43 AM krides

Pretty much what you've got, except you want the rotation script to be on the dummy pivot object instead of the camera. Try this (may have typos, I write in C# usually):

 var maxRot = 45;
 var angle = transform.rotation.eulerAngles.y;
 angle += Input.GetAxis("Mouse X");
 if (angle > maxRot)
     angle = maxRot;
 else if (angle < -maxRot)
     angle = -maxRot;
 transform.rotation.eulerAngles = new Vector3( 0, angle, 0 );

NB. You have to set the entire Vector3 - you can't modify transform.rotation.eulerAngles.y on it's own.

Jan 02, 2012 at 05:05 PM Winterblood
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments



asked: Jan 02, 2012 at 03:06 AM

Seen: 4005 times

Last Updated: Jan 02, 2012 at 05:05 PM