Time for action – moving the character

Eggs will be falling in all different areas of the screen from the sky. Let's prepare our main character to move through all the potential areas on the screen:

  1. Set up a new local function called moveChar() with an event parameter:
    local moveChar = function(event)
  2. Add in the accelerometer movement for the character:
      charObject.x = display.contentCenterX - (display.contentCenterX* (event.yGravity*3))
  3. Create character boundaries where it moves on the screen. This enables the character to stay within the game screen and not go past the offscreen boundaries:
      if((charObject.x - charObject.width * 0.5) < 0) then charObject.x = charObject.width * 0.5
      elseif((charObject.x + charObject.width * 0.5) > display.contentWidth) then
      charObject.x = display.contentWidth - charObject.width * 0.5
      end
    end

To make the accelerometer movement work with a device, we have to use yGravity.

Notice that the code in step 3 keeps the charObject display object from going past any wall border boundaries.

The character is currently controlled by the accelerometer. Another option to control the character is through a touch event. Try replacing the event listener with "touch" and using event parameters so that the touch event works properly.

If you remember how we incorporated the paddle movement with Breakout in Chapter 3, Building Our First Game – Breakout and Chapter 4, Game Controls, for the simulator, it should be very similar.

When the score is updated, it refers to our text display objects and translates the value from the number into a string.

Here is an example:

In the previous example, you will notice that we set a value of 100 to gameScore. In the following lines for scoreText, gameScore is used to concatenate the "Score: " string and the value of gameScore. Doing so displays the value of gameScore in a string format by scoreText.