Detect collision between player and ground
I'm still learning Unity and right now I'm trying to make my player able to jump. Of course I don't want my player to be able to jump on forever, so my idea was to only enable jumping when the player is in contact with a floor object. This is the code I have so far:
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);
}
}
}
But it seems OnCollisionEnter and OnCollisionExit never trigger. So the player is still able to jump whenever he wants. Am I doing something wrong?
Edit: After some debugging it seems both OnCollisionEnter and OnCollisionExit work perfectly fine. It's the if statements returning false. I checked if the Ground object actually exists, just to be sure with:
if (GameObject.Find("Ground") != null){ Debug.Log("ground found"); }
But that returned true just as expected. So there's something else going on.
Edit 2: Strangely enough both these seem to return "Untagged":
Debug.Log(hit.gameObject.tag);
Debug.Log(hit.collider.tag);
Why are you using Fixed Update to get inputs? Use Update()
As I said, I'm still learning. And this is what's inside Unity's first official tutorial. So I expected it to be correct that way. Anyway, I've done what you advised. It doesn't solve my issue though :)
Answer by Veerababu.g · Mar 28, 2016 at 07:24 AM
make sure about the tag once.I mean the tag what you write is same as what you given in inspector
I did. The tag is the same and it also exists. Ins$$anonymous$$d I've tried to debug it by letting it tell me which tag is being returned on collision. But all I get is "Untagged". And I'm 100% it is tagged, haha.
You were partly right actually! It turned out I was confusing the objects name with the objects tag! So the object really didn't have a tag at all. I've added the tag and it works perfectly fine!