2
我想做一個壁球遊戲,並認爲設置球運動將是一個很好的開始。我已經設法按照我想要的方式彈起球,它從左上角的50px下降,反彈兩次,然後重置回開始的位置。重置後不再繼續移動,球從頂角停留在50px處。
重置後爲什麼球沒有移動?我如何讓球從重置移動?
從這裏我想設置一個事件監聽器來重新啓動球,然後再次「服務」球。任何建議放在哪裏將是非常棒的。這是我第一次嘗試編碼我自己的遊戲,所以請記住我是一個完整的noob。彈跳球重置到所需的位置,但不移動
這是我的畫布代碼。
<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>
也許想要速度重置 – James
謝謝你的工作 –