欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javascript制作游戲開發(fā)碰撞檢測的封裝代碼

 更新時間:2015年03月31日 10:15:10   投稿:hebedich  
這篇文章主要介紹了javascript制作游戲開發(fā)碰撞檢測的封裝代碼,需要的朋友可以參考下

在JavaScript開發(fā)Web游戲時,需要使用到碰撞檢測時,為了方便開發(fā),封裝了矩形和圓形的兩個碰撞檢測方式。

【附帶案例操作捕獲一枚】
【注意:代碼上未做優(yōu)化處理】

演示圖

角色攻擊區(qū)域碰撞檢測.gif

塔防案例.gif

矩形區(qū)域碰撞檢測

/**
 * 矩形區(qū)域碰撞檢測
 * 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;
   
  //碰撞檢測(參數(shù)為此類)
  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;
  }
 
}

圓形區(qū)域碰撞檢測

/**
 * 圓形區(qū)域碰撞檢測
 * Created by Administrator on 14-4-7.
 * author: marker
 *
 */
function RadiusRectangle(x, y, radius){
  this.x = x;
  this.y = y;
  this.radius = radius;
 
  //碰撞檢測(參數(shù)為此類)
  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;
  }
}

以上所述就是本文的全部內(nèi)容了,希望能夠?qū)Υ蠹伊私鈐avascript有所幫助。

相關(guān)文章

最新評論