當物體移動並相互發生作用.需進行碰撞撿測.若重疊便發生碰撞.常見碰撞算法是通過『圓形邊界球』.它是包圍著對象最小圓. 無需隨物體旋轉而旋轉.所以速度最快之算法但精度較差.它由『圓心』與『半徑』所組成.
public class CIRCLE2D{
中心位置
public VECTOR2D center;
半徑
public float radius;
購造圓形邊界球,輸入中心位置與半徑.
public CIRCLE2D(float x,float y,float radius){
this.center = new VECTOR2D(x,y);
this.radius = radius;
}
『圓』與『點』碰撞檢測.計算『圓心』與『點』之距離.若距離小於『圓半徑』則發生碰撞.
public boolean overlap(VECTOR2D point){
float distance = center.Dist(point);
if(distance < radius )
return true;// 發生碰撞
else
return false;// 無發生碰撞
}
兩圓形碰撞檢測.計算兩圓心『距離』.若『距離』小於兩圓半徑之和則發生碰撞
public boolean overlap(CIRCLE2D circle){
float distance = center.Dist(circle.center);// 兩圓之距
if(distance <= radius + circle.radius)
return true;// 發生碰撞
else
return false;// 無發生碰撞
}
『圓形』與『矩形』碰撞算法最為複雜.需先計算『矩形』與『圓心』最近之點.然後計算『圓心』與『最近點』之距離.若此點在『圓』內則發生重疊.
public boolean overlap(RECT2D rect){
float closestX = center.x; // 最接近X
float closestY = center.y;// 最接近Y
if(center.x < rect.center.x – rect.width/2)
closestX = rect.center.x – rect.width/2;
else
if(center.x > rect.center.x + rect.width/2)
closestX = rect.center.x + rect.width/2;
if(center.y < rect.center.y – rect.height/2)
closestY = rect.center.y – rect.height/2;
else
if(center.y > rect.center.y + rect.height/2)
closestY = rect.center.y + rect.height/2;
if(center.Dist(closestX,closestY) < radius)
return true; // 『圓』內則發生碰撞
else
return false; // 無發生碰撞
}
}
你必須登入才能發表留言。