I have made a simple rotating code that allows an enemy to turn up or down depending on whether the player is above and below it (not the best, but it does the job its supposed to do). However, sometimes the enemy turns too much and does things it isn’t supposed to do. How can I prevent an enemy from turning past a certain point (eg. it has to stay within -90 to 90 degree range).
I have tried to set a min and max value (-90 and 90) but I learned that transform.rotation does not show the way it does in the editor so it didnt work.
I think, unity converts the quaternion to angle in the range from 0 to 360. -90 in inspector will be 270 in unity intern.
you can try to check angle between needed and current direction and rotate the object back if the angle is too big.
Vector3 startDirection;
//max angle to turn
public float angle;
private void Start()
{
//save start direction
startDirection = transform.up;
}
private void Update()
{
if (Vector3.SignedAngle (startDirection, transform.up, Vector3.forward) > angle)
{
transform.up = startDirection;
transform.Rotate(new Vector3(0, 0, angle));
}
if (Vector3.SignedAngle(startDirection, transform.up, Vector3.forward) < - angle)
{
transform.up = startDirection;
transform.Rotate(new Vector3(0, 0, - angle));
}
}
in some case you can use eulerangles (i think this will not work by rotation over zero to negative
//angle between 0 and 360
public float minAngle, maxAngle;
private void Update()
{
Vector3 tmpRotation = transform.eulerAngles;
if (tmpRotation.z > maxAngle)
{
transform.eulerAngles = new Vector3(0, 0, maxAngle);
}
if (tmpRotation.z < minAngle)
{
transform.eulerAngles = new Vector3(0, 0, minAngle);
}
}
and depended on your script, you can try just prevent the rotation from the execute if the angle is to big.
1 Like
Pretty new to rotation or angle based commands, can you please explain how signedangle works?