javascript製作遊戲開發碰撞檢測的封裝代碼,遊戲開發碰撞檢測

來源:互聯網
上載者:User

javascript製作遊戲開發碰撞檢測的封裝代碼,遊戲開發碰撞檢測

在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有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.