Is there a way to know which direction an object is moving?

Hello guys!
Is there a way to know which direction the player is moving and compare it with the angle it’s facing towards?
For example, the player is facing the direction he’s moving towards so there’s a 0-degree angle difference
while if he’s facing slightly to a degree from the direction he’s moving there’s an offset of a certain angle.
For example, if he’s moving forward while his butt is in the front there is a 180-degree offset.
is there a way to calculate the offset?

If you’re using a rigidbody and physics based movement, then rigidbody.velocity is the direction it is moving. I don’t know the answer to the rest of your question.

2 Likes

Are you using Rigidbody?

If you’re using a Rigidbody for the motion then you have the following:

Vector3 facing = rb.rotation * Vector3.forward;
Vector3 velocity = rb.velocity;

// returns the absolute minimum angle difference
float angleDifference = Vector3.Angle(facing, velocity);

// returns the angle difference relative to a third axis (e.g. straight up)
float relativeAngleDifference = Vector3.SignedAngle(facing, velocity, Vector3.up);

If the handlebars are a separate, child object that is not directly tied to the rotation of the rigidbody, you can use handleBarTransform.forward for the facing of the handlebars, assuming you have a reference to the Handlebars transform.

4 Likes

This works. from both directions, I get a positive value. how do I get a negative value? also and is there a way to completely ignore Y velocity? Thank you

Use the signedAngle version.

Project the vectors onto the x/y plane with Vector3.Project(myVector, Vector3.up)

1 Like

Thank you it worked!