圆形与矩形的碰撞检测--Mr.Ember

 

圆形与矩形的碰撞检测--Mr.Ember

已知:圆形半径和坐标* 矩形四个点坐标* 判断是否相交
 
先去找出矩形上离圆心最近的点,判断该点的距离是否小于圆半径,若小于半径,则为碰撞。
 
 
let closestPoint = {x:0, y:0};

约定圆形和矩形的类:

 //圆形
 function Circle(x,y,r) {
    this.r = r;
    this.x = x;
    this.y = y;
 }

 //矩形
 function Rect(ul,ur,dl,dr) {
    this.x = ul.x;
    this.y = ul.y;
    this.w = Math.abs(ul.x - ur.x);
    this.h = Math.abs(ul.y - dl.y);
 }

判断圆的x坐标是在矩形的位置

如果圆心在矩形的左侧  circle.x < rect.x   即closestPoint.x = rect.x;

如果圆心在矩形的左侧  circle.x > rect.x + rect.w; 即closestPoint.x = rect.x + rect.w;

 

否则,圆心就在矩形的正上正下方,即closestPoint.x = circle.x;

同理,y轴类似

    if(circle.y < rect.y) {  
        closestPoint.y = rect.y;
    } else if(circle.y > rect.y + rect.h) {
        closestPoint.y = rect.y + rect.h;
    } else {
        closestPoint.y = circle.y;
    }

然后判断是否相交 

   let closestPoint = handleClosestPoint(circle, rect);
    let distance = Math.sqrt(Math.pow(closestPoint.x - circle.x, 2) + Math.pow(closestPoint.y - circle.y, 2))
        console.log('distance',distance)
    if(distance < circle.r) return true // 发生碰撞
    else return false // 未发生碰撞

这种方法只是判断了矩形不旋转和不包含情况。

判断矩形旋转还需特殊处理

猜你喜欢

转载自www.cnblogs.com/teteWang-Ember/p/11399220.html