Javascript makes encapsulation code for game development collision detection, and game development Collision Detection
During JavaScript development of Web games, collision detection is required. In order to facilitate development, two Collision Detection Methods of rectangle and circle are encapsulated.
[Capture one with case operations]
[Note: the code is not optimized]
Demo Diagram
Corner attack detection .gif
Tower anti-DDoS case .gif
Rectangular area Collision Detection
/*** Rectangular area collision detection * 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; // collision detection (the parameter is of this class) 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 ;}}
Round area Collision Detection
/*** Round area collision detection * Created by Administrator on 14-4-7. * author: marker **/function RadiusRectangle (x, y, radius) {this. x = x; this. y = y; this. radius = radius; // collision detection (the parameter is of this class) this. intersects = function (rr) {var maxRadius = rr. radius + this. radius; // the length of the two angular edges. The diagonal edges can be calculated based on the formula: c 2 = a 2 + B 2. 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); // calculate the distance from the center to if (distance <maxRadius) {return true;} return false ;}}
The above is all the content of this article. I hope it will help you understand javascript.