有两个矩形rectA(x,y,width,height)、rectB (x,y,width,height)
检测A,B是否发生重叠,在讨论是否发生重叠时我们可以先看看没有重叠的四种情况,如下图:

以下是对这四种状态的判断:
1、rectB.y+rectB.height < rectA.y
2、rectB.x > rectA.x +rectA.width
3、rectB.y > rectA.y + rectA.height
4、rectB.x+rectB.width < rectA.x
知道如何判断没有重叠的状态,那发生重叠的状态该如何判断呢?没错“取反”!,我们创建函数Interaect并添加到Init.js中,该函数传入两个Rect对象参数,当两Rect对象发生重叠将返回true。
代码如下:
function Intersect(rectA,rectB) {
return !(rectB.y+rectB.height < rectA.y || rectB.x> rectA.x +rectA.width ||
rectB.y > rectA.y + rectA.height|| rectB.x+rectB.width < rectA.x)
}
版权声明:本文为weixin_44730897原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。