Space Demon is a vertical shooter game which takes place in space. In the previous articles we setup the environment, move our spaceship and got killed by a fire throwing demon. In this article we are going to add accelerometer input to our application which will improve user game play experience.
In our current game we move our spaceship by touching on the screen. The spaceship moves in either left or right direction. By introducing the accelerometer input we can eliminate the unnecessary touch events. Accelerometer will allow us to move the spaceship by tiling the device to the left or right. This will create a much better user experience.
Implementing Accelerometer Input:
Cocos2d framework makes it easy to use the accelerometer. The first task is to enable the accelerometer which can be performed using a single line of code:
Next, we need to setup a method which will be called at regular intervals by the accelerometer. The following implementation sets up the updateInterval:
The above code represents that the accelerometer will send the updates every 0.1 seconds. The updates are sent to the accelerometer method which is implemented below:
The movementSpeed variable sets the speed of the spaceship. You can change it to a faster speed with a higher value or a slower speed with a lower value. The setPosition method of the sprite is used to place the spaceship at a particular position on the screen.
Testing the Accelerometer:
In order to test the accelerometer you need to run the application on a device instead of the simulator. iPhone simulator does not have the ability to simulate the accelerometer. There are frameworks like iSimulate which will allow you to use the accelerometer on the simulator by sending the signals from the actual device. iSimulate is available in the app store for $15.
In this article we implemented the accelerometer input for our Space Demon game. In the next article we will add additional features to our game.