[英]Detect collision between player and ground Unity3D
我仍在學習Unity,現在我正在嘗試使我的播放器能夠跳躍。 當然,我不希望我的播放器永遠跳下去,所以我的想法是僅在播放器與地板物體接觸時才啟用跳動。 這是我到目前為止的代碼:
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);
請給我們更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.