How to rotate my object correctly?

I realize this question has been asked and answered a lot, however everything I can find either uses an outdated version of unity and the scripts don’t work, the scripts use javaScript (I use c#), or it just plain doesn’t work for what I want.

I have a green oval sprite with a slice out of it and a smaller green oval sprite without anything missing (see Fig. 1). I want the missing piece of the larger oval to always face the smaller oval no matter where the smaller oval is. (This is a 2d game and nothing should move along the “z” axis)

(Fig. 1)

51286-untitled.png

This is the script I currently have:

public Transform player;
	Vector3 target;
	
	void Update()
	{
		target = new Vector3(player.position.x, player.position.y, this.transform.position.z);
		transform.LookAt(target);
	}

However this does not work. It always rotates the larger oval 90 degrees along the “y” axis so the larger oval faces the smaller one like this:

I have used just about everything I can find and everything either doesn’t work or ends in the same result.

Please explain to me why this is happening and how I can fix this.

thanks for your help in advance.

LookAt rotates the forward vector (+z axis) to point at your the target. For a 2D game, this isn’t what you want.

You can use Vector3.Angle instead, which gives you an angle between two vectors.

Here is some pseudocode for what the relevant code might look like:

float angle = Vector3.Angle(Vector3.right, target.position - transform.position);

transform.eulerAngles = new Vector3(0, 0, angle);

The above code assumes that target.position and transform.position always have a z value of 0.

Edit:

The above code doesn’t actually work, since Vector3.Angle can’t return angles greater than 180. The correct way would be to use Mathf.Atan2 instead.

Vector3 difference = target.position - transform.position;
float angle = Mathf.Atan2(difference.y, difference.x);

// Do the same thing with angle as above