-4
\$\begingroup\$

I would like to know how i can rotate an object with an rigidbody so it's facing the way it's traveling.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ What did you try? \$\endgroup\$
    – Vaillancourt
    Commented Jun 12, 2015 at 11:04

1 Answer 1

1
\$\begingroup\$

First you need to get the direction you are traveling in:

Vector2 direction = rigidBody2D.velocity.normalize();

Then you want to get the angle of this direction:

float ang = Vector2.Angle(rigidBody2D.transform.position, direction);
Vector3 cross = Vector3.Cross(rigidBody2D.transform.position, direction);

if (cross.z > 0)
    ang = 360 - ang;

Then you can use MoveRotation to adjust your rigidBody's new direction:

Quaternion q = Quaternion.Euler(ang);
rigidBody2D.MoveRotation(q);

I didn't test any of this.

\$\endgroup\$
5
  • \$\begingroup\$ nice @jon ... it's the simple stuff that I often trip up on lol \$\endgroup\$
    – War
    Commented Jun 12, 2015 at 12:37
  • \$\begingroup\$ lol @Wardy, this wasn't your question though :P \$\endgroup\$
    – jgallant
    Commented Jun 12, 2015 at 12:37
  • \$\begingroup\$ Yeh I just liked how you went ... "oh it's easy ..." and i'm sat here thinking ... aww this is gonna be a tough one lol \$\endgroup\$
    – War
    Commented Jun 12, 2015 at 13:07
  • \$\begingroup\$ I'm sorry i didn't specify it in the question but how would you do this in a 3d space with a normal rigidbody and not a rigidbody2D. \$\endgroup\$
    – Signekatt
    Commented Jun 12, 2015 at 18:49
  • \$\begingroup\$ Same thing, except to get the angle you would do: Vector3.Angle(rigidBody.transform.position, direction); \$\endgroup\$
    – jgallant
    Commented Jun 12, 2015 at 18:51

Not the answer you're looking for? Browse other questions tagged .