Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get closest point in collider

Tags:

I wanted to know how I can get the same result this function gives in Unity 2018.3 where it is not avaliable yet:

https://docs.unity3d.com/2019.1/Documentation/ScriptReference/Collider2D.ClosestPoint.html

like image 350
janavarro Avatar asked Jun 15 '19 15:06

janavarro


People also ask

Is a trigger a collider?

Is the collider a trigger? A trigger doesn't register a collision with an incoming Rigidbody. Instead, it sends OnTriggerEnter, OnTriggerExit and OnTriggerStay message when a rigidbody enters or exits the trigger volume.

How can I see colliders?

Try under Edit > Project Settings > Physics 2D > Gizmos > Always Show Colliders . Save this answer. Show activity on this post. Unity shows collider only for objects that was selected in hierarchy.

What is collision in unity?

Intro to Game Development with Unity Collisions in Unity are separated from the actual Sprite itself, attached as separate components and are calculated on their own. Let us now learn the cause behind this. Everything in your game is a GameObject.


1 Answers

I had this problem today, I'm also using 2018.3. Here's a helper function here that supplants collider2D.ClosestPoint. Edit the colliders as you need.

public static class Collider2DExtension
{
    /// <summary>
    /// Return the closest point on a Collider2D relative to point
    /// </summary>
    public static Vector2 ClosestPoint(this Collider2D col, Vector2 point)
    {
        GameObject go = new GameObject("tempCollider");
        go.transform.position = point;
        CircleCollider2D c = go.AddComponent<CircleCollider2D>();
        c.radius = 0.1f;
        ColliderDistance2D dist = col.Distance(c);
        Object.Destroy(go);
        return dist.pointA;
    }
}

sourced it from this thread: https://forum.unity.com/threads/get-closest-point-of-collider2d.225120/

like image 117
moon cheese Avatar answered Oct 31 '22 13:10

moon cheese