2013-10-22 35 views
2

我已經開始了一個乒乓球比賽,其中的準則已經爲我設定,但我有一個球的問題。它在開發的早期階段,但我堅持這個問題:X軸不會上下移動。球並不意味着反彈了槳。這裏是我的代碼:HTML Pong試圖不工作

的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庫是爲我寫的。

回答

0

我相信你需要在設置頂部和左側的CSS時使用px。

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

您正在使用的元素,而不是偏移量(top)的height。 應該是

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