我正在制作一场比赛,Pong,我正试图让球从球拍上反弹,但它无法正常工作。相反,它正在做“重置游戏”的事情。我把console.log
的东西放进去看看它什么时候不起作用,并发现它没有做if
语句而且直接进入else
语句,即使我正在做那些应该做的事情触发if
语句。
顺便说一句,我使用的是JavaScript,并没有说控制台中有任何错误 和 我只是在Google上打开它。< / p>
这是代码:
<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>
答案 0 :(得分:1)
这就是这条线。
if(ballY > playerPaddleY && ballY < paddleHeight) {
您要更改为
if((ballY > playerPaddleY) && (ballY < (playerPaddleY + paddleHeight))) {
如果你使用console.log()ballY,playerPaddleY和paddleHeight,你会发现当前正在将ballY位置与桨的像素高度进行比较,这显然会失败。