OnEnterCollision2D 和 OnExitCollision2D 不工作 Unity C#

问题描述 投票:0回答:1

正如您在图片中看到的那样,立方体仍然与方块发生碰撞,但在控制台中,您可以看到一条消息说 false。那就是 isGrounded 变量。我不能跳,因为 isGrounded 是假的。这是附在立方体上的代码脚本:

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

public class Cube1 : MonoBehaviour
{
    public float jumpForce = 7.0f;
    private bool isGrounded = true;

    private Rigidbody2D rb;
    private AudioSource audio;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        audio = GetComponent<AudioSource>();
    }

    void Update()
    {
        if (isGrounded && (Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0)))
        {
            audio.Play();

            rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);

            Debug.Log("Works");

            isGrounded = false;
        }

        Debug.Log(isGrounded);
    }

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

        string collider = other.gameObject.name;

        if (collider == "leftCollider" || collider == "rightCollider" || collider == "bottomCollider" || other.gameObject.CompareTag("Spike") || other.gameObject.CompareTag("Thorn"))
        {
            GameOver();
        }
    }

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

    public void GameOver()
    {
        if (MyVariables.highScore < (int)MyVariables.score)
        {
            MyVariables.highScore = (int)MyVariables.score;
        }
        MyVariables.score = 0;
        MyVariables.obstacleCount = 0;
        Time.timeScale = 1f;
        SceneManager.LoadScene("Menu");
    }
}

谁能帮我解决这个问题?

c# collision-detection unityscript unity-editor
1个回答
0
投票

看起来您正在检查方块的标签是否与“地面”标签以及“方块”标签发生碰撞,但在游戏中,玩家对象仅与其中一个标签发生碰撞,并且没有将 isGrounded 设置为 true,因为您可以看到调用 OnCollisionEnter 函数的位置 而不是检查玩家是否与标签“Ground”和标签“block”发生碰撞,您需要检查一个或另一个,如下所示

if (other.gameObject.CompareTag("Ground"))
{
    isGrounded = true;
}

或者,您也可以使用向下延伸的 boxcast 作为地面检查器,以检查您是否正在触摸盒子,如果您担心程序在您的玩家触摸地面的一侧时意外设置 isGrounded = true,则效果会更好对象如下所示

private bool IsGrounded()
{
      return Physics2D.CapsuleCast(coll.bounds.center, coll.bounds.size, 
      0f, 0, Vector2.down, .1f, Ground);
}

上面的程序将检查玩家是否在他们正下方有地面,方法是在他们正下方创建一个 boxcast,然后检查每一帧是否该框与标记有地面标签的游戏对象重叠

© www.soinside.com 2019 - 2024. All rights reserved.