Jump to content
  • Advertisement
Sign in to follow this  
Ovicior

Unity How To Check If Grounded In 2D Unity Game?

This topic is 956 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);
    }
}
Edited by Ovicior

Share this post


Link to post
Share on other sites
Advertisement

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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites


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.

Share this post


Link to post
Share on other sites

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. Edited by Nypyren

Share this post


Link to post
Share on other sites

 


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. 

Share this post


Link to post
Share on other sites

 

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.

Share this post


Link to post
Share on other sites

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 Edited by HappyCoder

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!