Dennis
Dennis

Reputation: 11

Bouncing Ball Animation doesn't work

I want to create a simple bouncing ball. Whenever I press the UP Arrow key, the ball should get higher and falls down. I implemented a variable "gravity", which reduce the velocity of the ball. Well, that works. But after clicking the UP Arrow key again and again, the animation is getting faster and faster. I can't see why, since I've just started with programming and I am not really experienced.

Here's the code with HTML and CSS

<html>  
<head>
    <style>
        #objekt{
            width:20px;
            height:20px;
            background-color: blue;
            position:absolute;
            border-radius: 100%;
        }
        #line{
            width:100%;
            height:1px;
            background-color:black;
            position:absolute;
            top:220px;
        }
    </style>
    <script type = "text/javascript" src = "jquery-2.1.4.min.js"></script>
    <script>
    $(document).ready(function(){
        var objekt = $("#objekt");
        var x = 30;
        var y = 200;
        var vely = -3;
        var velx = 1;
        var gravity = 0.05;
        var bounce = -3;

        $(document).on("keydown", function(e){
            if(e.which == 38){  
                setInterval(function jumpObjekt(){
                    y += vely;
                    vely += gravity;
                    console.log(vely);
                    if(y > 200) vely = bounce;
                    if(bounce < 0){
                        bounce = bounce + 0.01;
                    } else {
                        bounce = 0;
                    }
                }, 10);
                vely = -3;
            }
        });

        setInterval(function(){
            objekt.css({
                    top: y,
                    left: x,
            });
        },10);
    });
    </script>
</head>

<body>
    <div id = "objekt"></div>
    <div id = "line"></div>
</body>

Upvotes: 1

Views: 229

Answers (1)

Shishir Morshed
Shishir Morshed

Reputation: 837

You need to assign setInterval function to a variable so you can clearInterval after pressing up arrow key every time.

You also need to initialized bounce variable inside keydown function.

Updated JS

var bounceHandler;
$(document).on("keydown", function(e){
    if(e.which == 38){  
        clearInterval(bounceHandler);
        var bounce = -3;
        bounceHandler = setInterval(function jumpObjekt(){
            y += vely;
            vely += gravity;
            console.log(vely);
            if(y > 200) vely = bounce;
            if(bounce < 0){
                bounce = bounce + 0.01;
            } else {
                bounce = 0;
            }
        }, 10);
        vely = -3;
    }
});

Working Demo using your code

Upvotes: 2

Related Questions