Kiksen
Kiksen

Reputation: 1777

Collision detection with rectangles

I have tried to make a small "game" with collision detection.

The problem is, in some cases objects just passes through. I am totally blind to the cause.

I have tried to create my own detection, which is commented out and then i tried this:

Code sample as fiddle

function rectanglesIntersect( minAx, minAy, maxAx, maxAy, minBx, minBy, maxBx, maxBy ) {
    var aLeftOfB = maxAx < minBx;
    var aRightOfB = minAx > maxBx;
    var aAboveB = minAy > maxBy;
    var aBelowB = maxAy < minBy;

    return !( aLeftOfB || aRightOfB || aAboveB || aBelowB );
}

Upvotes: 1

Views: 147

Answers (1)

markE
markE

Reputation: 105035

Luckily, your rects have these simplifying qualities when moving:

  • They only move in the Y direction (up or down).
  • They all move at 30px per move.

So you can determine if & where a rect pair will collide like this:

  1. At the start of the move, calculate if pair of rectangles can possibly collide by testing if they are vertically aligned.

    rect1.x > rect2.x && rect1.x < rect2.x + rect2.width;
    
  2. If the pair of rectangles is traveling towards each other, calculate if the pair is within 60 vertical pixels of each other. The 60 is important because each rect can travel 30 pixels per move so the rect pair can close in on each other by 30+30=60px per move.

    var willCollideThisMove = Math.abs(rect1.y-rect2.y)<=60;
    
  3. If the pair will collide, then the pair will collide at the midpoint of their distance difference:

    var collisionY = Math.min(rect1.y,rect2.y)+Math.abs(rect1.y-rect2.y)/2;
    

Do these 3 calculations for all rect pairs.

Upvotes: 3

Related Questions