c# - OnCollisionEnter2D 和 OnCollisionExit2D 的问题

标签 c# unity-game-engine

我试图让玩家不连续跳跃,所以我使用 isOnGrounded 变量来检查玩家是否在地面上。这是我的代码:

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

public class PlayerController : MonoBehaviour
{
    //REFERENCES
    private Rigidbody2D rb2D;
    //VARIABLES
    [SerializeField] float moveSpeed = 0;
    private float moveX;

    [SerializeField] bool isOnGrounded = true;
    [SerializeField] float jumpY;
    // Start is called before the first frame update
    void Start()
    {
        rb2D = GetComponent<Rigidbody2D>();
    }
    // Update is called once per frame
    void Update()
    {
        moveX = Input.GetAxis("Horizontal");
        PlayerJump();
    }
    private void FixedUpdate()
    {
        PlayerMove();

    }
    void PlayerMove()
    {
        rb2D.velocity = new Vector2(moveX * moveSpeed * Time.fixedDeltaTime, rb2D.velocity.y);

    }
    void PlayerJump()
    {
        if (Input.GetKeyDown(KeyCode.Space) && isOnGrounded == true)
        {
            rb2D.AddForce(new Vector2(rb2D.velocity.x, jumpY));
        }
    }
    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            isOnGrounded = true;
        }
    }
    private void OnCollisionExit2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            isOnGrounded = false;
        }
    }
}

enter image description here 问题是当玩家站在 Platform01 上时,显然 isOnGrounded = true 并且当玩家移出 Platform01 isOnGrounded = false 时,我想当移动到 Platform02 时它会自动检查 GroundisOnGrounded = true 但它仍然 false 并且一切都搞砸了。

最佳答案

这是因为 OnCollisionEnter2D(Platform02)OnCollisionExit2D(Platform01) 之前触发。

您可以记住最后一次碰撞的碰撞器,并在离开平台时与它进行比较。

public class PlayerController : MonoBehaviour
{
    private Collision2D ground;
    public bool IsGround => (bool)ground;

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            ground = other;
        }
    }
    private void OnCollisionExit2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground") && other == ground)
        {
            ground = null;
        }
    }
}

关于c# - OnCollisionEnter2D 和 OnCollisionExit2D 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74486174/

相关文章:

c# - WPF-创建可见性列表

c# - 如何创建一个对象的实例?

c# - Unity PUN RPC 来自另一个类的调用

c# - 从文件中提取体素坐标

c# - 在 Unity 中重命名序列化自动属性

c# - 有没有更好的方法来为队列实现 Remove 方法?

c# - 有没有办法执行以临时文件名存储的 exe?

c# - 无法通过 Windows 8.1 和 Windows 10 上的 Win32 API 从控制面板删除打印机

unity-game-engine - 脚本在 Unity3d 中不起作用

c# - 如何统一针对不同屏幕尺寸设置基于购物的 UI?