- Home /
Finding the Angle for Enemy Ai
I was trying to find the angle of the AI for a script, and I just want to know if my knowledge is correct. If you find the cross product/normal of the angle (the forward vector and the vector to the left or right), if the normal is Not perpendicular to the Up Vector, and is pointing in the same direction as that Up Vector (or is at least above zero) then the angle would be to the right. If the normal is pointing in the opposite direction of the Up Vector then the angle would be to the left. Is this correct or am I missing something.
float FindAngle(Vector3 fromVector, Vector3 toVector, Vector3 upVector) // float function
{
if(toVector == Vector3.zero) //if desired velocity is zero then return zero // to avoid error
return 0f;
float angle = Vector3.Angle (fromVector, toVector);
Vector3 normal = Vector3.Cross(fromVector, toVector); //finds cross product
angle *= Mathf.Sign(Vector3.Dot (normal,upVector)); //if normal and up vector are pointing in same direction the result is greater than zero(angle is to the right)
angle *= Mathf.Deg2Rad; //if the normal however is pointing down in relation to the upVector, then the result will be less than zero (and the angle will be to the right)
//if the normal and upVector were perpendicular to each other than that would be zero
return angle;
}
Check the Cross product section of this page of the manual. Unity uses the left-hand rule.
Here is my SignedAngle function:
function SignedAngle(v1 : Vector3,v2 : Vector3, normal : Vector3) : float {
var perp = Vector3.Cross(normal, v1);
var angle = Vector3.Angle(v1, v2);
angle *= $$anonymous$$athf.Sign(Vector3.Dot(perp, v2));
return angle;
}
Ok I think I got it. If the player is to the right of the enemy, then the normal will face the the same direction as Vector.Up and the angle will be to the right. Vice versa and the angle will be to the left.
Your answer
Follow this Question
Related Questions
ZOMBIE AI SCRIPT 1 Answer
Is the Player Being Looked at 1 Answer
How do I spawn unique Waypoints for my AI? 1 Answer
EnemyAI C# Error 1 Answer