我试图让玩家不连续跳跃,所以我使用 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;
}
}
}
问题是当玩家站在 Platform01 上时,显然 isOnGrounded = true
并且当玩家移出 Platform01 isOnGrounded = false
时,我想当移动到 Platform02 时它会自动检查 Ground
和 isOnGrounded = 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/