0
我仍在學習Unity,現在我正試圖讓我的玩家能夠跳躍。當然,我不希望我的球員能夠永遠跳下去,所以我的想法是隻有當球員與地板對象接觸時才能跳躍。這是我到目前爲止的代碼:檢測玩家與地面之間的碰撞Unity3D
public class PlayerController : NetworkBehaviour
{
public float speed; // Player movement speed
private bool grounded = true; // Contact with floor
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Show a different color for local player to recognise its character
public override void OnStartLocalPlayer()
{
GetComponent<MeshRenderer>().material.color = Color.red;
}
// Detect collision with floor
void OnCollisionEnter(Collision hit)
{
if (hit.gameObject.tag == "Ground")
{
grounded = true;
}
}
// Detect collision exit with floor
void OnCollisionExit(Collision hit)
{
if (hit.gameObject.tag == "Ground")
{
grounded = false;
}
}
void FixedUpdate()
{
// Make sure only local player can control the character
if (!isLocalPlayer)
return;
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
// Detect space key press and allow jump if collision with ground is true
if (Input.GetKey("space") && grounded == true)
{
rb.AddForce(new Vector3(0, 1.0f, 0), ForceMode.Impulse);
}
}
}
但似乎OnCollisionEnter
和OnCollisionExit
從未被觸發。所以玩家仍然能夠隨時跳躍。難道我做錯了什麼?
編輯:看來OnCollisionEnter
和OnCollisionExit
觸發完全正常。只是if語句返回false。但我不知道爲什麼。
if (GameObject.Find("Ground") != null)
返回true。
編輯2:奇怪的是這兩個返回Untagged
:
Debug.Log(hit.gameObject.tag);
Debug.Log(hit.collider.tag);
原來我把對象名稱和對象標籤搞混了。地面物體根本沒有標籤。我已經添加了該標籤,並且一切都很完美!我正準備自己回答,但我會接受你的:) – icecub
謝謝。與您的項目一切順利 –