简体   繁体   中英

My Rectangle Collision(With Images) Detection fires before touching?

I'm trying to figure out why my collision detection for these two images seem to fire before they touch. I've tried multiple simple detection algorithms but I keep running into the same issue.

EDIT - forgot the link http://exclusivebarbershopnj.net/canvas/Row.html

Here's the Rectangle function

function Rectangle(x, y, width, height) {
    var I = I || {};

    I.x = x;
    I.y = y;
    I.width = width;
    I.height = height;

    I.intersectsWith = function(rect) {
        return (rect.x < this.x + this.width && this.x < rect.x + rect.width && rect.y < this.y + this.height)
    }

    return I;
}

And here's the code that sees if they hit.

function boathit() {
    var rect = new Rectangle(player.x, player.y, player.width, player.height);

    lilypads.forEach(function(lilypad) {
        var rect2 = new Rectangle(lilypad.x, lilypad.y, lilypad.width, lilypad.height);

        if(rect2.intersectsWith(rect)) {
          console.log('rect');
          console.log(rect);
          console.log('rect2');
          console.log(rect2);
        }
    });
}

I'm really stumped here, and would appreciate any help.

It's not very readable like this, and it seems like you're missing a check.

Try using this instead (I'm assuming that if x is the left bound, than x+width-1 is the right bound and so on):

I.intersectsWith = function(rect) {
  var rects = [
    { left: this.x, right: this.x+this.width-1, top: this.y, bottom: this.y+this.height-1 },
    { left: rect.x, right: rect.x+rect.width-1, top: rect.y, bottom: rect.y+rect.height-1 }
  ];

  return rects[0].left <= rects[1].right && rects[1].left <= rects[0].right &&
    rects[0].top <= rects[1].bottom && rects[1].top <= rects[0].bottom;
}

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