简体   繁体   中英

Javascript can't detect collision axis between two Divs

Am detecting if 2 divs overlap, and if they do, I am checking the distance between rectangle 1's right side and rectangle 2's left side, rectangle 1's top and rectangle 2's bottom, ect, ect.

    if (rect1.right > rect2.left &&
        rect1.left < rect2.right &&
        rect1.top < rect2.bottom &&
        rect1.bottom > rect2.top) {

        //collision detected.

        var dtop = Math.abs(rect1.top - rect2.bottom);
        var dbot = Math.abs(rect1.bottom - rect2.top);
        var dright =Math.abs(rect1.right - rect2.left);
        var dleft = Math.abs(rect1.left - rect2.right);
        var closestSide = Math.min(dtop,dbot,dright,dleft);

        if (closestSide == dleft || dright) {
            collisionAxis = "x";
        } 

        if (closestSide == dtop || dbot) {
            collisionAxis = "y";
        } 

        alert("collisionAxis: " + collisionAxis);

        return collisionAxis;

    }

For some reason, collisionAxis is always being set to "y", even when closestSide == dleft || dright even when closestSide == dleft || dright , which should set collisionAxis to "x"...

Here is a JSFiddle example. The variable collisionAxis in my DetectCollision function should be set to "x" when the white rectangle collides with the black rectangle, since closestSide = dright , yet somehow it is being set to "y".

Can anyone please tell me why?

It should be,

    if (closestSide == dleft || closestSide == dright) {
        collisionAxis = "x";
    } 

    if (closestSide == dtop || closestSide == dtopdbot) {
        collisionAxis = "y";
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM