Time for action – moving the paddle with the accelerometer

As mentioned earlier, accelerometer events cannot be tested in the simulator. They only work when a game build is uploaded to a device to see the results. The paddle movement will stay within the wall borders of the level across the x axis. To move the paddle, follow the steps:

  1. Below the dragPaddle() function, create a new function called movePaddle(event):
    function movePaddle(event)
  2. Add in the accelerometer movement using yGravity. It provides acceleration due to gravity in the y direction:
      paddle.x = display.contentCenterX - (display.contentCenterX * (event.yGravity*3))
  3. Add in the wall borders for the level and close the function:
      if((paddle.x - paddle.width * 0.5) < 0) then
        paddle.x = paddle.width * 0.5
      elseif((paddle.x + paddle.width * 0.5) > display.contentWidth) then
        paddle.x = display.contentWidth - paddle.width * 0.5
      end
    end

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

We have applied the same code for the paddle from function dragPaddle():

This still keeps the paddle from going past any wall boundaries.