- Home /
Converting a Velocity
How can I convert a Velocity of a Forward of 0, 0, 1 to a new Velocity of another Forward? For exemple 0, 1, 0.
Basically, I'm used to get the velocity.x variable to know if the player is turning left or right. The problem is that some scenes have turns now, and the velocity.x variable is just not related anymore since it's respecting the world's forward wich is 0, 0, 1 I think.
When the player takes the map turn, the game changes it's Forward to fit to the new direction and I would like to create a new Velocity vector that would tell me the velocity based on the player's forward and not the world's forward.
I tried currentVelocity = currentForward * rb.velocity.magnitude;
But that still gives me the world's velocity of the player
You can rotate a velocity (Vector3) with a quaternion. Such as: rb.velocity = Quaternion.AngleAxis(30f, Vector3.up) * rb.velocity; , which rotates 30 degrees around the y axis (if y is up). If you are wanting to rotate the velocity when the map rotates, then apply that method with the same angle as the map. If this is not what you are talking about, please let us know.
Thanks for your response. How can I get the rotation angle of Y from the forward ?
Quaternion can get the rotation between two vectors (or in this case forwards) as well with: rb.velocity = Quaternion.FromToRotation(oldForward, newForward) * rb.velocity;
Answer by Bunny83 · Feb 06, 2019 at 02:29 AM
If you want to know the velocity in local space of your camera. Just use InverseTransformDirection of the transform of your camera with your worldspace velocity:
public Transform camTransform;
Vector3 localVelocity = camTransform.InverseTransformDirection(rb.velocity);
Now localVelocity.x
is always "right" as seen from the camera.
If you just want to know if the velocity is pointing to the left or to the right of the camera, you could also use the vector dot product
if ( Vector3.Dot(rb.velocity, camTransform.right) > 0 )
Debug.Log("to the right");
else
Debug.Log("to the left");
Thanks. Your code can actually be implemented directly to the rolling ball object with currentVelocity = transform.InverseTransformDirection(rb.velocity);