This article mainly introduces javascript packaging code for game development collision detection. For more information about how to use collision detection when developing Web games in JavaScript, it encapsulates two collision detection methods for rectangles and circles.
[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.