Getting/Setting local velocity?

Does anyone have a simple way of getting and setting a localVelocity for a RigidBody.

So if it’s traveling forward and I suddenly “teleport” the rigidbody and it’s facing a different direction, I want it to be going forward relative to itself and not in the same “world” direction that it was before :slight_smile:

Thanks guys,
Nathan

Use rigidbody.AddRelativeForce with the ForceMode = VelocityChange. Unity - Scripting API: Rigidbody.AddRelativeForce

AddForce or AddRelativeForce with ForceMode = VelocityChange is additive so it adds to the current velocity of the rigidbody. So to do what you want to do you’re going to want to neutralize your previous velocity and then add it again with your new forward.

Something like (not tested):

// Get the velocity in global coords
Vector3 currentVelocity = rigidbody.velocity;
// Translates the global representation of the rigidbody's velocity into a local coordinate representation.
Vector3 currentVelocityLocal = transform.InverseTransformDirection(currentVelocity);

// Neutralize your current velocity so your net velocity is 0.
rigidbody.AddForce(( -1 * currentVelocity ), ForceMode.VelocityChange);

// Do your teleport

// Add your velocity but in terms of the local coordinate system
rigidbody.AddRelativeForce(currentVelocityLocal, ForceMode.VelocityChange);

I think that’s it. Anyone care to spot check me on this?

2 Likes

transform.InverseTransformDirection (rigidbody.velocity).z

when u setup this object, make sure it’s foward vector is in z direction, then you are good.

Hyjinx and tigerspidey,

Thanks for the help! I used Hyjinx code and I think it’s working correctly now!!! :slight_smile: