!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!

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

Thanks for this, I was having similar issues but found a much simpler way to achieve this:

    private GameObject player;
    private SpriteRenderer spriteRenderer;
    private readonly string playerTag = "Player";

public void Start() {
        player = GameObject.FindWithTag(playerTag);
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    private void LookAtPlayer() {
        // What is the difference in position?
        float diff = player.transform.position.x - transform.position.x;
        
        spriteRenderer.flipX = diff > 1;
    }

    private void Update() {
        LookAtPlayer();
    }

Please let me know if you require clarification on anything