In the last project, we initialized our ship where it's supposed to start and we created the loop in our game loop. In this project, we're going to add the accelerometer and use it to get input from the user about which direction to move our ship (tilting the RaspberrySTEM left will move the ship left and tilting right will move the ship right). In this project, we'll use that input to animate our ship.
As we learned in Accelerometer, the initialization code for the accelerometer will consist of importing the Accel() function and then initializing the accelerometer:
We also need to create and define two other variables that we'll need at this point:
TILT_FORCE: If we tilt the accelerometer right or left, it will register a value greater than 0 (if we tilt left) or less than 0 (if we tilt right). In theory, any value greater than 0 is a left tilt and any value less than 0 is a right tilt. But, because the accelerometer is very sensitive, even if we try to hold it perfectly flat, it will likely register at least a tiny bit of tilt. So, to give us a margin of error, we're going to assume that the accelerometer needs to be tilted at least a certain amount before we register it as a tilt. If we want the game to be very sensitive to tilting, we can set this value close to 0 (so just a small tilt will register); if we don't want the game to be very sensitive, we can set the value close to 1 (so only a large tilt will register). And we'll initially set the value to .1 and see how that works for us.
SPACESHIP_STEP: As we register tilt in one direction or the other, we need to have the ship move in that direction. And we need to tell it how far to move each time we register a tilt. If we move it too far each time we register a tilt, the ship will appear to move very fast and we'll feel like we have no control over it; if we move it too small of a distance each time, the game will feel sluggish and non-responsive. Most likely, we'll just want the ship to move a fraction of a pixel each time a tilt is registered. We'll start with .1 pixels for now and see how that works for us.
In our initialization section for the ship, we can set these values:
Now that the accelerometer is initialized, we can use it to get input from the controller. We do this just like we did in the ACCELEROMETER project:
Next, we can add code to move the ship based on teh input we've received from the accelerometer:
Here is the full code for our game at this point: