How To Check If Grounded In 2D Unity Game?

Started by
16 comments, last by swiftcoder 8 years, 4 months ago

Hey,

I've implemented jumping and moving in my game, but want to prevent infinite jumping. I've tried to integrate a few systems into my game, but have been unable to do so. Can anyone help?


using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{

    private float moveSpeed = 5f;
    private float jumpHeight = 300f;
    private Rigidbody2D rigidBody;

    // Use this for initialization
    void Start()
    {
        rigidBody = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f)
        {
            transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
        }

        if (Input.GetKeyDown(KeyCode.W))
        {
            rigidBody.AddForce(new Vector2(0, jumpHeight));
        }
    }
}

EDIT: Found a solution. Create an empty, make it child of player, then place it where the feet are. Here's the code I used. You have to give all ground a layer, and put that layer in this script.


using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    //Variables for general movement.
    private float moveSpeed = 5f;
    private float jumpHeight = 300f;
    private Rigidbody2D rigidBody;

    //Variables for grounding system.
    public bool isGrounded;
    public Transform grounder;
    public float radius;
    public LayerMask ground;

    // Use this for initialization
    void Start()
    {
        rigidBody = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        //Were keys 'A' or 'D' pushed down?
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D))
        {
            //Move the object to it's current position * moveSpeed * time.deltaTime.
            transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
        }

        isGrounded = Physics2D.OverlapCircle(grounder.transform.position, radius, ground);

        //Was the key 'W' pushed down?
        if (Input.GetKeyDown(KeyCode.W) && isGrounded == true)
        {
            //Add force to the rigid body, none to the x-axis and jumpHeight to the y-axis.
            rigidBody.AddForce(new Vector2(0, jumpHeight));
        }
    }

    //Function which draws gizmos, showing the computer's calculations in the form of a sphere.
    void OnDrawGizmos()
    {
        //Color of gizmos is blue.
        Gizmos.color = Color.blue;
        //Gizmos is to draw a wire sphere using the grounder.transform's position, and the radius value.
        Gizmos.DrawWireSphere(grounder.transform.position, radius);
    }
}
What will you make?
Advertisement

One option is to do a (short) raycast downwards from the player. If you hit something, you're grounded.

Hello to all my stalkers.

One option is to do a (short) raycast downwards from the player. If you hit something, you're grounded.

Can you please paste some code that could do that? I'm not sure how that works (On the technical side. I understand the concept). It'd be amazing if you could integrate it into the code I pasted here, but I understand if you choose not to.

What will you make?

Unity provides a very simple way to do this - override OnCollisionStay2D(), check if the collider is a ground object, and use that to update some boolean isGrounded flag in your class.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Unity provides a very simple way to do this - override OnCollisionStay2D(), check if the collider is a ground object, and use that to update some boolean isGrounded flag in your class.

In order to do it that way you'd need to have ground colliders only on the tops of ground objects. Otherwise you'd be able to jump off the sides or bottom of things that are marked as ground.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.


In order to do it that way you'd need to have ground colliders only on the tops of ground objects. Otherwise you'd be able to jump off the sides or bottom of things that are marked as ground.

Aye, that's fair.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Unity provides a very simple way to do this - override OnCollisionStay2D(), check if the collider is a ground object, and use that to update some boolean isGrounded flag in your class.


In order to do it that way you'd need to have ground colliders only on the tops of ground objects. Otherwise you'd be able to jump off the sides or bottom of things that are marked as ground.


Sounds like a feature, not a bug! I love me some wall-jump.


In order to do it that way you'd need to have ground colliders only on the tops of ground objects. Otherwise you'd be able to jump off the sides or bottom of things that are marked as ground.

Aye, that's fair.

Yeah, but I don't want wall jumping. I'm building a little RPG where you can go left or right, and inside buildings if you want.

What will you make?

Unity provides a very simple way to do this - override OnCollisionStay2D(), check if the collider is a ground object, and use that to update some boolean isGrounded flag in your class.

In order to do it that way you'd need to have ground colliders only on the tops of ground objects. Otherwise you'd be able to jump off the sides or bottom of things that are marked as ground.

Not necessarily, you could stick some logic inside the OnCollisionStay to check that the ground is under the player.

Unity provides a very simple way to do this - override OnCollisionStay2D(), check if the collider is a ground object, and use that to update some boolean isGrounded flag in your class.


In order to do it that way you'd need to have ground colliders only on the tops of ground objects. Otherwise you'd be able to jump off the sides or bottom of things that are marked as ground.


You could just check the contacts in the Collision2D object. If one has a normal that is pointing up, then you are touching ground.

// a max slope of 30 degrees
private static float GroundAngleTolerance = Mathf.Cos(30.0f * Mathf.Deg2Rad);

void OnCollisionEnter2D(Collision2D coll) 
{
  foreach(ContactPoint2D contact in coll.contacts)
  {
    if (Vector3.Dot(contact.normal, Vector3.up) > GroundAngleTolerance)
    {
      // this collider is touching "ground"
    }
  }
}
EDIT: I quoted ground because this would consider any contact that touches the bottom of the player as ground
My current game project Platform RPG

This topic is closed to new replies.

Advertisement