Pong | Sending a message from the ball to the score object.

When a goal is scored, the ball object needs to send a message to the score object. This is necessary because only the score object can update itself due to encapsulation. However, the score object has no way of knowing when a goal has been scored. It relies on the ball to inform it.

  1. In the assets panel, double click the ball.script file. In the update function, change the code after the comment as shown to send a message when a goal is scored.
	-- check if a goal has been scored
	if pos.x < -15 then
		msg.post("score", "player2_scored")
		spawn_ball(self)
	end
	if pos.x > 975 then
		msg.post("score", "player1_scored")
		spawn_ball(self)
	end
What does this code do?

If the ball has gone off the left side of the screen, before it is respawned it sends a message to the score object with the string, "player2_scored".

If the ball has gone off the right side of the screen, before it is respawned it sends a message to the score object with the string, "player1_scored".

  1. Save the changes by pressing CTRL-S or 'File', 'Save All'.

The game won't keep score just yet. We now need the score object to listen for this message. Stage 8c >