Ground Detection

I’m trying to detect ground, on both platforms and the main ground, in my 2d game. So, What I’ve done is given all of my platforms and my main ground the tag “ground”. However, I can’t seem to get my IsGrounded() method to work. Can someone help me out?..

bool IsGrounded()
	{
		foreach(GameObject groudnObj in GameObject.FindGameObjectsWithTag("ground")){
			if(Vector3.Distance(collider2D.transform.position, groudnObj.collider2D.transform.position) < 2f){
				if(groudnObj.collider2D.transform.position.y < this.collider2D.transform.position.y){
					return true;
				}
			}
		}
		return false;
	}

2 Answers

2

For ground detection i’ll recommend use linecast

Or you may attach empty gameobject with trigger collider to your character and use it as ground detector.

Here’s example project Unity Asset Store - The Best Assets for Game Making

btw, checking all objects is a bad idea)

Thank you! Linecast is what i was looking for :) The documentation on the new 2d system isn't very good yet.

Hi,

  • add box colliders to the payers feet.

  • Switch on ‘Is Trigger’

  • add a script like this:

     using UnityEngine;
     using System.Collections;
     
     public class DetectGroundHit : MonoBehaviour {
             public PlayerController refPlayerController;
             
             void OnTriggerEnter() {
             	if (refPlayerController) {
             		refPlayerController.groundHitYN=true;
             	}
             }
             
             void OnTriggerStay() {
             	if (refPlayerController) {
             		refPlayerController.groundHitYN=true;
             	}
             }
             
             void OnTriggerExit() {
             	if (refPlayerController) {
             		refPlayerController.groundHitYN=false;
             	}
             }
     }
    
  • the script PlayerController is applied to the Player Object. This script has a public bool which is set when the player hits a ground object.

  • add to the platforms and main ground box colliders or mesh colliders.

Is that what you need?

All the best,
Klaus

This worked splendidly for me, simple and agile if u put it on a distinct gameObject that u can move around, thanks man.