using UnityEngine; using System.Collections; public class CollisionState : MonoBehaviour { public LayerMask collisionLayer; public LayerMask enemyLayer; public bool onGround, onWall, onWallRight, onWallLeft; public Vector2 bottomPosition = Vector2.zero; public Vector2 rightPosition = Vector2.zero; public Vector2 leftPosition = Vector2.zero; public float collisionRadius = 1f; [HideInInspector]public Collider2D enemyHit; private InputState inputState; private Rigidbody2D body; private Animator animator; void Awake() { inputState = GetComponent(); body = GetComponent(); animator = GetComponentInChildren(); } void Update() { animator.SetBool("on ground", onGround); animator.SetBool("on wall", onWall); } void FixedUpdate() { enemyHit = null; // onGround = Physics2D.OverlapCircle(body.position + bottomPosition, collisionRadius, collisionLayer); // onWallLeft = Physics2D.OverlapCircle(body.position + leftPosition, collisionRadius, collisionLayer); // onWallRight = Physics2D.OverlapCircle(body.position + rightPosition, collisionRadius, collisionLayer); // onWall = onWallRight || onWallLeft; enemyHit = Physics2D.OverlapCircle(body.position + bottomPosition, collisionRadius, enemyLayer); } // void OnDrawGizmosSelected() { // Gizmos.color = Color.red; // Vector2 pos = bottomPosition; // pos.x += transform.position.x; // pos.y += transform.position.y; // Gizmos.DrawWireSphere(pos, collisionRadius); // pos = rightPosition; // pos.x += transform.position.x; // pos.y += transform.position.y; // Gizmos.DrawWireSphere(pos, collisionRadius); // pos = leftPosition; // pos.x += transform.position.x; // pos.y += transform.position.y; // Gizmos.DrawWireSphere(pos, collisionRadius); // } float lastFixedTime; void OnCollisionStay2D(Collision2D collision) { if (Time.fixedTime != lastFixedTime) { // only reset flags at the start of each frame // (OnCollisionStay2D is called once for every collider this body is in contact with) onGround = false; onWallLeft = false; onWallRight = false; lastFixedTime = Time.fixedTime; } foreach (ContactPoint2D contact in collision.contacts) { Color color = Color.white; Vector2 normal = contact.normal; if (normal == Vector2.right) { color = Color.red; onWallLeft = true; } if (normal == -Vector2.right) { color = Color.green; onWallRight = true; } if (normal == Vector2.up) { color = Color.blue; onGround = true; } onWall = onWallLeft || onWallRight; Debug.DrawRay(contact.point, contact.normal, color); } } void OnCollisionExit2D() { // reset flags when we arent colliding with anything at all onGround = false; onWallLeft = false; onWallRight = false; onWall = false; } }