反弹球会重置到所需位置,但不会移动

Bouncing ball resets to desired position but does not move

本文关键字:位置 移动      更新时间:2023-09-26

我正在尝试制作壁球游戏,并认为设置球的移动是一个很好的开始。我已经设法让球按我想要的方式反弹,它从左上角50像素处落下,反弹两次,然后重置到开始的位置。重置后,球没有继续移动,而是停留在距离上角50像素的位置
为什么重置后球没有移动?如何使球从重置开始移动
从这里开始,我想设置一个事件监听器来重新开始投球,然后再次"发球"。任何关于把它放在哪里的建议都会很棒。这是我第一次尝试编写自己的游戏,所以请记住,我是个十足的傻瓜。

这是我的画布代码。

<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>

球停止反弹,因为当前代码在第二次反弹后连续调用ballReset()。您应该在重置方法中重置ballBounce计数器以保持其跳动。Fiddle

function ballReset() {
     ballX = ballStartPos;
     ballY = ballStartPos;
     ballBounce = 0; // Added code
 }