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.
2 Answers
2That’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
Braking doesn't make cars go backwards... Do you mean "How do i know if my rigid body is speeding up or slowing down?".
– liamcaryHow does the car move? Is it a rigidbody (they use world velocity to move,) or using a charController (moveDirection is local, I think, so +z is always forwards to the car.) Is it a 2D game, so it just faces left or right? Is there a track, so forwards means which way the track is going?
– Owen-Reynolds@Owen Its a 3D game, its a rigidbody.
– poohshoes@poohshoes: Such "small" details like if it's a 2 or 3d game should be in the description of your question. In most cases one sentence isn't enough to give all required information.
– Bunny83