- Home /
!Urgent! How to get a sprite to look at another object?
I'm working in 2D unity and I want to have a sprite look at the player but transform.LookAt and
Quaternion rot = Quaternion.LookRotation( transform.position - player.transform.position, Vector3.forward );
transform.rotation = rot;
doesn't work either so what's a good way to do this? Thank you!
Answer by BMayne · Aug 30, 2014 at 06:38 PM
Hey,
This is a common problem that comes up when doing 2D Games. Luckily with some simple math you can fix this really quickly.
//What is the difference in position?
Vector3 diff = (lookTarget.position - transform.position);
//We use aTan2 since it handles negative numbers and division by zero errors.
float angle = Mathf.Atan2(diff.y, diff.x);
//Now we set our new rotation.
transform.rotation = Quaternion.Euler(0f, 0f, angle * Mathf.Rad2Deg);
Regards
If you're curious about how to get this to work with a triangle sprite, you need to subtract 90 to your angle, or it'll look directly right of the object you want to look at. The new code is practically the same;
//What is the difference in position?
Vector3 diff = (lookTarget.position - transform.position);
//We use aTan2 since it handles negative numbers and division by zero errors.
float angle = Mathf.Atan2(diff.y, diff.x);
//Now we set our new rotation.
transform.rotation = Quaternion.Euler(0f, 0f, angle * Mathf.Rad2Deg - 90);
Your answer
Follow this Question
Related Questions
Get slerp to work just as LookAt(,Vector3.right) does 1 Answer
How to make an enemy look at you and follow you 0 Answers
Hello, Need some help with Enemy facing the player on z axis !! 0 Answers
transform.LookAt boundaries 1 Answer
Using LookAt method to get object X rotation to face another object 1 Answer