Why isn't my jumping script working?
Okay, so I am currently working on a game with a character that I want to be able to jump only once until he hits the ground again so I wrote a code to make him do exactly that but now he can only jump once the whole entire game. Here is the code I used.
bool isgrounded = true;
void Update () {
if (isgrounded == true) {
if (Input.GetKeyDown(KeyCode.Space)) {
GetComponent<Rigidbody2D>().velocity = new Vector2 (0f, 7f);
isgrounded = false;
}
}
}
void OnCollisionEnter2D (Collision2D coll) {
if (coll.gameObject.tag == "GroundCollider") {
isgrounded = true;
}
}
Answer by akillingbeck · Aug 25, 2017 at 01:41 PM
Your solution is in your error:
void OnCollisionEnter2D (Collider2D coll) {
Should be
void OnCollisionEnter2D (Collision2D coll) {
See: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html
Oh wow, did I really write Collider2D? You can tell I'm not the best at this.
@akillingbeck Replacing Collider2D with Collision2D removed the error but I can still only jump once through the whole game.
If your collisions are working correctly, then this could be caused by a collider which is not "GroundCollider" and is blocking your player from reaching a GroundCollider.
Add a Debug.Log(string.Format("OnCollisionEnter2D : I got hit by {0}",coll.gameObject.name));
Inside your OnCollisionEnter2D function. If nothing prints in the Unity console, you haven't setup properly (check docs). If it does print and it's not the object with the correct tag, you can look at the Edit->Proect Settings->Physics matrix to avoid certain layers colliding with other layers.
@akillingbeck I played around with the physics matrix a bit and still nothing, I did get a message in the console whenever I hit ground collider though.