如何计算Box2D / Farseer中夹具和点之间的距离?

时间:2015-03-07 15:41:53

标签: c# c++ box2d distance farseer

基本上,我有一个装置和一个点。我想知道它们之间的距离(而不是它们的中心之间)。

我知道存在Distance API,但它只适用于2个灯具:/

1 个答案:

答案 0 :(得分:1)

你应该知道更多的数学知识。两个对象之间的距离是它们坐标之间的向量长度。 Farseer使用Xna类型Vector2或Vector3。只需减去两个所需的矢量以获得所需的矢量,并通过相应矢量类型的方法获得 Length 。 Fixture的坐标位于 Body.Position

之下

对于使用灯具形状到特定点的距离,只需从中创建假的pointShape(用于需要的半径最小的圆圈),然后使用Distance类。

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
                });
}