Limit rotation angle

by Hector   Last Updated October 09, 2019 13:13 PM - source

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?

Tags :