- Home /
Looking at target in 2D
So I am trying to achieve this behaviour:
At the moment this is currently happening:
As you can see, when running along the bottom edge the rotation spins around and the green axis is facing up rather than down.
I am using transform.right = targetPos - transform.position;
to look at the next point.
The only difference between the two gifs is that in the working version one of the bottom points is 0.01 lower, this behaviour only occurs when the points are perfectly aligned.
Obviously one fix would be to never have the points perfectly aligned, but I want to know what is causing this problem.
Any help appreciated, thanks
Answer by FlaSh-G · Jun 18, 2017 at 10:19 PM
When you set transform.right, the new rotation is calculated using Quaternion.FromToRotation, which doesn't care about how the other two axes are rotated. Not so for Quaternion.LookRotation, which lets you specify an up vector. The third vector comes by itself with both specified.
transform.rotation = Quaternion.LookRotation(Vector3.forward, direction);
This will make the local forward vector look towards the target instead of right, but I'm sure you'll get the rest.
Took a bit of playing around with but lookrotation was what I needed, thanks.