开发者

Multiple rectangle collision

开发者 https://www.devze.com 2023-03-29 16:53 出处:网络
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

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 stat开发者_开发问答ic 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);
}


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消