简体   繁体   中英

I'm trying to get my cube to only jump on the ground but my if statement isn't working

public Rigidbody rb;
public bool cubeIsOnTheGround = true;
public float speed = 10;

Vector3 direction;

// Start is called before the first frame update
void Start()
{
    rb.GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update()
{
    Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
    direction = input.normalized;
    
    if (Input.GetButtonDown("Jump"))
    {
        rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
    }

    if (cubeIsOnTheGround == true)
    {
        if (Input.GetButtonDown("Jump"))
        {
            rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
            cubeIsOnTheGround = false;
        }
    }
}

void FixedUpdate()
{
    rb.position += direction * speed * Time.deltaTime;
}

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        cubeIsOnTheGround = true;
    }
}

The if statemnt boolIsOnTheGround is not working. What I'm trying to do is check whether the cube is on the ground so I kno when you can jump. The cube just bounces infinitely by pressing space.

In your code you have two if-blocks where you jump:

    if (Input.GetButtonDown("Jump"))
    {
        rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
    }

    if (cubeIsOnTheGround == true)
    {
        if (Input.GetButtonDown("Jump"))
        {
            rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
            cubeIsOnTheGround = false;
        }
    }

The first if-block does not check cubeIsOnTheGround , so it will jump as long as the jump button is pressed. If you remove the first block this behavior should stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM