MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

这篇翻译不完整。请帮忙从英语翻译这篇文章

这是 Gamedev Canvas tutorial教程的第10步。您可以在完成本课程后在这里Gamedev-Canvas-workshop/lesson5.html找到源代码。

It's fun to watch the ball bouncing off the walls and be able to move the paddle around, but other than that the game does nothing and doesn't have any progression or end goal. It would be good from the gameplay point of view to be able to lose. The logic behind losing in breakout is simple. If you miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over.

Implementing game over

Let's try to implement game over in our game . Here's the piece of code from the third lesson where we made the ball bounce off the walls:

if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
    dx = -dx;
}

if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
    dy = -dy;
}

Instead of allowing the ball to bounce off all four walls, let's only allow three now — left, top and right. Hitting the bottom wall will end the game. We'll edit the second if block so it's an if else block that will trigger our "game over" state upon the ball colliding with the bottom edge of the canvas. For now we'll keep it simple, showing an alert message and restarting the game by reloading the page. Replace the second if statement with the following:

if(y + dy < ballRadius) {
    dy = -dy;
} else if(y + dy > canvas.height-ballRadius) {
    alert("GAME OVER");
    document.location.reload();
}

Letting the paddle hit the ball

The last thing to do in this lesson is to create some kind of collision detection between the ball and the paddle, so it can bounce off it and get back into the play area. The easiest thing to do is to check whether the center of the ball is between the left and right edges of the paddle. Update the last bit of code you modified again, to the following:

if(y + dy < ballRadius) {
    dy = -dy;
} else if(y + dy > canvas.height-ballRadius) {
    if(x > paddleX && x < paddleX + paddleWidth) {
        dy = -dy;
    }
    else {
        alert("GAME OVER");
        document.location.reload();
    }
}

If the ball hits the bottom edge of the Canvas we need to check whether it hits the paddle . if yes, then it bounces off just like you'd expect; if not then the game is over as before.

代码对比

这里是完整例子对比一下代码吧!

Exercise: make the ball move faster when it hits the paddle.

下一步

We're doing quite well so far and our game is starting to feel a lot more worth playing now you can lose! But it is still missing something. Let's move on  to the sixth chapter — Build the brick field — and create some bricks for the ball to destroy.

文档标签和贡献者

 此页面的贡献者: usernameisMan
 最后编辑者: usernameisMan,