
上QQ阅读APP看书,第一时间看更新
Time for action — controlling the ball with the player's paddle
It's nice to see the ball bounce off the walls, but in a game of Pongo, you need to be able to control the ball with your paddle. So we will implement this now. Follow the given steps:
- Let's start with the player paddle. We need a new method that checks the collision of the ball with the player's paddle. Create a new method called
CheckPaddleCollP
. Please note the return type is Boolean.Method CheckPaddleCollP:Bool()
- Next, we want to check if the ball is close to the paddle regarding its X position.
If bX > 625.0 Then
- The next check will be if the ball's Y position is between minus 25 pixels and plus 25 pixels from the paddel's Y position. If yes, then return
True
from this method.If ((bY >= pY-25.0) and (bY <= pY+25.0)) Then Return True Endif
- Now, close off the first
If
check, returnFalse
, because the ball didn't hit the paddle, and then close the method.Endif Return False End
- Ok, now we need to call
CheckPaddleCollP
from somewhere. We implement it inside theUpdateGame
method. We make anIf
check againstCheckPaddleCollP
, if it isTrue
and also if the ball's X speed is positive. That means it goes from left to right.UpdateBall() 'Update the ball's position If CheckPaddleCollP() = True And bdX > 0 Then
- If the paddle got hit, then first we inverse its X speed and bounce it back.
BdX *= -1
- Next, we want to check where it hit the paddle exactly. In the top area, the ball should bounce upwards. In the lower area, it should bounce downwards. And in the middle, it should bounce back straight. At the end, we will close the former
If
check.If ((bY - pY) > 7) Then bdY = 1.5 If ((bY - pY) < -7) Then bdY = -1.5 If ((bY - pY) <= 7) And ((bY - pY) >= -7 Then bdY = 0 Endif
Ok, save here and test the code again. You are able to play back the ball. For the next step, you can load up the file
Pongo_08.Monkey
, if you need to.