Javascript“球”弹跳

时间:2014-10-19 14:38:56

标签: javascript html

我是JS noob。我正在进入浏览器游戏编程,想要快速举例说明球落球和弹跳只是为了学习。出于某种原因,当我创建一个jsfiddle时,我的代码实际上没有工作,我的div的onclick事件=" ball"似乎没有附加,但是当我在浏览器中运行它时,它确实如此。但这不是我的问题。

在此代码中,用户点击球,这只是一个黑色bg的div。然后div跟随用户光标,当用户第二次单击时,div开始向窗口底部下降。当它碰到底部时,它应该反弹回来,其最初落下的y坐标与窗口底部之间的距离的一半。因此,如果它在y位置600下降并且页面底部是800,则第一次反弹的顶点应该是700.第二次反弹,顶点将是750.第三次反弹,775。你明白了。有人可以帮我一点吗?我猜我每次击球时都需要增加一个计数器?

<html>
<head>
<style>
#ball {
    width: 50px;
    height: 50px;
    background-color: black;
    position: absolute;
}
</style>
<script>

window.onload = function() {

    var ballClicked = false;
    var ballFalling = false;
    var ballX = 100;
    var ballY = 100;
    var timesBounced = 0;
    var bounceApex = 0;
    var startingDropHeight = 0;
    var intervalVar;
    var ball = document.getElementById("ball");
    ball.style.left = ballX;
    ball.style.top = ballY;

    ball.onclick = function() {
        if (ballClicked == false) {
            ballClicked = true;
        } else {
            ballClicked = false;
            ballFalling = true;
            startingDropHeight = ballY;
            intervalVar = setInterval(function(){dropBall()} , 5);
        }
    };

    document.onmousemove = function(e) {
        if (ballClicked == true) {
            ballX = e.pageX;
            ballY = e.pageY;
            ball.style.left = ballX;
            ball.style.top = ballY;
        }
    };

    function dropBall() {
        if (ballFalling == true) {
            ballY = ballY + 1;
            ball.style.top = ballY;
            if (ballY == window.innerHeight - 50) {
                timesBounced = timesBounced + 1;
                bounceApex = (startingDropHeight + (window.innerHeight - 50)) / 2;
                ballFalling = false;
                if (bounceApex > window.innerHeight - 50) {
                    clearInterval(intervalVar);
                }
            };
        } else {
            ballY = ballY - 1;
            ball.style.top = ballY;
            if (ballY == bounceApex) {
                ballFalling = true;
            };
        }
    };

};

</script>
</head>
<body>
<div id="ball"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

添加左侧和顶部样式时,您还需要指定单位。所以,而不是:

ball.style.left = 100;

它应该是:

ball.style.left = "100px";

我已经修复了你的代码并制作了一个有效的jsfiddle,会稍微改善一下弹跳。请在此处查看:http://jsfiddle.net/12grut99/

关于重复弹跳,这一行就是问题:

bounceApex = (startingDropHeight + (window.innerHeight - 50)) / 2;

您总是根据原始下落高度计算顶点,但每次反弹后,下降高度应为之前的bounceApex(球到达的最高点)。