在JavaScript開發Web游戲時,需要使用到碰撞檢測時,為了方便開發,封裝了矩形和圓形的兩個碰撞檢測方式。
【附帶案例操作捕獲一枚】
【注意:代碼上未做優化處理】
演示圖

角色攻擊區域碰撞檢測.gif

塔防案例.gif
矩形區域碰撞檢測
/** * 矩形區域碰撞檢測 * Created by Administrator on 14-4-7. * author: marker */function Rectangle(x, y, _width, _height){  this.x = x;  this.y = y;   this.width = _width;  this.height = _height;     //碰撞檢測(參數為此類)  this.intersects = function(obj){    var a_x_w = Math.abs((this.x+this.width/2) - (obj.x+obj.width/2));    var b_w_w = Math.abs((this.width+obj.width)/2);    var a_y_h = Math.abs((this.y+this.height/2) - (obj.y+obj.height/2));     var b_h_h = Math.abs((this.height+obj.height)/2);    if( a_x_w < b_w_w && a_y_h < b_h_h ) return true;    else return false;  } }圓形區域碰撞檢測
/** * 圓形區域碰撞檢測 * Created by Administrator on 14-4-7. * author: marker * */function RadiusRectangle(x, y, radius){  this.x = x;  this.y = y;  this.radius = radius;   //碰撞檢測(參數為此類)  this.intersects = function(rr){    var maxRadius = rr.radius + this.radius;    // 已知兩條直角邊的長度 ,可按公式:c²=a²+b² 計算斜邊。    var a = Math.abs(rr.x - this.x);    var b = Math.abs(rr.y - this.y);    var distance = Math.sqrt(Math.pow(a,2) + Math.pow(b,2));// 計算圓心距離    if(distance < maxRadius){      return true;    }    return false;  }}以上所述就是本文的全部內容了,希望能夠對大家了解javascript有所幫助。
新聞熱點
疑難解答