[英]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.