在javascript开发web游戏时,需要使用到碰撞检测时,为了方便开发,封装了矩形和圆形的两个碰撞检测方式。
【附带案例操作捕获一枚】
【注意:代码上未做优化处理】
演示图

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

立即学习“Java免费学习笔记(深入)”;
塔防案例.gif
矩形区域碰撞检测
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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 ;
}
}
|
登录后复制
圆形区域碰撞检测
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
function RadiusRectangle(x, y, radius){
this .x = x;
this .y = y;
this .radius = radius;
this .intersects = function (rr){
var maxRadius = rr.radius + this .radius;
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有所帮助。