- Home /
Question by
EndOfAnEmpire · Feb 10, 2020 at 10:59 PM ·
2d-platformer2d-physics2d-gameplay
How to check if a 2D player collider is touching the ground/platform?
I'm trying to check if a player is touching the ground in order to turn on or off the jump script in a 2D platform game. I tried a few things but all of them seem to be failing. This is my recent attempt:
public Collider2D playerjumpcollider;
public Collider2D groundCollider;
void Start()
{
playerjumpcollider = GameObject.FindGameObjectWithTag("Player").GetComponent<Collider2D>();
groundCollider = GameObject.FindGameObjectWithTag("Ground").GetComponent<Collider2D>();
}
void Jump() { if (Input.GetButtonDown("Jump")) { if (playerjumpcollider.IsTouching(groundCollider)) { player.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse); } } }
Comment
Best Answer
Answer by Anis1808 · Feb 11, 2020 at 03:35 AM
You can simply create a script that you attach to your player for example "PlayerCollision" :
public bool isGrounded = false;
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.tag == "Ground"){
isGrounded = true;
}
}
void OnCollisionExit2D(Collision2D col)
{
if(col.gameObject.tag == "Ground"){
isGrounded = false;
}
}
Then you would simply call the variable isGrounded using GetComponent().isGrounded;