Lock Rotation of Object between 2 points, which is looking at the direction the mouse is pointing
I've been struggling with this for a while and im not able to find a solution. As stated in the title i want to lock the rotation of the z-axis in a 2 game where the player object looks where the mouse is placed and it shouldn't rotate more than a specific value.
Appreciate any help.
Answer by romatallinn · Oct 28, 2016 at 11:08 PM
You can use Mathf.Clamp for this.
transform.rotation = Quaternion.Euler(0, 0, Mathf.Clamp(transform.rotation.z, min, max));
However, you have to be sure that you use an appropriate form of the angle. I mean, for example, you have the current angle 20 degrees. You want to clamp it between 0 and 45. In this case, it will work great. You will get back 20. But, the angle of 20 degrees is the same as the angle of -340. Unity sometimes provides you negative angles, sometimes positive. If it did provide you -340, then it will be clamped to 0, but it had to be just 20. Thus, you have to make a few if-statements to ensure that you use an appropriate range for it. There is nothing difficult. If the current angle is negative, then add to it 360 and, afterwards, you can use it in clamp.