0
votes

I have one draggable rectangle and multiple static rectangle. I know how to detect if two rectangles collide and once I detect the collision between two rectangles I replace the draggable rectangle to the nearest non-colliding position. But the problem is that I cannot figure out any good algorithm to replace it to "another" nearest position if the actual nearest position is occupied by some other static rectangle. All is seen clearly in this picture: http://i.stack.imgur.com/hocZR.png

Could you please suggest a solution to the problem or point me to resources that can help me find it myself?

Here's how I detect collision between two rectangles:

function detectCollision(r1, r2) {
  return !(r2.left > r1.right || 
           r2.right < r1.left || 
           r2.top > r1.bottom ||
           r2.bottom < r1.top);
}
3

3 Answers

0
votes

Maybe just make it not allow you to place the rectangle until it is in a place not occupied by any other rectangles

0
votes

Maybe you can make the draggable rectangle static like the others so you won't face the problem you are trying to solve now.

0
votes

This may not work all the time, but instead of:

if(rect = findcollision())
    move_out_of_the_way(rect);

Do:

while(rect = findcollision()){
    move_out_of_the_way(rect);
}

And if the loop has run for more than 10 times you give up or something.