- Home /
I Can't Jump, And If I Remove if(isGrounded) I Can Do More Then 10 Jumps IN The Air
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Movement : MonoBehaviour {
public float Speed;
public float JumpForce;
bool isGrounded = false;
private Rigidbody2D rb;
float movX;
// Use this for initialization
void Start ()
{
rb = GetComponent<Rigidbody2D>();
}
void Update ()
{
movX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2 (movX * Speed, rb.velocity.y);
if(Input.GetKeyDown(KeyCode.Space))
{
if(isGrounded)
jump ();
}
}
void jump()
{
rb.AddForce (transform.up * JumpForce);
isGrounded = false;
}
private void OnCollisioneEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "ground")
{
isGrounded = true;
}
}
}
One thing that is sticking out is a typo: OnCollisioneEnter2D
-> OnCollisionEnter2D
(note the extra "e" in the first one).
Things to check: Is the collision occurring? Is everything tagged correctly? Try adding some logging like this to see if it helps you find the issue:
private void OnCollisionEnter2D(Collision2D collision)
{
var other = collision.gameObject;
Debug.Log($"{name} (tag = {tag} colliding with {other.name} (tag = {other.tag})");
if (collision.gameObject.tag == "ground")
{
isGrounded = true;
}
}
You're not alone, I too have banged my head into the wall for quite a while only to find the solution was that I forgot to tag one of my GameObjects or misspelled a lifecycle method :) Hope this helps!
Answer by N-8-D-e-v · Jun 05, 2020 at 06:59 PM
make sure to tag your ground as "ground", oncollisionenter2d is spelled wrong, and also I wouldn't do it this way, as it normally doesnt work. Instead either raycast, https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html or create an empty gameobject as a child of the player at his/her feet, and put a collider on it to do a ground check