- Home /
Rotate Object to face Velocity (2D)
So I have a script that I want to force the object to look in the direction its velocity is taking it. (or possibly 180 degrees of it, depending on the orientation of the 2D collider it's using.)
However, it seems at random, the object snaps to 90 degrees for no apparent reason, and the collider points in an odd direction.
So i'm at my wit's end here, anyone have any idea what to do?
Here's the code that forces rotation in velocity (Note that the object will bounce around, so direction changes will occur)
private Vector3 dist = new Vector3();
private Vector3 distprevframe = new Vector3();
private Vector3 dir = new Vector3();
void Update () {
dist = transform.position;
dir = dist - distprevframe;
dir = dir * 90;
distprevframe = transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle + 90, Vector3.forward);
Also, since I think it's relevant, here is the code for the object being spawned
Rigidbody2D Shot;
Shot = Instantiate (ProjectileTest, target.position, Quaternion.Euler (Vector3.forward)) as Rigidbody2D; //target is where the object is spawned.
Shot.velocity = transform.TransformDirection (Vector3.forward * bulletspeed);
Shot.transform.Rotate (Vector3.forward);
Answer by robertbu · Nov 23, 2014 at 07:59 PM
For 3D object (even in 2D space), @JeffKesselman's answer is in the right direction. But if your object is a sprite or a quad, then construct your sprite so that the front of the object faces right when the rotation is (0,0,0), then you can do:
Vector2 dir = transform.rigidbody2D.velocity;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
You are the best . . my logic was same as you the only problem which i never thought of was the default sprite orientation . . and when i constructed my sprite to face right it worked!! Thank you so much
Answer by Jeff-Kesselman · Nov 23, 2014 at 07:45 PM
This is all much too pointlessly complicated.
The vector of your motion is your velocity normalized.
So try something like this:
Vector2 motionDirection = transform.rigidbody2D.velocity.normalized();
transform.rotation = Quaternion.LookRotation(motionDirection, new Vector3(0,0,1));
or you can find the point at the end of the vector and use LookAt
Vector2 lookAtPoint = transform.rigidbody2D.velocity.normalized();
lookAtPoint += transform.position;
transform.LookAt(lookAtPoint,new Vector3(0,0,1);
The moral of this story is that vector algebra is a very good thing to know if you are working with a matrix/vector based system.
@Jeff$$anonymous$$esselman - 'normalized' is not a function, and for a LookRotation() you don't need to normalize the vector.