C#XNA计算矩形之间的距离(旋转友好)

时间:2014-02-19 02:56:21

标签: c# xna collision detection

这里提供了2种方法;

if(rectangle.Intersects(otherRectangle))
{
    //collision stuff
}

Catch:仅适用于非旋转矩形。

if(Vector2.Distance(player.pos, enemy.pos) < 50)
{
    //collision stuff
}

Catch:仅适用于圈子。

我想要的是在此图片中计算x和y: problem

事实

定义两个矩形的宽度和长度以及它们的旋转。 我可以用毕达哥拉斯定理来计算D. 但是真实距离是D - (X + Y)。

一般方法

显然,可以使用余弦规则计算x和y。 但我只有宽度或长度以及两个形状之间的角度。

并发症

另外,这需要适用于任何轮换。 左边的矩形可以在任何方向旋转,x根据所说的旋转而不同。

问题

我如何计算x和y? 我只想要一种比边界框和毕达哥拉斯更复杂的有效碰撞检测方法。定理。

1 个答案:

答案 0 :(得分:1)

一种方法是使用反角旋转线并使用轴对齐框检查:

class RotatedBox 
{
    ...

    float CalcIntersectionLength(Vector2 lineTo) //assume that the line starts at the box' origin
    {
        Matrix myTransform = Matrix.CreateRotationZ(-this.RotationAngle);
        var lineDirection = Vector2.Transform(lineTo -this.Center, myTransform);
        lineDirection.Normalize();
        var distanceToHitLeftOrRight = this.Width / 2 / Math.Abs(lineDirection.X);
        var distanceToHitTopOrBottom = this.Height / 2 / Math.Abbs(lineDirection.Y);
        return Math.Min(distanceToHitLeftOrRight, distanceToHitTopOrBottom);
    }
}

现在您可以使用

计算实际距离
 var distance = (box1.Center - box2.Center).Length
                - box1.CalcIntersectionLength(box2.Center)
                - box2.CalcIntersectionLength(box1.Center);

确保旋转方向与您的可视化相匹配。

相关问题