Calculate Distance To Move A Box To Remove Intersection
Solution 1:
As I read it now you calculate the centers of both boxes and use those two points to make the vector that pushes one of the boxes. That's the wrong vector. If you place the boxes right on top of each other that vector will be (0,0)
. If the boxes only just clip each other the vector will be at it's highest possible value.
You can see this in action with the ghosts. First it gets pushed only a little bit, then it gets pushed a lot.
Instead the vector you need should be based on the size of the overlap. If the overlap is 20px by 30px your vector is (+20,+30)
var vector = {
x: Math.min(box1.x + box2.width, box2.x + box2.width) - Math.max(box1.x, box2.x),
y: Math.min(box1.y + box2.height, box2.y + box2.height) - Math.max(box1.y, box2.y)
}
vector.x
is the top-right of the bounding box minus the bottom-left of the bounding box. Idem for vector.y
.
This moves the box by exactly the right amount: http://jsfiddle.net/x8MT3/2/
I added a 3rd box pair that needs 2 iterations, probably the top box should move the other way. The vector as I've set it up is always (+,+)
, you can do your center point calculation to determine which sign each direction should have.
Post a Comment for "Calculate Distance To Move A Box To Remove Intersection"