- Home /
How do I obtain the local velocity of a Rigid body on one axis?
I'm creating a simple driving game were the player controlled vehicle is a single box-like rigid body.
I am accelerating the vehicle with rigid.body.AddRelativeForce and I'm steering the object with rigid.body.MoveRotation.
I really need to be able to obtain the relative velocity along the vehicles local X axis (forwards and backwards) to be able to script rules and logic from, and right now all I seem able to do is get either the world velocity (rigidbody.velocity) or all-axis-combined velocity (rigidbody.velocity.magnitude) but neither of these are accurate enough for what I want to do.
Can anyone offer any hints here?
Thanks.
Answer by Jesse Anders · Nov 02, 2010 at 03:59 PM
Try (untested):
float xVel = transform.InverseTransformDirection(rigidbody.velocity).x;
Just tested it, it works -- I've been doing this manually all this time. Thanks!
That does exactly the same as the code I posted... (which works btw, just tested)
Hehehe this should work: Quaternion.FromToRotation(transform.forward, Vector3.forward) * rigidbody.velocity); It was correct, just I think one of the axes was inverted
Answer by Atnas1010 · Nov 02, 2010 at 02:19 PM
Is this what you are looking for?
(transform.rotation * rigidbody.velocity).x
This works, but for folks looking back to see how to achieve this in unity 5 use:
private Rigidbody rb;
//in the start function
rb = GetComponent<Rigidbody>();
//in the update loop
rotation = (transform.rotation * rb.velocity).x;
P.S. I am a newbie to C# so please correct me if I have made a mistake
I would like clarification on this. I believe this answer is more 'performant' than float xVel = transform.InverseTransformDirection(rigidbody.velocity).x
;? is that correct? for example if called in every frame.
Answer by e-bonneville · Nov 02, 2010 at 01:40 PM
Use rigidbody.velocity.x
. Is that what you're looking for?
No, rigidbody.velocity.x gives me the velocity on the world x axis, not the local axis - this means it can report anything from high to low values depending on the direction I'm driving the vehicle in.