Rotate object on another object
Greetings, I am starting to make artificial intelligence in my game and I can’t understand how to make my enemies turn on my player. I’m still new to Unity, so I don’t understand how vectors work. I would really appreciate help
Answer by streeetwalker · Mar 26, 2020 at 10:56 AM
@CeleDko , the general idea is: if you subtract two point vectors, you get the a direction vector that represents the difference between them moved to the zero point ( the world origin ). That represents the direction from the first vector to the second one. You can use that vector for your rotation.
Say you are in 2D, and your player is at ( 1, 1 ) and your enemy is at ( 2, 2 ) . You should plot that on a grid! Also, say the enemy is rotated in what ever direction. (in 2D, an object rotates on it z axis, and normally positive x is considered the forward direction, so we'll assume your enemy faces positive x )
You want the enemy to face the player. To do so we need to get the direction from the enemy to the player. The player is the 'target' or 'end' point, and the enemy is the 'start' point.
the general algorithm is: direction = end point - start point
so: ( 1, 1 ) - ( 2, 2 ) = ( 1 - 2, 1 - 2 ) = ( -1, -1 ) < that is the direction to turn to.
The Quaternion class, which is Unity's internal rotation representation, has many nice functions to rotate objects: One is Quaternion.AngleAxis( angle, rotation axis ).
To use that we need to covert the direction to a degree angle using the trigonometric Arctangent function. The rotation axis will be z, represented by the vector(0,0,1), or Vector3.up.
So, get the direction from enemy to the player, then get the angle, then rotate :
float direction = player.transform.position - enemy.transform.position;
float angle = Mathf.Atan2( direction.y, direction.x) * Mathf.Rad2Deg;
enemy.transform.rotation = Quaternion.AngleAxis( angle, Vector3.up );
Note that this will not be animated - it will instantly change the rotation. If you want to animate it, you'll put the AngleAxis code in an animation loop and calculate a anther variable based on the angle and Time.DeltaTime, and use that in the AngleAxis function instead.
Your answer
Follow this Question
Related Questions
Clamping Between Two Different Ranges 1 Answer
How do you make the vrtk rotator accommodate more than one axis at a time? 0 Answers
Rotate rigidbody to specified rotation using AddForce 0 Answers
Draw a ray from a gamobject and keep direction of the ray relative to the gameobjects rotation. 1 Answer
How to properly access an object in an array using a for loop? 0 Answers