简体   繁体   中英

collision detection algorithm issue

here is the jsfiddle i am working on so far : http://jsfiddle.net/TLYZS/

if you debug the code and check the collision function you can see that the collision is working fine when the user overlap with the other character wish in a fighting game the collision should not work like this :

  1. you can see that when i punch or kick the character from a little distance the collision detection function does not work even if you can see it on the screen that the user is punishing the character
  2. how can i fix this collision detection function to make it work fine ?

     function Collision(r1, r2) { return !(r1.x > r2.x + r2.w || r1.x + r1.w < r2.x || r1.y > r2.y + r2.h || r1.y + r1.h < r2.y); } 

在此处输入图片说明

在此处输入图片说明

Here is my old JS implementation of flash.geom.Rectangle. Try to use it in your project:

function Rectangle(x, y, w, h) {  //  constructor
    if(x==null) x=y=w=h=0;
    this.x = x;      this.y = y;
    this.width = w;  this.height = h;       
}
Rectangle.prototype.isEmpty = function() {  // : Boolean
    return (this.width<=0 || this.height <= 0);
}
Rectangle.prototype.intersection = function(rec) {  // : Rectangle
    var l = Math.max(this.x, rec.x);
    var r = Math.min(this.x+this.width , rec.x+rec.width );
    var u = Math.max(this.y, rec.y);
    var d = Math.min(this.y+this.height, rec.y+rec.height);
    if(r<l || d<u) return new Rectangle();
    else           return new Rectangle(l, u, r-l, d-u);
}

Then you just call

var r1 = new Rectangle( 0, 0,100,100);
var r2 = new Rectangle(90,90,100,100);
// r1.intersection(r2) would be Rectangle(90,90,10,10)
if( !r1.intersection(r2).isEmpty() ) ... // there is a collision

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM