- Home /
How do I know if my rigid body is moving "forwards" (instead of "backwards")?
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.
Braking doesn't make cars go backwards... Do you mean "How do i know if my rigid body is speeding up or slowing down?".
How 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?
@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.
Answer by Bunny83 · Mar 21, 2013 at 09:27 PM
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...
Answer by ErfanAhmadi · Mar 21, 2013 at 06:21 AM
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
Your answer
Follow this Question
Related Questions
Using Physics.gravity to accelerate an object 3 Answers
Animation Speed Problem 2 Answers
Render texture material is backwards. 0 Answers
Speed Limit,Sideways movement and speed limit 0 Answers
Jump Backwards Off Of Wall? 0 Answers