简体   繁体   中英

an if statement returns true, but the condition won't trigger

I have an if statement in my code as you can see below. When I check in console log when those two elements collide with each other, the if statement becomes true, but it won't stop my interval function. I wonder what would have caused it to not work as it should?

var animationTimer = setInterval(bladAnimation, 30);

document.onkeydown = function(event) {
    if (event.keyCode == 37) {
        // <--
        fx = -15;
        fy = 0;
        froskAnimation()
    }
    if (event.keyCode == 38) {
        // opp
        fy = -15;
        fx = 0;
        froskAnimation()
    }
    if (event.keyCode == 39) {
        // -->
        fx = 15;
        fy = 0;
        froskAnimation()
    }
    if (event.keyCode == 40) {
        // ned
        fy = 15;
        fx = 0;
        froskAnimation()
    }
}

function froskAnimation() {

    Xfrosk = fx + Xfrosk;
    Yfrosk = fy + Yfrosk;

    if ((Yfrosk + 70 > maxY) || (Yfrosk < minY)) {
        Yfrosk = Yfrosk - fy;
    }
    if ((Xfrosk + 70 > maxX) || (Xfrosk < minX)) {
        Xfrosk = Xfrosk - fx;
    }

    frosk.style.left = Xfrosk + "px";
    frosk.style.top = Yfrosk + "px";
    console.log(Xfrosk)
}

function bladAnimation() {
    Yblad = by + Yblad;

    if ((Yblad + 70 > maxY) || (Yblad < minY)) {
        by = by * -1;
    }

    blad.style.top = Yblad + "px";
}

if (blad.x < frosk.x + frosk.width  && blad.x + blad.width  > frosk.x 
        && blad.y < frosk.y + frosk.height && blad.y + blad.height > frosk.y) {
    clearInterval(animationTimer);
}

full code here: https://codepen.io/ctrlvi/pen/jXbJYG

That condition is executed only once, when your javascript is loaded. At that point the condition is probably false. You should move it at the end of bladAnimation (I suppose what you're trying to do is stop the self-moving block when it hits the other one).

function bladAnimation() {
    Yblad = by + Yblad;

    if ((Yblad + 70 > maxY) || (Yblad < minY)) {
        by = by * -1;
    }

    blad.style.top = Yblad + "px";

    if (blad.x < frosk.x + frosk.width  && blad.x + blad.width  > frosk.x 
        && blad.y < frosk.y + frosk.height && blad.y + blad.height > frosk.y) {
        clearInterval(animationTimer);
    }

}

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