Skip to content

Instantly share code, notes, and snippets.

@2A5F
Last active March 21, 2019 08:25
Show Gist options
  • Save 2A5F/b5b00f05fe4b194930b3f0bd25da7ba6 to your computer and use it in GitHub Desktop.
Save 2A5F/b5b00f05fe4b194930b3f0bd25da7ba6 to your computer and use it in GitHub Desktop.
Unity2d GroundCheck
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class GroundCheck : MonoBehaviour
{
public bool is_on_ground = false;
[Range(0, 90)]
public float MaxAngle = 45;
private BoxCollider2D self;
void Start()
{
self = GetComponent<BoxCollider2D>();
self.isTrigger = true;
}
void FixedUpdate()
{
var pos = new Vector2(transform.position.x, transform.position.y);
var hits = Physics2D.BoxCastAll(pos - self.offset, self.size, 0, Vector2.down, self.size.y);
foreach (var item in hits)
{
if (item.transform.gameObject.tag == "Player") continue;
var angle = Mathf.Atan2(item.normal.x, item.normal.y) * (180 / Mathf.PI);
var fixedangle = Mathf.Abs(angle);
if (fixedangle < MaxAngle)
{
is_on_ground = true;
return;
}
}
is_on_ground = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment