-1

I have been trying to create something like simple game in jQuery, and i want to have a div that can simulate jumpping. So i've written the following code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(document).keydown(function(e){
    $(".box").stop(true);   
    if (e.which == 37) { 
        if(parseInt($(".box").position().left)>49){
            $(".box").css("left", parseInt($(".box").position().left)-50);
        }
       return false;
    }
    if (e.which == 38) { 
    
       $(".box").animate({ 
        bottom: "+=50px",
        },function(){
            $(".box").animate({bottom: "-=50px"});
        });
       return false;
    }
    if (e.which == 39) { 
       
       return false;
    }
    if (e.which == 40) { 
       
       return false;
    }
    });
});
</script>
<div style="width:500;margin:0px auto;">
    <div class="main" style="width:500px;height:500px;border:1px solid #ccc;position:relative;">
        <div class="box" style="border:1px solid #ccc;width:50px;height:50px;box-sizing:border-box;position:absolute;left:100px;bottom:0px;"></div>
    </div>
</div>

So this code allows the box to move left and jump, with animated effect. The question is how to not just stop the animation (as in the code stop()) but to simply not allow the div class Box to jump further untill the animation is complete and the box is down to position bottom 0. Currently the code just stops the animation if you try to jump while the animation is running.

1 Answer 1

0

Actually I was able to find a solution. You simply add a variable false,and then on checking for arrow up key pressing you add codeto check if it is false, then add true when is animating, and after animation make it false again, so:

$(document).ready(function(){
    var isAnimating = false;

    $(document).keydown(function(e){
    if (e.which == 37) { 
        if(parseInt($(".box").position().left)>49){
            $(".box").css("left", parseInt($(".box").position().left)-50);
        }
       return false;
    }
    if (!isAnimating && e.which == 38) { 
        isAnimating = true;
        $(".box").animate({ 
            bottom: "50px",
                },function(){
                    $(".box").animate({bottom: "0px"},function(){
                    isAnimating = false; 
                    });
                });   
       return false;
    }
    if (e.which == 39) { 
       
       return false;
    }
    if (e.which == 40) { 
       
       return false;
    }
    });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.