我还在学习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);
答案 0 :(得分:1)
请提供更多信息