Vilmis
Vilmis

Reputation: 55

Unity2D preventing character from multi-jumping

My character can jump as much as you press ( W or space) I've read that you can prevent it with Raycast, but I don't understand how to do so. This is my character's code(this is a platformer game) :

private Rigidbody2D myRigidBody2D;
void Start () {

    myRigidBody2D = GetComponent<Rigidbody2D>();

}

private void Update()
{
    if (Input.GetButtonDown("Jump"))
    {
        myRigidBody2D.AddForce(new Vector2(0, jumpForce));
    }
}

Upvotes: 1

Views: 1570

Answers (1)

Programmer
Programmer

Reputation: 125455

I've read that you can prevent it with Raycast

Yes, you can but you will likely run into problems which can still be fixed.

The best way to do this is to use a boolean variable to check if the character is touching the ground or not. You can set this variable to true or false in the OnCollisionEnter2D and OnCollisionExit2D functions.

Create a tag called "Ground". Change all your ground Gameobjects to this tag then the example below should prevent multiple jumping.

bool isGrounded = true;

private float jumpForce = 2f;
private Rigidbody2D myRigidBody2D;

void Start()
{

    myRigidBody2D = GetComponent<Rigidbody2D>();

}

private void Update()
{
    if (Input.GetButtonDown("Jump") && isGrounded)
    {
        myRigidBody2D.AddForce(new Vector2(0, jumpForce));
    }
}

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = true;
    }
}

void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = false;
    }
}

Upvotes: 3

Related Questions