Search code examples
javascriptfunctioncollisionrect

How to expel a rect from inside another rect - Javascript


I am trying to make rect1 move out from inside rect2. I have tried to look around for an awsner but i am unable to find a satisfactory awnser. I can detect the rectangles intersecting, but i cannot expel rect1 so it goes outside rect2. Can you provide some code to help me do this? I will provide my detection code so far.

Code:

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

Thank you for responding if you do.

i should tell you the bigger picture. I am trying to make a function where i input 3 rect objects, to test if they are colliding or not, and if so, i want the third rect object to move accordingly. For example, the function parameters are rect1, rect2, rect1, meaning when rect1 intersects rect2 on the left side, i want the third parameter rect1 to move left


Solution

  • One approach would be to identify the minimum amount needed to move in either X or Y directions and then move that amount. This does not take any bounding rectangles into account:

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

    See it in a fiddle here.