Javascript-encapsulated code for game development collision detection-javascript skills

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.