calculate distance between two (Collider or Mesh) AABB bounds using sdf equation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // src* = https://gist.github.com/andrew-raphael-lukasik/658184336c9799ed66f3a5acfa3e7f9c | |
| using UnityEngine; | |
| using Unity.Mathematics; | |
| using static Unity.Mathematics.math; | |
| public class CalculateDistanceBetweenColliderBounds : MonoBehaviour | |
| { | |
| [SerializeField] Collider collider0; | |
| [SerializeField] Collider collider1; | |
| void OnDrawGizmos () | |
| { | |
| if( collider0==null || collider1==null ) return; | |
| Bounds bounds0 = collider0.bounds; | |
| Bounds bounds1 = collider1.bounds; | |
| float sd0 = sdBounds( bounds0.center , bounds1 , out Vector3 conjecture0 ); | |
| float sd1 = sdBounds( bounds1.center , bounds0 , out Vector3 conjecture1 ); | |
| float dist = Vector3.Distance( conjecture0 , conjecture1 ); | |
| Gizmos.color = new Color(0,1,1,0.2f); | |
| Gizmos.DrawCube( bounds0.center , bounds0.size ); Gizmos.DrawCube( bounds1.center , bounds1.size ); | |
| Gizmos.DrawWireCube( bounds0.center , bounds0.size ); Gizmos.DrawWireCube( bounds1.center , bounds1.size ); | |
| UnityEditor.Handles.Label( transform.position , $"approx distance: {dist}" ); | |
| } | |
| static float sdBounds ( Vector3 point , Bounds bounds , out Vector3 contact ) | |
| { | |
| Vector3 dir = point - bounds.center; | |
| float sd = sdBox( dir , bounds.extents ); | |
| contact = point - dir.normalized*sd; | |
| // note: we dont need to know the real contact point in this case, this is pure conjecture | |
| return sd; | |
| } | |
| // src: https://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm | |
| static float sdBox ( float3 p , float3 b ) | |
| { | |
| float3 q = abs(p) - b; | |
| return length(max(q,0f)) + min(max(q.x,max(q.y,q.z)),0f); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it returns the shortest distance between bounds:
