C#C
C#3y ago
emmap

❔ Newbie Q: Preventing double jump in unity

Im making a platformer game and I want to prevent my character from jumping more than once. So I created a seperate game object that will follow its feet. When it collides with the ground, it will set onGround to true in the player movement script. When onGround is true, then the character can jump. But this is not working. Here is the code: Player Movement - component of the player object:
public class CatMovement : MonoBehaviour
{
    public bool OnGround = true;

    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        Rigidbody2D body = GetComponent<Rigidbody2D>();
        if (Input.GetKey(KeyCode.UpArrow) && OnGround)
        {
            // Getting the rigidbody component of the sprite - vector 3 since using 3 values (x,y,z) 
            // GetComponent<Rigidbody2D>().velocity = new Vector3(0, 10, 0);
            body.AddRelativeForce(new Vector2(0, 1000));
            this.OnGround = false;
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            body.AddRelativeForce(new Vector2(50, 0));
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            body.AddRelativeForce(new Vector2(-50, 0));
        }
    }
}

Ground Detection - component of the feet object:
public class GroundDetection : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        GameObject cat = GameObject.FindWithTag("Cat");
        transform.position = cat.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
    }
    void OnCollisionEnter2D(Collision2D col)
    {
        Debug.Log("Ok");
        CatMovement movement = GetComponent<CatMovement>();
        movement.OnGround = true;
    }
}
Was this page helpful?