Detect if velocity equals 0?
Hi Unity Answers!
I have a basic jump working for my Movement script. However, I want the player to only be able to jump if they're on the ground. I've used different methods that check for ground collision and even Raycast distance from ground...but they all have flaws.
My new solution is to check whether if player's "y" velocity is 0 then they're able to jump. Problem is I can't figure out how to write that in C#.
Here's my current working jump script without the velocity detection:
public class NewBehaviourScript : MonoBehaviour {
public Rigidbody PlayerRB;
public float jumpHeight = 5f;
void Start ()
{
PlayerRB = GetComponent<Rigidbody>();
}
void Update ()
{
if (Input.GetButtonDown("Jump"))
PlayerRB.velocity = new Vector3(0, jumpHeight, 0);
}
}
I've been trying to write something like this to detect the player's velocity
void Update ()
{
if (Input.GetButtonDown("Jump")) && PlayerRB.velocity == 0);
PlayerRB.velocity = new Vector3(0, jumpHeight, 0);
}
I've added (PlayerRB.velocity == 0) but this gives me errors. I've tried different ways of writting it...but I'm very new to C# so I really don't have a clue. Thanks guys!
Answer by Dave-Carlile · Oct 14, 2015 at 02:13 PM
Velocity is a Vector3. Among other things it has fields for x, y, z. This is why when you create a vector you code things like PlayerRB.velocity = new Vector3(0, jumpHeight, 0);
. The first 0 is the x vector component, jumpHeight is y, and the final 0 is z.
You can examine one of those fields like this...
float y = PlayerRB.velocity.y;
That gives you the value for y. Then you can compare it just like any other float variable. You can also just check it directly...
if (PlayerRB.velocity.y == 0)
{
... do something ...
}
Now, generally you don't want to compare floating point values for equality. Because of precision errors the value might be something like 0.0000001. This is effectively 0 when it comes to speed, but if you try to see if it's equal to 0 that will be false. A better way to do this comparison is to use the Mathf.Approximately function to do the comparison...
if (Mathf.Approximately(PlayerRB.velocity.y, 0))
{
}
This will compare the value of velocity.y to 0 and return true if it's closer than some very small value.
Answer by GaryOPostle · Jun 21, 2017 at 10:04 PM
I know this question is old but I just googled it myself and then found out the answer so, you can just compare the velocity to Vector3.zero;
void Update () { if (Input.GetButtonDown("Jump")) && PlayerRB.velocity == Vector3.zero);
PlayerRB.velocity = new Vector3(0, jumpHeight, 0); }
You should Never compare a velocity (or anything) directly to vector3.zero (similar like checking if some float is == 0.0.. no!) Also, you are manipulating the velocity of your rigid body directly, from the docs:
"In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour"
Also; do it in FixedUpdate !