如何在我的Pong游戏中找到一个错误?
问题描述:
我正在制作一款游戏Pong,并且我试图让球反弹离开桨但它不起作用。相反,它正在执行“resetGame”的事情。我在console.log
里面写了一些东西,看它什么时候不工作,并且发现它不是在执行if
语句,而是直接回到else
语句,即使我正在做的事情应该会触发if
语句。如何在我的Pong游戏中找到一个错误?
顺便说一句,我使用的JavaScript,并且它不说,有在控制台和我只是与谷歌打开它的任何错误。
这里是代码:
<html>
<h3>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -PONG- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -</h3>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 11;
var ballSpeedY = 5;
var playerPaddleY = 240;
const paddleHeight = 120;
function calculateMousePos(evt) {
var rect = canvas.getBoundingClientRect();
var root = document.documentElement;
var mouseX = evt.clientX - rect.left - root.scrollLeft;
var mouseY = evt.clientY - rect.top - root.scrollTop;
return {
x:mouseX,
y:mouseY
};
}
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
var framesPerSecond = 30;
setInterval(function() {
moveEverything();
drawEverything();
}, 1000/framesPerSecond);
canvas.addEventListener('mousemove',
function(evt) {
var mousePos = calculateMousePos(evt);
playerPaddleY = mousePos.y- (paddleHeight/2);
});
}
function ballReset() {
ballX = canvas.width/2;
ballY = canvas.height/2;
ballSpeedX = -ballSpeedX;
}
function moveEverything() {
ballX = ballX + ballSpeedX;
ballY = ballY + ballSpeedY;
if (ballX > canvas.width) {
ballReset();
}
if(ballX < 0) {
console.log("hello");
if(ballY > playerPaddleY && ballY < paddleHeight) {
console.log("hellooo");
ballSpeedX = -ballSpeedX;
}
else {
console.log("helloooooo");
ballReset();
}
}
if(ballY > canvas.height) {
ballSpeedY = -ballSpeedY;
}
if(ballY < 0) {
ballSpeedY = -ballSpeedY;
}
}
function drawEverything() {
canvasContext.fillStyle = 'black';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
canvasContext.fillStyle = 'white';
canvasContext.fillRect(0, playerPaddleY, 13, paddleHeight); // player
canvasContext.fillRect(785, 240, 13, 120); //computer player
canvasContext.beginPath();
canvasContext.arc(ballX, ballY, 10, 0,Math.PI*2, true); //ball
canvasContext.fill();
}
</script>
</html>
答
这是行。
if(ballY > playerPaddleY && ballY < paddleHeight) {
你想如果你CONSOLE.LOG()BALLY,playerPaddleY和paddleHeight将成为明显的是,你正在比较中的像素BALLY位置的高度,以改变
if((ballY > playerPaddleY) && (ballY < (playerPaddleY + paddleHeight))) {
桨,这显然失败了。
+0
好的,谢谢你,你解决了我的问题 –
商标资本化;拼写;语法;降噪。 – Cerbrus