Unity - Quaternion Rotation
Keep an eye on a GameObject with LookRotation!
You might have played a Tower Defense game before. Have you ever noticed that at least one enemy is always looking at you, regardless where you move to? Exactly that is the concept of LookRotation in Unity. It keeps track of another GameObject and rotates to always focus it. Let’s find out how we can implement such a behavior in Unity today!
The starting environment
We have two cubes, cube A and cube B.
The objective is that cube B will track and follow the movement of cube A.
The code we need
A quick google search will take us to the Unity Scripting reference of Quaternion.LookRotation(). There we can find the following example code:
Let’s break that code down:
- We assign a target which will be looked at. In our case, this will be Cube A
- A relative position will be calculated, by getting the target’s position and substracting the current player position (in our case Cube B) from it
- Next up is the calculation of the actual rotation amount. We use the LookRotation() method and hand over the relative position and a Vector3 for the upwards direction.
- Lastly, we assign the current rotation of cube B to the calculated rotation
If we now run the code in Unity, we will get the following behavior:
Cube B will now always look at Cube A, regardless of where it moves!
And that’s about it for todays little article!
Thanks for your time!