# Maximum and Minimum rotation

Hey, guys, I’m fairly new to scripting so I apologize if this turns out to be really basic, I am creating a 3d game, I want a maximum and minimum angle to stop rotation and I came up with this but for some reason, it’s not working .thank you!, Hi! I’m trying to make a 3d game, but I’ve faced a problem. I should limit the x&z-Rotation of that object between 40 and -40. Thank You!

Vector3 prevpos = Vector3.zero;
Vector3 posdelta = Vector3.zero;

``````// Update is called once per frame
void Update () {
if(Input.GetMouseButton(0))
{

posdelta = Input.mousePosition - prevpos;

if ((transform.eulerAngles.x < 40) && (transform.position.x > -40))
{
transform.Rotate(Camera.main.transform.right, -Vector3.Dot(posdelta, Camera.main.transform.up), Space.World);

}
if ((transform.eulerAngles.z < 40) && (transform.position.z > -40))
{
transform.Rotate(transform.forward, Vector3.Dot(posdelta, Camera.main.transform.right), Space.World);

}

}
prevpos = Input.mousePosition;
}
``````

I see a couple things in your code that might cause issues. First, i wouldn’t use this method but that is just my preference of course. It’s a bit complex for the purpose. The if statement could be a problem, you want to keep the value between -40 and 40. The value needs to be between those values to rotate, but it will stop rotating when it is outside the range. But when you are outside the range, it will not be able to rotate, so you can’t get back. It’s a one way street. It will not help to turn the < into a < = because then it will just rotate a bit further but it will cause the same problem.

Setting eulerAngles directly is not recommended and you should use Quaternions in case you are not sure if the value will loop around 360 degrees. It looks like this is not the case so you will be fine. I would use a method something like this:

``````Vector3 prevpos = Vector3.zero;
Vector3 posdelta = Vector3.zero;

float xRotation = 0;
float zRotation = 0;

float speedFactor = 0.1f;

// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
posdelta = Input.mousePosition - prevpos;

xRotation += posdelta.x * speedFactor;
zRotation += posdelta.y * speedFactor;

xRotation = Mathf.Clamp(xRotation, -40, 40);
zRotation = Mathf.Clamp(zRotation, -40, 40);

transform.eulerAngles = new Vector3(xRotation, 0, zRotation);
}

prevpos = Input.mousePosition;
}
``````

This will increment or decrement the value of the rotation according to the positionDelta. Then the value gets clamped between -40 and 40. This way it won’t get stuck after 40. We then multiply by a factor so we can control the rotation speed, without it it will be way to fast. And that’s it really. Also be careful with the mousePosition, its not a problem now because all the Vector3s are mousePositions, but mousePosition is actually a Vector2. So casting it to a vector3 will add a z-axis of value 0.