弹跳球动画不起作用

时间:2015-12-11 20:43:26

标签: javascript jquery css animation

我想制作一个简单的弹跳球。每当我按下向上箭头键时,球应该变高并跌倒。我实施了一个变量“重力”,它降低了球的速度。嗯,这很有效。但是一次又一次单击向上箭头键后,动画变得越来越快。我不明白为什么,因为我刚开始编程,而且我并不是很有经验。

这是带有HTML和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>

1 个答案:

答案 0 :(得分:2)

您需要将setInterval函数分配给变量,以便每次按向上箭头键后clearInterval。{/ p>

您还需要在keydown函数内初始化bounce变量。

更新了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