Pong | Updating the score.
The score game object needs to respond when it receives a message to update the score.
- In the assets panel, right click the main folder (or any file inside it) and select, 'New...', 'Script'.
- Name the script, 'score', and click, 'Create Script'.
- In the init function of the score script, initialise the two variables to hold the scores for each player.
function init(self)
self.player1_score = 0
self.player2_score = 0
end
- In the on_message function, add the code to respond to the messages that the score object can receive.
function on_message(self, message_id, message, sender)
if message_id == hash("player1_scored") then
self.player1_score = self.player1_score + 1
label.set_text("#label", self.player1_score .. " : " .. self.player2_score)
end
if message_id == hash("player2_scored") then
self.player2_score = self.player2_score + 1
label.set_text("#label", self.player1_score .. " : " .. self.player2_score)
end
end
What does this code do?
If the score object receives a message that player1 has scored it increments the player1_score variable before updating the text in the label. Note 'label' is the id of the label object. We prefix this with a # symbol.
two dots (..) is a concatenator operator in Lua. This joins variables and strings together. The player1_score variable is concatenated with a colon and the player2_score.
- Finally it is important to remember to attach this script file to the score game object. In the assets panel, double click, 'main.collection'.
- In the outline panel, right click, 'score' and select, 'Add Component File'.
- Choose, '/main/score.script' and click 'OK'.
- Save the changes by pressing CTRL-S or 'File', 'Save All'.
- Run your game at this point. It should now keep the score.
Our game logic is now finished, but it would be nice to add some sound effects. Stage 9a >