I. Jones I. Jones - 4 months ago 11
C# Question

When a cube is moving how can I make it so that it can't jump when it is in the air?

I have a cube that is on the scene and when you press one of the arrow keys it moves up and in the direction of the arrow key. When you click while the cube is already in the air it jumps again before it gets back to the ground. How do I make it so that the cube can't jump again until it is back on the ground? This is my code so far:

public class MovePlayer : MonoBehaviour {

Vector3 endPos;
Vector3 startPos;


bool jumping = false;

// Update is called once per frame
void Update () {
endPos = gameObject.transform.position;
startPos = gameObject.transform.position;

if (Input.GetButtonDown ("up") && gameObject.transform.position == endPos) {

transform.Translate(Vector3.up * 50 * Time.deltaTime, Space.World);
transform.Translate(Vector3.forward * 50 * Time.deltaTime, Space.World);
}
else if (Input.GetButtonDown ("down") && gameObject.transform.position == endPos) {
transform.Translate(Vector3.up * 50 * Time.deltaTime, Space.World);
transform.Translate(-Vector3.forward * 50 * Time.deltaTime, Space.World);
}
else if (Input.GetButtonDown ("left") && gameObject.transform.position == endPos) {
transform.Translate(Vector3.up * 50 * Time.deltaTime, Space.World);
transform.Translate(Vector3.left * 50 * Time.deltaTime, Space.World);
}
else if (Input.GetButtonDown ("right") && gameObject.transform.position == endPos) {
transform.Translate(Vector3.up * 50 * Time.deltaTime, Space.World);
transform.Translate(Vector3.right * 50 * Time.deltaTime, Space.World);
}

}
}

SP. SP.
Answer

Make the Boolean jumping false if the player is in contact/colliding with the ground. If not make it true. Then add and check it with the jump input condition so true will not let jump and false will let jump.

For detecting ground use some code like below. Tag the ground as you want. Both player and ground will need collider component and at least one of them will need Rigidbody component attached.

void OnCollisionEnter (Collision other)
{
 if (other.collider.tag == "ground_tag")
{
 Jumping = false;
}
}

void OnCollisionExit (Collision other)
{
 if (other.collider.tag == "ground_tag")
{
 Jumping = true;
}
}