- Home /
How to jump on only "ground" colliders
Hey guys, so i think im having an issue with my ground check not working the way i want. The player seems to do well with not continuously jumping when in the air. My problem is that if my player interacts with any "collider", it treats it like its the ground and can jump off of them. This includes enemy AI and collectible coins. I dont really blame my script cause that seems to be what im telling it to do. How to I specify that the platforms are "ground" and the coins and enemies are not "ground"? I even made the Layer of my platforms called "Ground" but im not sure how to reference it in my script. Any ideas?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GroundCheck : MonoBehaviour {
private Player player;
void Start()
{
player = gameObject.GetComponentInParent<Player>();
}
void OnTriggerEnter2D(Collider2D col)
{
player.grounded = true;
}
void OnTriggerStay2D(Collider2D col)
{
player.grounded = true;
}
void OnTriggerExit2D(Collider2D col)
{
player.grounded = false;
}
}
Answer by Phantom_101 · Sep 24, 2017 at 07:41 PM
The above code is wrong. If the player touches anything, then the player is grounded. I don't think you would want that. What you need to do is to add a tag (e.g. "ground" or "jumpable") and try to find it when OnColliderEnter or OnColliderExit is called. I don't have a clue as to why you did -->Trigger<-- instead of -->Collider<--. Here's a sample:
private bool isGrounded;
void Update(){
if(Input.GetKeyDown(KeyCode.Space)){
if(isGrounded){
//jump
}
}
}
void OnCollisionEnter(Collider other){
if(other.tag == "ground"){
isGrounded = true;
}
}
void OnCollisionExit(Collider other){
if(other.tag == "ground"){
isGrounded = false;
}
}
You are exactly right with everything the player touches making it "grounded", no idea why they are doing that in the tutorial im following. I added your code and it has no errors. Now i took my platform and added a Tag called "ground" like you mention in the script and added it to the platform. The only problem is that the player jumps when ever the space bar is pressed. So even if im in the air, i can press the space bar and he can keep jumping. Any idea?
Oops... Think I made a mistake. For the OnCollision methods, the parameter type should be of Collision ins$$anonymous$$d of Collider. After you've changed it, be sure to use other.gameObject.tag. See if it works now.
Yep. I tested it and it worked. And then I started playing around with 2D area effecters lol. It should be fine for you now. Sorry about the late replies.
Your answer
Follow this Question
Related Questions
Grounded check not working on sloped ground. 1 Answer
Jump if ground is detected 1 Answer
How to set up line cast for two groundchecks? 0 Answers
How to only Jump on Ground Items 1 Answer