Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Distance from point to collider?

Discussion in 'Physics for ECS' started by PhilSA, Feb 16, 2020.

  1. PhilSA

    PhilSA

    Joined:
    Jul 11, 2013
    Posts:
    1,926
    • I have a point in the world
    • I have a collider
    • I'd like to know the distance from point to collider (especially the negative distance if there is penetration)
    I'm trying to do this like so:
    Code (CSharp):
    1. ConvexCollider* convexCollider = (ConvexCollider*)physicsCollider.ColliderPtr;
    2.  
    3. PointDistanceInput pointDistanceInput = new PointDistanceInput
    4. {
    5.     Filter = convexCollider->Filter,
    6.     MaxDistance = 0f,
    7.     Position = myWorldSpacePoint,
    8. };
    9. convexCollider->CalculateDistance(pointDistanceInput, out DistanceHit pointDistanceHit);
    But I always get a distance of zero. What am I doing wrong?
    • Is my cast to ConvexCollider valid? ("physicsCollider" here is a capsule primitive collider, of type "PhysicsCollider")
    • Is my "Position" assignment in PointDistanceInput valid? Should it be in worldSpace?
     
  2. MaxAbernethy

    MaxAbernethy

    Joined:
    Mar 16, 2019
    Posts:
    53
    MaxDistance=0 means the query will not return a hit unless the point is inside the collider. CalculateDistance() returns a bool indicating whether it found a hit within the specified MaxDistance or not. The purpose is to let the query early out without finding the closest point if it knows there is none closer than MaxDistance, but I don't think any ConvexCollider implements any early out yet, so it's just as well to set MaxDistance = float.MaxValue.

    Position should be in the ConvexCollider's local space.
     
    PhilSA likes this.
  3. MaxAbernethy

    MaxAbernethy

    Joined:
    Mar 16, 2019
    Posts:
    53
    Also, you may not want to set the filter like that. CalculateDistance() will test the filter on the query against the filter on the collider. So if the filter on the collider disables self-collision, then this query would not return a hit.
     
    PhilSA likes this.