Search code examples
c#c++box2ddistancefarseer

How to calculate distance between a fixture and a point in Box2D/Farseer?


Basically, I have a fixture, and a point. I want to know the distance between them (not between their centers).

I know there exists the Distance API, but it only works with 2 fixtures :/


Solution

  • It's more math knowledge that you should knew. Distance between two objects is a length of vector between their coordinates. Farseer uses Xna type Vector2 or Vector3. Just subtract two needed vectors to get the needed one and get Length through the method on the corresponding vector type. Fixture's coordinates are under its Body.Position.

    For distance to specific point using shape of your fixture just create fake pointShape from it (use for your needs circle with minimum radius) and then use Distance class.

    float getDistance(Vector2 point, Fixture fixture)
    {
        var proxyA = new DistanceProxy();
        proxyA.Set(fixture.Shape, 0);
    
        var proxyB = new DistanceProxy();
        // prepare point shape
        var pointShape = new CircleShape(0.0001, 1);
        proxyB.Set(pointShape, 0);
    
        Transform transformA;
        fixture.Body.GetTransform(out transformA);
    
        Transform transformB = new Transform();
        transformB.Set(point, 0);
    
        DistanceOutput distance;
        SimplexCache cache;
    
        FarseerPhysics.Collision.Distance.ComputeDistance(out distance, out cache,
                    new FarseerPhysics.Collision.DistanceInput(){
                        UseRadii=true,
                        ProxyA=proxyA,
                        ProxyB=proxyB,
                        TransformA=transformA,
                        TransformB=transformB
                    });
    }