1

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);
        }
    

enter image description here

enter image description here

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

if(r<l || d<u) return new Rectangle --> return false ? else return new Rectangle(l,u,r-l,d-u) --> return true ? i tried your code but it give me the same result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.