I’ve recently started trying to learn Unity again and so far I’ve gotten some basic movements done including a jump, however I can just keep pressing the jump button to go higher and higher, I don’t want to be able to jump unless the player object is touching the ground object, I’ve done a lot of googling but I couldn’t figure anything out. Heres the code i’m written so far
Rigidbody2D rb;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
public float moveSpeed = 2.0f;
public float jumpHeight = 200.0f;
// Update is called once per frame
void Update () {
var left = Input.GetKey(KeyCode.A);
var right = Input.GetKey(KeyCode.D);
var jump = Input.GetKeyDown(KeyCode.Space);
if (left) {
transform.Translate(Vector2.left * moveSpeed * Time.deltaTime);
}
if (right)
{
transform.Translate(Vector2.right * moveSpeed * Time.deltaTime);
}
if (jump) {
rb.AddForce(transform.up * jumpHeight, ForceMode2D.Force);
}
}