User Interaction
In the previous lesson, we learned how to draw various things on the screen. This lesson will introduce keyboard and mouse controls. Let's start with our MAN image.
To put the image in motion, we'll increment its position on the x axis.
You should see our image moving to the right. How can we control this with the keyboard? The code below uses an if condition to check if the right arrow is being pressed.
Let's add a new control for moving to the left. For this, we decrement the position on the x axis.
Now our image can move left and right! We can also add up and down controls by changing the y position.
Check the Key class for more information on keyboard controls. Now let's change the image tint when the mouse is pressed.
In the code above, we use the cursor variable to access the state of the mouse. Cursor press and release are activated whenever the user presses or releases a button.
User input is one of the most import functions of a game. Try controlling the image with different keys.
Back Next