- Home /
How do I make an object look at an another object in Top-Down 2D? ( C# )
I've tried googling it but none seemed to work for me.
How can I make an object follow and LOOK AT an another object while they both move?
LookAt doesn't work properly in 2D.
Thanks! :)
/////
Here is my current code to follow the object. It doesn't contain any code to look at the object.
public Vector3 objectPosition;
private Vector3 diff;
public static float speed = 5.0f;
// Use this for initialization
void Start () {
transform.position = new Vector3 (0,25,0);
}
// Update is called once per frame
void Update () {
Vector3 playerPosition = GameObject.FindWithTag("object").transform.position;
transform.position = Vector3.Lerp (transform.position, objectPosition, Time.deltaTime * speed);
}
Try feeding in your 2D coords to the LookAt and zeroing the third, unused axis.
Answer by robertbu · May 11, 2014 at 01:54 PM
Assuming standard 2D on the XY plane:
var dir = target.position - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
This code assumes that the front side of the object is to the right. If your front side is the top, then add 90 to 'angle' before passing it to AngleAxis().
Thanks! It worked perfectly.
If you have the time, could you explain to me how it worked? Like, line by line. Thanks again!
Anyone else could explain her code as well. Would be much appreciated :)
The first line creates a direction vector. Vectors don't have an origin...they just point in a particular direction. If you don't understand vectors, spending an hour or two reading about them will really help you with Unity.
Imagine that Vector starting at the origin and pointing in a direction like the hand on a clock. The second line calculates the angle of that "clock hand." Angle 0.0 is directly to the right (three o'clock). Up (noon) is 90 degrees.
AngleAxis() spins an object around a particular axis. I'm using Vector3.forward, so it will spin the object on the world's 'z' axis. I'm rotating to the angle we calculated in the previous line.
Hello friend, thank you very much for the solution, thank you from Brazil.
Your answer
Follow this Question
Related Questions
Camera rotation around player while following. 6 Answers
Waypoint navigation in 2D without LookAt 2 Answers
Shoot second cell in 2d 0 Answers
Problem With 2D Camera Following Target 3 Answers