Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

CompositeCollider2D public method ClosestPoint() does not perform as indicated in the Scripting API

Discussion in 'Editor & General Support' started by king_ad_the_bad, May 25, 2022.

  1. king_ad_the_bad

    king_ad_the_bad

    Joined:
    Feb 6, 2020
    Posts:
    2
    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.
    Code (CSharp):
    1. public class ClosestPointTest : MonoBehaviour
    2. {
    3.     CompositeCollider2D _tilemapCollider;
    4.    
    5.     void Start() {
    6.         _tilemapCollider = GameObject.Find("Ground Tilemap").GetComponent<CompositeCollider2D>();
    7.     }
    8.  
    9.     void Update() {
    10.         Vector2 point = new Vector2(gameObject.transform.position.x, gameObject.transform.position.y);
    11.         Debug.Log("IsInside = " + IsInside(_tilemapCollider, point));
    12.     }
    13.  
    14.     public bool IsInside(Collider2D c, Vector2 point) {
    15.         return c.ClosestPoint(point) == point;
    16.     }
    17. }
    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?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
  3. king_ad_the_bad

    king_ad_the_bad

    Joined:
    Feb 6, 2020
    Posts:
    2
    Ah, yep. I did not know that feature existed, I'll play with it with this new information. Thanks!