In this final section, we’ll complete ghostTouched(), which is the code that’ll be called every time the player successfully taps a ghost object. This code will register the touch event and double-check that the player is at the start of Corona’s multi-step touch sequence.
Once the touch event has been checked and registered, the system will increase the player’s score by one point and remove the ghost object. While we’re writing this score code, we’ll add a line that’ll display the player’s score on screen, so they can keep track of how well they’re doing.
But there’s one more scenario to consider and that’s what’ll happen if a ghost object isn’t touched, but falls off screen. Rather than these objects building up off screen, where they could potentially cause problems, we’ll write some code that deletes any ghost objects that the player can no longer see.
1. Display player’s score
Beneath (1000,timerDown,timeLimit), set the initial score: score = 0. Then: scoreText = display.newText(“Score:” ..score, 160, 10, native.systemFontBold, 20). This will display the text Score: followed by the current score. The rest defines the style and position of the text.
Tell Corona we’re defining the ghostTouched event we mentioned earlier in our code, by adding the following: local function ghostTouched(event). On the next line, check we’re at the beginning of Corona’s touch sequence: if ( event.phase == “began” ) then.
3. Get rid of the ghost
If we’re at the beginning of this sequence then the object has been touched and needs to be removed. Add these two lines: Runtime:removeEventListener( “enterFrame”, event.self ) / event.target:removeSelf(). Next, increase the user’s score: score = score + 1.
4. Close the code block
Next, check this new score displays correctly: scoreText.text = (“Score: “..score, 160, 10, native.systemFontBold, 20). Close this block of code with two lines: end / end. The next block will tell the system to delete any untouched ghost objects that fall off screen.
5. Has the ghost gone?
The first step in this process is checking that the ghost object hasn’t been deleted. One way is to test whether the object’s y coordinate is zero; if it is zero then the object has been deleted: local function offscreen(self, event) / if(self.y == nil) then / return / end.
6. Delete the ghost
If the coordinate isn’t zero, check using an amount of pixels. We’re using 20 pixels: if(self.y > display.contentHeight + 20) then. If it is, then that object is unreachable. To delete it: Runtime:removeEventListener( “enterFrame”, self ) / self:removeSelf() / end / end.