一对一碰撞检测
target是目标物体,move是移动物体
情况1:target在move左上角
情况2:target在move右上角
情况3:target在move左下角
情况4:target在move右下角
重叠阴影面积算法
let width = (Math.min(tx2,mx2) - Math.max(tx1,mx1));
let height = (Math.min(ty2,my2) - Math.max(ty1,my1));
let stackArea = (width > 0 ? width : 0) * (height > 0 ? height : 0);
stackArea=0代表没有重叠;stackArea >0代表有交集
我们来点实际的代码
//判断两个矩形DIV是否重叠---------------------------------------- function isOver(targetDom, moveDom) { if (targetDom === moveDom) return false; let tx1 = parseInt(targetDom.style.left); let ty1 = parseInt(targetDom.style.top); let tx2 = tx1 + parseInt(targetDom.style.width); let ty2 = ty1 + parseInt(targetDom.style.height); let mx1 = parseInt(moveDom.style.left); let my1 = parseInt(moveDom.style.top); let mx2 = mx1 + parseInt(moveDom.style.width); let my2 = my1 + parseInt(moveDom.style.height); let width = Math.min(tx2, mx2) - Math.max(tx1, mx1); let height = Math.min(ty2, my2) - Math.max(ty1, my1); let stackArea = (width > 0 ? width : 0) * (height > 0 ? height : 0); // ---------------------------------------- if (stackArea > 0) return true; return false; }
一对多碰撞检测
target是目标物体,move是移动物体
这里就需要去遍历所有的target,计算每个重叠面积大小,挑出面积最大的那一个。
为了方便计算比较,我们通常是在上面的代码基础上加一个面积大小判断,重叠面积超过target面积一半的情况就认为是碰撞对象
//判断多个矩形DIV是否重叠,并获取最大的那个---------------------------------------- function isOverManyTarget(targetDom, moveDom) { if (targetDom === moveDom) return false; let tx1 = parseInt(targetDom.style.left); let ty1 = parseInt(targetDom.style.top); let tx2 = tx1 + parseInt(targetDom.style.width); let ty2 = ty1 + parseInt(targetDom.style.height); let mx1 = parseInt(moveDom.style.left); let my1 = parseInt(moveDom.style.top); let mx2 = mx1 + parseInt(moveDom.style.width); let my2 = my1 + parseInt(moveDom.style.height); let width = Math.min(tx2, mx2) - Math.max(tx1, mx1); let height = Math.min(ty2, my2) - Math.max(ty1, my1); let stackArea = (width > 0 ? width : 0) * (height > 0 ? height : 0); // ---------------------------------------- //计算面积 let measure = parseInt(targetDom.style.width) * parseInt(targetDom.style.height); let measureHalf = measure / 2; if (stackArea > measureHalf && stackArea <= measure) return targetDom; return null; }