- Home /
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)
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.
Answer by _Gkxd · Jul 30, 2015 at 07:14 PM
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
Hi, this works beautifully for the top half of the object but the second I cross this line:
It starts moving the opposite direction of where it should be following the second I cross that line.
I tried to edit the code some but nothing I did fixed the issue. Would you happen to know what is causing this?
That is a bit strange... maybe I got the angle flipped. Does changing angle
to -angle
fix anything?
If not, could you post screenshots with the red/green/blue arrows in the scene view? That would help me understand what's happening a bit better.
Changing angle to -angle fixes the bottom half however now it is doing it to the top half. $$anonymous$$y computer just started acting up and I cant seem to get it to take screenshots right now for some reason (this isn't the first time its done this)(its a somewhat old computer) it might take me a little bit to get the screenshots that you asked for to you.