I have a rigidbody that is a car in a 3D game. I need to be able to detect when it is moving backwards or forwards so that I can tell if I am braking or accelerating.
That’s pretty simple. The velocity vector tells you the speed in worldspace. That’s pretty useless since we need to know the velocity in relation to our own orientation. So we just need to transform the velocity vector into localspace:
// C# and UnityScript
var velocity = rigidbody.velocity;
var localVel = transform.InverseTransformDirection(velocity);
if (localVel.z > 0)
{
// We're moving forward
}
else
{
// We're moving backward
}
This of course assumes that the forward axis (z-axis) of your rigidbody points forward…
Here Is The C# Code :
public bool isMovingForward;
public bool isMovingBackward;
public Vector3 LastPOS;
public Vector3 NextPOS;
void LateUpdate() {
NextPOS.x = transform.position.x;
if(LastPOS.x < NextPOS.x){
isMovingForward = true;
isMovingBackward = false;
}
if(LastPOS.x > NextPOS.x){
isMovingBackward = true;
isMovingForward = false;
}
else if(LastPOS.x == NextPOS.x){
isMovingForward = false;
isMovingBackward = false;
}
LastPOS.x = NextPOS.x;
}
you Can Also Use Something Like That : if(CarSpeed > 30){Code};
if You Car Moving Forward And Back ward is on x Axis , Enter This code .
if You Car Moving Forward and Back ward is on z Axis , use Z instead X in code .
Sorry For My Language.
GOOD LUCK