JavaScript production game development Collision detection Package code _javascript Tips

Source: Internet
Author: User
Tags abs pow

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.

Related Article

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.