我正在尝试使rect1
从rect2
内部移出。我试图四处寻找awsner,但找不到满意的遮阳篷。我可以检测到相交的矩形,但无法将rect1
排除,所以它不在rect2
之外。您能否提供一些代码来帮助我做到这一点?到目前为止,我将提供我的检测代码。
码:
var DoCollision = function(rect1, rect2, objectToMove){
if (rect1.x + rect1.w > rect2.x &&
rect1.x < rect2.x + rect2.w &&
rect1.y + rect1.h > rect2.y &&
rect1.y < rect2.y + rect2.h){
// Expel rect1 from rect2 here using objectToMove as the object being expelled (In this case, rect1).
};
};
多谢您的回覆。
我应该告诉你大局。我试图做一个函数,在其中输入3个
rect
对象,以测试它们是否发生碰撞,如果发生碰撞,我希望第三个rect
对象相应地移动。例如,函数参数为rect1
,rect2
,rect1
,这意味着当rect1
与左侧的rect2
相交时,我希望第三个参数rect1
向左移动 最佳答案
一种方法是确定在X或Y方向上移动所需的最小数量,然后移动该数量。这不考虑任何边界矩形:
function doCollision(rect1, rect2, objectToMove){
if (rect1.x + rect1.w > rect2.x &&
rect1.x < rect2.x + rect2.w &&
rect1.y + rect1.h > rect2.y &&
rect1.y < rect2.y + rect2.h){
if (objectToMove === rect1) {
moveOutside(objectToMove, rect2);
}
else if (objectToMove === rect2) {
moveOutside(objectToMove, rect1);
}
};
};
function moveOutside(rectToMove, otherRect) {
// Determine if the overlap is due more to x or to y,
// then perform the appropriate move
var moveOverOtherX = rectToMove.x + rectToMove.w - otherRect.x;
var otherOverMoveX = otherRect.x + otherRect.w - rectToMove.x;
var moveOverOtherY = rectToMove.y + rectToMove.h - otherRect.y;
var otherOverMoveY = otherRect.y + otherRect.h - rectToMove.y;
var minOver = Math.min(moveOverOtherX, otherOverMoveX, moveOverOtherY, otherOverMoveY);
if (minOver == moveOverOtherX) {
rectToMove.x = otherRect.x - rectToMove.w;
}
else if (minOver == otherOverMoveX) {
rectToMove.x = otherRect.x + otherRect.w;
}
else if (minOver == moveOverOtherY) {
rectToMove.y = otherRect.y - rectToMove.h;
}
else {
rectToMove.y = otherRect.y + otherRect.h;
}
rectToMove.update();
}
在a fiddle here中查看。