- Home /
Set The Local Velocity Of A Rigidbody
I am currently using a smoothdamp function to de-accelarate my player's velocity. However, because velocity.x and .z aren't local, it doesn't work properly.
if (grounded)
{
if (!Input.GetButton("Horizontal"))
rigidbody.velocity.x = Mathf.SmoothDamp(rigidbody.velocity.x, 0, walkDeaccelerationVelx, walkDeacceleration);
if (!Input.GetButton("Vertical"))
rigidbody.velocity.z = Mathf.SmoothDamp(rigidbody.velocity.z, 0, walkDeaccelerationVelz, walkDeacceleration);
}
So what do I do to the above code to make each statement act on the rigidbody's local velocity?
In think you can just use transform.InverseTransformDirection() on the velocity, do the damping, and transform the vector back to world space with transform.TransformDirection().
Sorry, I don't understand. Could you repost my above code with that adjustment? As I am unsure of how I would apply a vector to the .x and .z of a different vector.
do you have a good reason for directly affecting velocity ins$$anonymous$$d of doing it the proper way? I.$$anonymous$$ adding force in the inverse direction of velocity. You could simply do add force (-velocity) and stop when velocity is approx vector3.zero or at that point manually set velocity to zero. Generally speaking if your going to use a rigidbody use physics to change stuff, otherwise dont use a rigidbody.
Yes, as the decrease in velocity must be deter$$anonymous$$ed by the current velocity and it must be done smoothly, which I am unsure of how to do with add force as I don't know how to actually get the local velocity. $$anonymous$$y way in theory works great, if I can set the local velocity.
Answer by robertbu · Jul 20, 2013 at 07:03 PM
Here is what I was talking about (untested):
var v3Velocity = transform.InverseTransformDirection(rigidbody.velocity);
if (!Input.GetButton("Horizontal"))
v3Velocity.x = Mathf.SmoothDamp(v3Velocity, 0, walkDeaccelerationVelx, walkDeacceleration);
if (!Input.GetButton("Vertical"))
v3Velocity.z = Mathf.SmoothDamp(v3Velocity.z, 0, walkDeaccelerationVelz, walkDeacceleration);
rigidbody.velocity = transform.TransformDirection(v3Velocity);
Answer by sparkzbarca · Jul 20, 2013 at 07:10 PM
you can get the local velocity via transform.inversetransformdirection(velocity)
however -velocity is the going exactly the opposite direction in world space so you can stay in world space.
//braking power should be a value between 0 and 1 probably
//a breaking force of 0 will not stop you a breaking force of 1 should stop
// you completely nearly instantly
float BrakingPower;
bool Brake;
void FixedUpdate()
{
if(Brake)
rigidbody.addforce(-rigidbody.velocity * BrakingPower * time.deltatime);
}
}
that should do it.