Home > Web Front-end > JS Tutorial > body text

Encapsulation code for collision detection in game development using javascript_javascript skills

WBOY
Release: 2016-05-16 16:06:57
Original
1437 people have browsed it

When developing web games with JavaScript, collision detection is required. In order to facilitate development, two collision detection methods, rectangular and circular, are encapsulated.

【Capture one with case operation】
[Note: The code has not been optimized]

Demo picture

Character attack area collision detection.gif

Tower defense case.gif

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;
   
  //碰撞检测(参数为此类)
  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;
  }
 
}
Copy after login

Circular 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;
 
  //碰撞检测(参数为此类)
  this.intersects = function(rr){
    var maxRadius = rr.radius + this.radius;
    // 已知两条直角边的长度 ,可按公式:c&sup2;=a&sup2;+b&sup2; 计算斜边。
    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));// 计算圆心距离
    if(distance < maxRadius){
      return true;
    }
    return false;
  }
}
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone in understanding javascript.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!