Search code examples
unity-game-engineunity3d-2dtools

Unity get distance to edge of Collider2D from within


I have a Collider2D which moves around within a larger, stationary Collider2D and I'd like to get the distance from the centre of the smaller one to the edge of the larger one along the direction it's travelling in.

My first thought was to use a Raycast such as:

Physics2D.Raycast(this.transform.position, 
                  this.rigidbody2D.velocity.normalized).distance;

But obviously the distance is always 0 as they are already intersecting.

Is there any way to do this?

EDIT: Here is a diagram as requested diagram

Both circles are Collider2D objects, the arrow is the direction the smaller one is travelling in and the red x is the point I'd like to find (so I can determine the distance).


Solution

  • Instead of trying to check for a collision you could do it mathematically.

    If you know the radius/position of the circle, the position of the smaller Collider2D, and the vector of its movement, then you can solve where that movement vector intersects with the circle.

    Here is how to figure that out mathematically: http://www.analyzemath.com/CircleEq/circle_line_intersection.html

    Another approach if you still want to raycast could be to cast the ray from a point along the smaller object's movement vector with distance greater than the larger circle's diameter. This ray would then be cast toward the smaller object. Essentially, you are casting the ray from outside the circle instead of inside the circle.