-4
\$\begingroup\$

This question already has an answer here:

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

\$\endgroup\$

marked as duplicate by MichaelHouse Jun 12 '15 at 14:01

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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\$
  • \$\begingroup\$ nice @jon ... it's the simple stuff that I often trip up on lol \$\endgroup\$ – War Jun 12 '15 at 12:37
  • \$\begingroup\$ lol @Wardy, this wasn't your question though :P \$\endgroup\$ – jgallant Jun 12 '15 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 Jun 12 '15 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 Jun 12 '15 at 18:49
  • \$\begingroup\$ Same thing, except to get the angle you would do: Vector3.Angle(rigidBody.transform.position, direction); \$\endgroup\$ – jgallant Jun 12 '15 at 18:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.