How can i stop a character from double jumping?

ε祈祈猫儿з 提交于 2021-01-28 06:01:09

问题


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);

    }




}
}

回答1:


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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/44296313/how-can-i-stop-a-character-from-double-jumping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!