let closestPoint = {x:0, y:0};
約定圓形和矩形的類:this
//圓形 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座標是在矩形的位置spa
若是圓心在矩形的左側 circle.x < rect.x 即closestPoint.x = rect.x;code
若是圓心在矩形的左側 circle.x > rect.x + rect.w; 即closestPoint.x = rect.x + rect.w;blog
不然,圓心就在矩形的正上正下方,即closestPoint.x = circle.x;ci
同理,y軸相似io
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; }
而後判斷是否相交 console
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 // 未發生碰撞
這種方法只是判斷了矩形不旋轉和不包含狀況。function
判斷矩形旋轉還需特殊處理class