且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测2个UIView之间的碰撞

更新时间:2021-12-16 09:39:25

对,所以首先检查重叠的矩形(已经完成)。当发现重叠时,则需要优化碰撞测试。对于有问题的矩形的每个角,计算从角色中心到有问题的矩形的角的距离。如果从中心到任意一个角的距离小于圆的半径,则发生碰撞。要稍微优化代码,请计算(dx * dx + dy * dy)并将其与半径平方进行比较。这样,您不必计算任何平方根。

Right, so first you check for overlapping rectangles (which you've already done). When you find an overlap, then you need to refine the collision test. For each corner of the offending rectangle, compute the distance from the center of your character to the corner of the offending rectangle. If the distance from the center to any of the corners is less than the radius of the circle, then you have a collision. To optimize the code a little bit, compute (dx * dx + dy * dy) and compare that to the radius squared. That way you don't have to compute any square roots.

在进一步检查时,除了进行角点检查外,还需要进行边缘检查。例如,如果顶部 y 值在圆心上方,而底部 y 值在圆心下方的圆,然后计算矩形左边缘和圆的中心之间的 x 差,如果该距离小于半径,则发生了碰撞。同样,对于矩形的其他三个边缘。

Upon further review, you also need to do an edge check in addition to the corner check. For example, if the top y value is above the center of the circle and the bottom y value is below the center of the circle, then compute the difference in x between the rectangle left edge and the center of the circle, and if that distance is less than the radius, then a collision has occurred. Likewise for the other three edges of the rectangle.

以下是一些用于角落检查的伪代码

Here's some pseudo-code for the corner checking

int dx, dy, radius, radiusSquared;

radiusSquared = radius * radius;
for ( each rectangle that overlaps the player rectangle )
{
    for ( each corner of the rectangle )
    {
        dx = corner.x - center.x;
        dy = corner.y - center.y;
        if ( dx * dx + dy * dy < radiusSquared )
            Collision!!!
    }
}