Z
Z
zhqrik2018-03-31 09:55:15
C++ / C#
zhqrik, 2018-03-31 09:55:15

How to prevent multiple jump in Unity?

Here is the code, please fix it!
If you press the spacebar, the character flies, what should I do?

using UnityEngine;

public class PlayerContrl : MonoBehaviour {
    public float speed = 20f;
    private Rigidbody2D rb;
  // Use this for initialization
  void Start () {
        rb = GetComponent<Rigidbody2D>();
  }
  
  // Update is called once per frame
  void Update () {
        float moveX = Input.GetAxis ("Horizontal");
        rb.MovePosition(rb.position + Vector2.right * moveX * speed * Time.deltaTime);
        if (Input.GetKeyDown(KeyCode.Space))
            rb.AddForce(Vector2.up * 7500);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2018-03-31
@zhqrik

Did you watch the official tutorial ? In short, you need to use raycasts or, for example, OnCollisionStay to determine the proximity of the ground relative to your character. When the character is not on the ground - forbid jumping.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question