I am trying to detect if a user is grounded. I have a GameObject
on the screen with a BoxCollider2D
component on it and is on the Ground
Layer. I then have a character with a Rigidbody2D
and CircleCollider2D
on it along with this class:
public class CharacterEnvironment : MonoBehaviour {
float distToGround;
// Use this for initialization
void Start() {
var collider = GetComponent<CircleCollider2D>();
distToGround = collider.bounds.extents.y;
}
// Update is called once per frame
void Update() {
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, distToGround + 0.1f, LayerMask.NameToLayer("Ground"));
Debug.Log(hit.collider);
if (hit && hit.collider != null) {
Debug.Log(hit.collider);
}
}
}
When my raycast runs, hit.collider
is always null
, even when the object is resting on top of the Ground Object. Am I doing the calculations wrong?
Edit: I have added the check for hit
in the if statement.