gpt4 book ai didi

javascript - HTML Pong 尝试不工作

转载 作者:行者123 更新时间:2023-11-28 01:51:59 24 4
gpt4 key购买 nike

我开始了一场乒乓球比赛,其中已经为我设定了指导方针,但我对球有疑问。这是开发的早期阶段,但我一直坚持这个问题:X 轴不会上下移动。球尚未从 Racket 上弹起。这是我的代码:

索引.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 库是为我编写的。

最佳答案

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

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

关于javascript - HTML Pong 尝试不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19528741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com