Unity2d - Help with player class.

Hey, what’s a better method for checking if the player is grounded? I shouldn’t be checking Y velocity because i get velocity at times even when walking on flat surfaces.

thanks.

    using UnityEngine;
using System.Collections;

public class player : MonoBehaviour {

	public float speed = 0.05f;
	public float jumpVelocity = 0.05f;

	public bool onGround = true;
	public bool jumped = false;

	public float timer = 0.0f;
	public float timerMax = 3.0f;

	// Use this for initialization
	void Start () {

	
	}
	
	// Update is called once per frame
	void Update () {
		 
		//DEBUG
		print(this.rigidbody2D.velocity.y);

		//test if player is on the ground

		if (this.rigidbody2D.velocity.y == 0.0f) {

						onGround = true;

				} else {

			onGround = false;
			
		}
		
		if (Input.GetKeyDown(KeyCode.Space) && onGround == true) {

			     jumped = true;
			     

			while(jumped) 
			{

				timer += Time.deltaTime;
				this.rigidbody2D.AddForce(new Vector2(0, jumpVelocity));

				if(timer >= timerMax)
				{

					jumped = false;
					timer = 0.0f;

				}

			
			}

		}else if(Input.GetKey(KeyCode.RightArrow))
		{

			this.transform.position += Vector3.right * speed * Time.deltaTime;

		}else if(Input.GetKey(KeyCode.LeftArrow))
		{
			
			this.transform.position += Vector3.left * speed * Time.deltaTime;
			
		}

	
	}

You’ll also get 0 velocity at the top of a jump.

Most common practice is to use a trigger collider placed near the characters feet. If that collider is in contact with ground then you are good to go.

You can also use short raycasts to detect ground. May be more performant if you only need ground checks occasionally.