大部分模形都適合使用『圓形碰撞』.但若模形呈長條形則適合使用『矩形碰撞』.也稱為『軸對齊邊界盒碰撞』.特點是頂底邊與X軸平行,左右邊與Y軸平行.碰撞算法以包圍著對象最小矩形.但缺點是無法隨物體旋轉.速度快但精度較差.若定義矩形則由中心位置與長寬所組成.
public class RECT2D {
矩形中心位置
public VECTOR2D center;
矩形寬與高
public float width;
public float height;
購造『軸對齊邊界盒』輸入中心位置與寬高.
public RECT2D(float x,float y,float width,float height){
this.center = new VECTOR2D(x, y); // 中心點
this.width = width;
this.height = height;
}
『點』與『矩形』碰撞.若點為於四條邊之內則發生碰撞
public boolean overlap(VECTOR2D point){
if(point.x < center.x + width/2 &&
point.x > center.x – width/2 &&
point.y < center.y + height/2 &&
point.y > center.y – height/2 )
return true;
else
return false;
}
兩矩形碰撞測試,原點在左下角.算法睇上圖有D複雜.『矩形1左邊』在『矩形2右邊』之左則.『矩形1右邊』在『矩形2左邊』之右則.『矩形1底邊』在『矩形2頂邊』之下則.『矩形1頂邊』在『矩形2底邊』之上則.只要全部符合則兩矩形重疊.
public boolean overlap(RECT2D rect){
if(center.x – width/2 < rect.center.x + rect.width/2 &&
center.x + width/2 > rect.center.x – rect.width/2 &&
center.y – height/2 < rect.center.y + rect.height/2 &&
center.y + height/2 > rect.center.y – rect.height/2 )
return true;
else
return false;
}
『圓形』與『矩形』碰撞.原點在左下角.需先計算『矩形』與『圓心』之『最近點』.『圓心』在『矩形』之外.則『最近點』落在『矩形』邊緣之上.如果『圓心』在『矩形』之內.則『最近點』是『圓心』.然後計算『圓心』與『最近點』之距離.若小於『圓半徑』內則發生重疊.
public boolean overlap(CIRCLE2D circle){
float closestX = circle.center.x; // 圓心座標X
float closestY = circle.center.y;// 圓心座標Y
if(circle.center.x < center.x – width/2)
closestX = center.x – width/2;
else
if(circle.center.x > center.x + width/2)
closestX = center.x + width/2;
if(circle.center.y < center.y – height/2)
closestY = center.y – height/2;
else
if(circle.center.y > center.y + height/2)
closestY = center.y + height/2;
if(circle.center.DistSquared(closestX,closestY) < circle.radius * circle.radius)
return true; // 『圓』內則發生碰撞
else
return false; // 無發生碰撞
}
}