I’m writing a 2D platformer and I’m trying to make it so that the player can’t jump in mid-air. I did this with the boolean “grounded”, which is required to be true so the player can jump, enables when the player touches a platform and disables after the player jumps. However, when I run the program, the character just infinitely jumps without any input.
public class PlayerMovement : MonoBehaviour {
private Rigidbody2D rb2d;
public float speed;
public float jumppower;
public float dashpower;
private bool grounded;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>();
transform.position = Vector2.zero;
grounded = true;
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.LeftArrow))
rb2d.AddForce (Vector2.left * speed * Time.deltaTime);
if (Input.GetKey (KeyCode.RightArrow))
rb2d.AddForce (Vector2.right * speed * Time.deltaTime);
if (Input.GetKeyDown (KeyCode.Space) && (grounded == true))
Debug.Log ("Off Ground.");
grounded = false;
rb2d.AddForce (Vector2.up * jumppower * Time.deltaTime);
if (Input.GetKeyDown (KeyCode.D))
rb2d.AddForce (Vector2.right * dashpower);
if (Input.GetKeyDown (KeyCode.A))
rb2d.AddForce (Vector2.left * dashpower);
if (Input.GetKeyDown (KeyCode.R))
transform.position = Vector2.zero;
}
void OnColliderEnter (Collider other) {
if (other.gameObject.CompareTag ("Platform"))
Debug.Log ("Ground.");
grounded = true;
}
}