我正在尝试制作壁球比赛,并认为设置球运动将是一个很好的起点。我设法让球以我想要的方式弹跳,它从左上角50px下降,弹跳两次然后重置回到它开始的位置。重置后,球不会继续移动,而是从顶角停留50px。
为什么重置后球不动?如何让球从重置中移开?
从这里开始我想设置一个事件监听器来重新启动球,然后再次“投球”。关于在哪里放置这个的任何建议都会很棒。这是我第一次尝试编写自己的游戏,所以请记住,我是一个完整的菜鸟。
这是我的画布代码。
<html>
<title>Squash Game V1</title>
<h1>Squash</h1>
<canvas id="gameCanvas" width=800 height=600></canvas>
<script>
var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var gravity = 0.2;
var bounceFactor = 0.6;
var ballSpeedX = 3;
var ballSpeedY = 10;
var ballSpeedY2 = 5;
var ballBounce = 0
var ballStartPos = 50
const resistence = 0.998
const ballWidth = 15;
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
var framesPerSecond = 60;
setInterval(function() {
moveEverything();
drawEverything();
}, 1000/framesPerSecond);
}
function ballReset() {
ballX = ballStartPos;
ballY = ballStartPos;
}
function moveEverything() {
// this moves ball down
ballY += ballSpeedY;
// this moves the ball across
ballX += ballSpeedX;
// this speeds ball up as it's falling plus slows down making it fall
ballSpeedY += gravity;
ballSpeedX = ballSpeedX*resistence;
//this bounes the ball
if (ballY > canvas.height - ballWidth) {
ballSpeedY = -ballSpeedY
//this reduces height of the bounce
ballSpeedY *= bounceFactor;}
//this should count bounces
if (ballY > canvas.height - ballWidth){
ballBounce = ballBounce + 1;
}
//ball will bounce of right wall
if (ballX > canvas.width - ballWidth) {
ballSpeedX = -ballSpeedX}
//ball will bounce off left wall
if (ballX < 0 + ballWidth) {
ballSpeedX = -ballSpeedX}
if (ballBounce >= 2) {
ballReset()}
}
function drawEverything() {
//this draws the pong court
colourRect(0,0,canvas.width,canvas.height, 'black');
//this draws the ball
colourCircle(ballX, ballY, 10, "white")
function colourCircle(centreX, centreY, radius, drawColour) {
canvasContext.fillStyle = drawColour;
canvasContext.beginPath();
canvasContext.arc(centreX, centreY, radius, 0,Math.PI*2, true)
canvasContext.fill();
}
//this function draws a rectangle
function colourRect(leftX, topY, width, height, drawColour) {
canvasContext.fillStyle = drawColour;
canvasContext.fillRect(leftX, topY, width, height);
} }
</script>
</html>
答案 0 :(得分:0)
球停止弹跳,因为你的当前代码在第二次反弹后不断调用ballReset()。您应该在重置方法中重置ballBounce
计数器以使其保持弹跳。 Fiddle
function ballReset() {
ballX = ballStartPos;
ballY = ballStartPos;
ballBounce = 0; // Added code
}