栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

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

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

演示图

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

塔防案例.gif

矩形区域碰撞检测


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;
  }
 
}

圆形区域碰撞检测


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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/103246.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号