网络编程 
首页 > 网络编程 > 浏览文章

javascript制作游戏开发碰撞检测的封装代码

(编辑:jimmy 日期: 2025/12/28 浏览:3 次 )

在JavaScript开发Web游戏时,需要使用到碰撞检测时,为了方便开发,封装了矩形和圆形的两个碰撞检测方式。

【附带案例操作捕获一枚】
【注意:代码上未做优化处理】

演示图

javascript制作游戏开发碰撞检测的封装代码

角色攻击区域碰撞检测.gif

javascript制作游戏开发碰撞检测的封装代码

塔防案例.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有所帮助。

上一篇:jQuery选择器源码解读(三):tokenize方法
下一篇:jQuery选择器源码解读(二):select方法
一句话新闻
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap