Pong | Handling the ball leaving the screen.
If the ball hits the top or bottom of the screen we need to change it's y direction. We can achieve this quite easily by using y = -y as described in stage 5 when we spawned the ball.
- In the assets panel, double click the ball.script file. In the update function, add the additional code to include checking if the paddle is about to leave the screen.
function update(self, dt)
-- move the ball in it's current direction at a speed in pixels per second
local pos = go.get_position()
pos = pos + self.direction * self.speed * dt
go.set_position(pos)
-- check if the ball has hit the top or bottom of the screen
if pos.y < 15 or pos.y > 625 then
self.direction.y = -self.direction.y
end
-- check if a goal has been scored
if pos.x < -15 then
spawn_ball(self)
end
if pos.x > 975 then
spawn_ball(self)
end
end
pos holds the vector3 position of the ball. We can access an element of this associative array by using a key (x, y, z etc.)
If the y position of the ball is less than 15 pixels or greater than 625 we know it has left the screen. This is because the game screen is 0-640 pixels tall. (Set in the game.project file). Since the position of all game objects is measured from their centre and the ball is 30x30 pixels, at -15 it is off the screen.
If the ball has left the screen we simply need to reverse it's direction.
A similar action is taken if the ball has left the left edge of the screen (x < -15) or the right edge of the screen (x > 975). The difference being we want to call the function to respawn the ball in this situation.
Note we have used two if statements instead of one when detecting a goal. (We could use if pos.x <- 15 or pos.x > 975). This is because we are using a computational method of "thinking ahead". We know that if the ball leaves the screen to the left we increase player 2's score, and from the right, player 1's score. Therefore we will need different actions later depending on who scored the goal. Therefore, it makes sense to use two seperate conditions here, ready for this code later.
We also used "thinking ahead" when we created a function to spawn the ball. We knew we'd need it here too.
- Save the changes by pressing CTRL-S or 'File', 'Save All'.
- Run your program. The ball should bounce off the top and bottom of the screen and respawn if a goal is scored.
We now need to either write the scoring feature or the paddle bouncing. It doesn't really matter which we choose. Let's do the paddle bounce next. Stage 7a >.