# Limit rotation angle

I am currently trying to rotate the weapons of a spaceship towards the mouse position, but in order to avoid the collision of projectiles with the ship I want to limit the angle the weapon can turn.

I've tried doing this:

    Vector3 mousePos = Input.mousePosition;
float range = 100.0f;
float rotStep = 0.1f;

Vector3 positionOnScreen = Camera.main.ScreenToWorldPoint(mousePos + Vector3.forward * range);

Vector3 targetDir = positionOnScreen - transform.position;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, rotStep * Time.deltaTime, 0.0f);

Quaternion lookRot = Quaternion.LookRotation(newDir);

float xAngle = lookRot.eulerAngles.x;
if (xAngle > 10 && xAngle <= 180)
{
xAngle = 10;
}
else if (xAngle < 350 && xAngle > 180)
{
xAngle = 350;
}

float yAngle = lookRot.eulerAngles.y;
if (yAngle > 10 && yAngle <= 180)
{
yAngle = 10;
}
else if (yAngle < 350 && yAngle > 180)
{
yAngle = 350;
}

float zAngle = lookRot.eulerAngles.z;
if (zAngle > 10 && zAngle <= 180)
{
zAngle = 10;
}
else if (zAngle < 350 && zAngle > 180)
{
zAngle = 350;
}

lookRot.eulerAngles =new Vector3(xAngle, yAngle, zAngle);
transform.rotation = lookRot;


The problem here is that I don't know how to limit the rotation angle since it's not the same depending on the ship rotation (for example if it's (0, 0 , 0) or (-90, -90, -90)). I've tried using transform.localRotation too, but still happens the same. Do you how could I limit the rotation regardless of the ship rotation?

• Have you tried using Mathf.Clamp()? – Millard Oct 18 '19 at 23:37

I think you should use the LocalRotation. because from what I see you are only checking the rotation of the cannons in world space, not locally.
• ah im sorry my bad i missed that. what you could maybe do is compare the rotation of the cannons to the rotation of the ship and if it goes past a set limit like if(cannon.rotation.y <= ship.rotation.y + 45 && cannon.rotation.y >= ship.rotation.y + -45 ) – MaartenVlutters Oct 18 '19 at 12:06