我試圖讓玩家不連續跳躍,所以我使用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
并且當玩家移出 Platform01isOnGrounded = false
時,我想當移入 Platform02 時它會自動檢查Ground
,isOnGrounded = true
但它仍然false
和一切都搞砸了。
uj5u.com熱心網友回復:
這是因為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;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/536471.html
標籤:C#unity3d