When JavaScript develops a web game, it needs to use collision detection, which encapsulates two of rectangular and circular collision detection methods for easy development.
"Incidental case operation captures one"
"Note: No optimizations are done on the code"
Demo diagram
Role attack area collision detection. gif
Tower defense case. gif
Collision detection in rectangular area
/**
* Rectangular area Collision Detection
* Created by the 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;
Collision Detection (parameter is such)
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;
}
Circular area Collision Detection
/**
* Circular area Collision Detection
* Created by the Administrator on 14-4-7.
* Author:marker
* * *
/function Radiusrectangle (x, y, radius) {
this.x = x;
This.y = y;
This.radius = radius;
Collision Detection (parameter is such)
this.intersects = function (RR) {
var Maxradius = Rr.radius + This.radius;
Given the length of the two-angled edge, you can calculate the hypotenuse by formula: 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))//Compute Center Distance
if (distance < Maxradius) {return
true;< c19/>} return
false;
}
The above is the entire content of this article, I hope to be able to understand JavaScript help.