HTML Pong尝试不起作用

3

我已经开始了一个乒乓球游戏,其中指南已经为我设定好了,但是我遇到了一个问题:球有问题。虽然这个游戏还处于早期开发阶段,但我却卡在了这个问题上:X轴无法上下移动。球现在还不能从球拍上弹起。以下是我的代码:

Index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Ping Pong</title>
        <link href="pong.css" rel="stylesheet" type="text/css"/>
        <script src="js/jquery.js" type="text/javascript"></script>
        <script src="js/pong.js" type="text/javascript"></script>
</head>
<body>

    <header>
        <h1>Ping Pong</h1>
    </header>

        <!-- Scoreboard goes here -->

    <div id="game">
        <div id="playground">
                    <div id="ball"></div>
                    <div id="paddleA" class="paddle"></div>
                    <div id="paddleB" class="paddle"></div>
        </div>
    </div>

    <!-- used for debugging -->
    <div id="debug">
    </div>

    <footer>
        This is an example of creating a Ping Pong Game.
    </footer>   

</body>
</html>

Pong.js

var KEY = {
 UP:38,
 DOWN:40,
 W:87,
 S:83
};

var directionX = 1;
var directionY = 1;



$(function(){
   var timer = setInterval(gameloop,30)
});

//This is where the logic for the game goes.
function gameloop(){
    var playground = $("#playground");
    var ball = $("#ball");

    var width = parseInt (playground.css("width"))
    var left = parseInt (ball.css("left"));

    if(left >= width){
        directionX = -1;
    }
    else if (left <= 0){
        directionX = 1;    
    }   

    var height = parseInt (playground.css("height"))
    var top = parseInt (ball.css("top"));

    if(top >= height){
        directionY = -1;
    }
    else if (top <= 0){
        directionY = 1;    
    }   



    ball.css("left",left+5 * directionX);
    ball.css("top",height+5 * directionY);

}

function debug(text){
    $("#debug").text(text);
}

还有pong.css

#playground{
    background: #e0ffe0 /*url(images/pixel_grid.jpg)*/;
    width: 400px;
    height: 200px;
    position: relative;
    overflow: hidden;
}

#ball {
    background: #fbb;
    position: absolute;
    width: 20px;
    height: 20px;
    left: 150px;
    top: 100px;
    border-radius: 10px;
}

.paddle {
    background: #bbf;
    left: 50px;
    top: 70px;
    position: absolute;
    width: 30px;
    height: 70px;
}

#paddleB {
    left: 320px;
}

#winner{
    display:none;   
    position: relative;
    width: 200px;
    margin-left: 100px;
    top: 30%;
    font-size: 20px;
    border: 3px solid red;
    padding: 20px;
    background-color: #FFF;
    text-align:center;
    font-family: Comic-Sans;
}

顺便提一下,如果你想知道的话,这个JS库是为我编写的。

2个回答

1

您正在使用元素的 height 而不是偏移量 (top)。应该是

ball.css("top", top + 5 * directionY);

0
我相信你在设置CSS的top和left时需要使用px单位。
ball.css("left",(left+5 * directionX) + "px");
ball.css("top",(height+5 * directionY) + "px");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接