我正在制作基于本教程的游戏:https://developer.mozilla.org/en-US/docs/Games/Workflows/2D_Breakout_game_pure_JavaScript
我想我理解了桨左右移动的方式。但是,当我试图让它上下移动时,它根本不起作用。我确实尝试过各种各样但仍然无法正常工作。那么问题是我如何让它上下移动?
以下是整个代码:
<script>
var canvas = document.getElementById("tausta");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var paddleY = canvas.height-paddleHeight;
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
if(e.keyCode == 37) {
leftPressed = true;
}
if(e.keycode == 38){
upPressed = true;
}
if(e.keycode == 40){
downPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
if(e.keyCode == 37) {
leftPressed = false;
}
if(e.keycode == 38){
upPressed = false;
}
if(e.keycode == 40){
downPressed = false;
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, paddleY, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy;
}
if(rightPressed && paddleX < canvas.width-paddleWidth) {
paddleX += 5;
}
if(leftPressed && paddleX > 0) {
paddleX -= 5;
}
if(upPressed && paddleY < canvas.height-paddleHeight) {
paddleY += 5;
}
if(downPressed && paddleY > 0) {
paddleY -= 5;
}
x += dx;
y += dy;
}
setInterval(draw, 10);
</script>
答案 0 :(得分:1)
原来这是一个简单的错误。 你输入了
if(e.keycode == 38){
if(e.keycode == 40){
但它应该是
if(e.keyCode== 38){
if(e.keyCode== 40){
资本C