Handling events with if
Now we have the circle moving, but do we always want the circle to move? No, let’s change it so that we only update the position if the user is holding down an arrow key.
Add an if statement that will check if the right arrow key is held down. You can put the code that adds to the playerX
value within the if statement so that it is only run if the arrow key is held down.
Compile and run the program. Notice how the player’s x location is not changing. Hold down the right arrow key, and the circle will move right. Release the key and it will stop.
Now we have it moving right, let’s get it so we can move left as well.
Add another if statement to check if the left key is held down. Inside this if statement, add the code to subtract the speed from the playerX
variable.
Compile and run the program. Test out the following and make sure that you can explain how it works:
- Try holding down the left key
- Try holding down the right key
- Try holding down left and right keys together
Notice the logic is not quite right. Try removing the else
and instead have two independent if statements.
Test it out again:
- Hold down the left key
- Hold down the right key
- Hold down left and right keys together
Have a go at getting the player to move vertically as well.
Using these same mechanics you can create a whole wealth of different functionalities. In each case you can use an if statement to check if an event has occurred, and then you update values within the program in reponse.