Math in Unity : LookAt()
In this article we will briefly talk about the LookAt() method.
It already exists in Unity, and is primarily designed for 3D.
Here’s the reference
https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
Today we will create it from scratch for 2D, the reality is that at the logic level absolutely nothing changes, except the fact that here we will have only two axes to work on.
And it will be very simple, because in practice we will take all the code we have in Start(), and we will translate it into a single method.
For now I simply create LookAt()
and I cut and paste everything inside.
Now, we simply make the method reusable.
First, we need parameters.
As we have seen in these articles, what we need to do the math is:
the Vector that represents our forward,
the Vector representing our position,
and the Vector representing the object position.
We pass these three parameters inside the method
Then we replace the variables with parameters.
We need a variable for direction, and we assign it to
objPos - pos
We calculate the angle,
from our forward and the direction
Then, we calculate the Cross product on Z axis
We create the Vector3 variable of “rotation” and assign it to the Rotate() method
and return it.
So we need to change the method from void to Vector3.
We pass the parameters
Beware of one thing:
since we create a method, we have to initialize DIRECTION in Start() or we get an error.
Another thing is this: I used Normalize (_direction) directly in Update()
But maybe is better use it in Start()
Last change, we have to assigned LooktAt() at our transform.up.
This how works LookAt() method.