javascript矩形碰撞檢測程式碼

antzone發表於2017-04-04

本章節分享一段矩形碰撞檢測程式碼,如下:

[JavaScript] 純文字檢視 複製程式碼
/**
 * 矩形區域碰撞檢測
 * 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;
  }
   
}

相關文章