Pong | Playing the sounds.

  1. In the assets panel, double click the 'ball.script' file. (Or the 'ball - /main/ball.script' object in the outline panel).
  2. In the update function, find the section with the comment, '-- check if a goal has been scored'. Insert two lines of code to play the goal sound before the ball is respawned.
	-- check if a goal has been scored
	if pos.x < -15 then
		msg.post("score", "player2_scored")
		sound.play("#goal")
		spawn_ball(self)
	end
	if pos.x > 975 then
		msg.post("score", "player1_scored")
		sound.play("#goal")
		spawn_ball(self)
	end
What does this code do?

sound.play takes a single parameter which is the Id of the sound object you wish to play. Note, the Id is prefixed with a hash symbol. The sound will stop when it is complete. You can make a sound loop by changing it's 'Looping' property. There are many more settings too. You can stop a sound with sound.stop.

  1. In the on_message function, find the line of code towards the end that normalises the new vector after the ball bounces off the paddle. Insert a line of code to play the bounce sound as the last action of the if condition.
function on_message(self, message_id, message, sender)
	if message_id == hash("contact_point_response") then
		go.set_position(go.get_position() + message.normal * message.distance)
		self.direction.x = -self.direction.x
		self.direction.y = -self.direction.y
		local dist = go.get_position(sender) - go.get_position()
		self.direction.y = self.direction.y - dist.y / 150
		self.direction = vmath.normalize(self.direction)
		sound.play("#bounce")
	end
end
  1. Save the changes by pressing CTRL-S or 'File', 'Save All'.
  2. Run your game. It should now have some simple sound effects that are played when the ball bounces off the paddle or when a goal is scored.
  3. Run

The tutorial is now complete, but we can always make it better! Stage 10 >

Debugging

If your code doesn't work and you can't hear any sounds, consider the following potential issues:

  1. Is the volume turned up? Can you hear other sounds from your computer OK?
  2. Check the properties of the sound objects. Are they pointing to the sound files?
  3. Did you remember to set the 'Id' of the sound objects to 'bounce' and 'goal'? Check for spelling errors.
  4. Did you add the code to the ball object to play the sound in the correct place in the functions?
  5. Did you refer to the correct object names? #bounce, #goal
  6. Are you still running a previous version of the game without reloading?
    Check the windows you have open.