I have a simple script attached to an otherwise empty game object. It uses code scraped from a relatively recent response on Unity Answers (2019) which is uses the Collider2D method ClosestPoint() to determine whether a point is inside a collider.
public class ClosestPointTest : MonoBehaviour
{
CompositeCollider2D _tilemapCollider;
void Start() {
_tilemapCollider = GameObject.Find("Ground Tilemap").GetComponent<CompositeCollider2D>();
}
void Update() {
Vector2 point = new Vector2(gameObject.transform.position.x, gameObject.transform.position.y);
Debug.Log("IsInside = " + IsInside(_tilemapCollider, point));
}
public bool IsInside(Collider2D c, Vector2 point) {
return c.ClosestPoint(point) == point;
}
}
I also have a Grid containing a Tilemap which has a TilemapCollider2D > CompositeCollider2D.
The Scripting API for the Collider2D.ClosestPoint states:
But when I move the game object around after entering play mode The debug statement returns false whether the collider is outside or inside the collider. In fact, the only time it appears to return true is when the point is exactly on a collider edge.
Where is my misunderstanding? Is this a unity bug or (more likely) a me bug? If this won’t work, what’s an alternate method to determine if a point is within a collider on the 2D plane?