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