user8077453
user8077453

Reputation: 15

How can i stop a character from double jumping?

I'm trying to make the character stop jumping when in the air, but the problem is that it can jump when colliding with walls.

So i tried to make a certain amount of time pass by before the character could jump again in the script below, but for some reason it doesn't work.

If anyone has any more efficient ways of doing this i would definitely appreciate it.

using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

public class PlayerMovement : MonoBehaviour {

public float UpSpeed;
public Rigidbody rb;
public float horizonSpeed;

public bool isGrounded;

public float gravInc = 50;
public int counter;
public float DownSpeed = 50;

public int jumpCount = 0;
public float secCount = 0;
public bool validUp = true;
public float sec;


public void OnCollisionStay(Collision collision)


{
    isGrounded = true;
}

public void OnCollisionExit(Collision collision)
{
    isGrounded = false;
}


public void Start()
{
    rb = GetComponent<Rigidbody>();


}
private void Update()
{



        if (secCount == (sec))
        {
            validUp = true;

        }


    sec = Time.time;

    if (Input.GetKeyDown ("up") && isGrounded == (true) && validUp == (true))
    {
        rb.AddForce(transform.up * UpSpeed);
        secCount = 0;
        validUp = false;
        secCount = sec + 3;



    }

    else if(Input.GetKeyDown ("right"))
    {
        horizonSpeed = 200;
        rb.AddForce(transform.right * horizonSpeed);
    }
    else if (Input.GetKeyDown ("left"))
    {
        horizonSpeed = -200;
        rb.AddForce(transform.right * horizonSpeed);

    }




}
}

Upvotes: 1

Views: 3838

Answers (2)

Daahrien
Daahrien

Reputation: 10320

You have to make a different collider that sits on the feet of your player (also smaller). Make it a trigger.

And use OnTriggerStay to set its isGrounded variable to true, and OnTriggerExit to set it to false.

void OnTriggerStay(Collider other){
    isGrounded = true;
}

void OnTriggerExit(Collider other){
    isGrounded = false;
}

Upvotes: 4

King Dedede
King Dedede

Reputation: 1010

I've encountered this issue before - defining an invisible "valid ground" layer on all valid surfaces that must be contacted to jump would help more than a timing thing.

If you just use timing, someone could double (or triple!) jump if they jump off a cliff or down a hill. Walls would not have the valid surface object on them, so the player couldn't jump against walls.

By using valid surface identifiers, you can also make surfaces that are designed to be slid down without allowing jumping.

Upvotes: 2

Related Questions