How To Check If Grounded In 2D Unity Game?

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

Have you seen this one yet?

http://unity3d.com/learn/tutorials/modules/beginner/2d/2d-controllers

It explains it really nice.

Advertisement

Have you seen this one yet?

http://unity3d.com/learn/tutorials/modules/beginner/2d/2d-controllers

It explains it really nice.

I've watched it a few times, and pulled some stuff from it.

What will you make?

Everyone, I figured it out. I used a empty object, attached it to the bottom of the player, then assigned it to a public variable.


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?

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

Nice. I think I'll try that out.

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.

What method do you use for leaving the grounded state with that method? I'm catching groundedness in OnCollisionStay() and setting grounded to false at the end of FixedUpdate(), but there's some noticeable latency when landing. I considered using OnCollisionEnter() and OnCollisionExit(), but the exit could potentially incorrectly set grounded to false when walking between colliders horizontally.

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.

What method do you use for leaving the grounded state with that method? I'm catching groundedness in OnCollisionStay() and setting grounded to false at the end of FixedUpdate(), but there's some noticeable latency when landing. I considered using OnCollisionEnter() and OnCollisionExit(), but the exit could potentially incorrectly set grounded to false when walking between colliders horizontally.

I'm not using a method. Just this line of code. It's not the best way to do it, but it works.


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

Sources:

https://www.reddit.com/r/Unity2D/comments/3vo60j/how_to_prevent_multiple_jumps_in_2d_game_c/

^^This is the one I used.

What will you make?

Yeah. I was using a sensor before, but I'm checking out the contact normal method that Happy was talking about.

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.


What method do you use for leaving the grounded state with that method?

I honestly haven't tried it in 2D. My old character controller in 3D works on the same principle, and there's no really noticeable latency (but PhysX may deal with contacts differently to Box2D).

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

This topic is closed to new replies.

Advertisement