【发布时间】:2016-03-28 15:40:42
【问题描述】:
我还在学习 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);
【问题讨论】: