Astronomy Hour of Code
Activity 19: Adding Keyboard Controls and AudioInstructions:
(Advanced Lesson)
In this lesson we are going to add keyboard controls to the skybox so you can move the camera around. In order to give the sense of movement to unsighted users we are going to play the click sound every time the camera moves 10 degrees. In order to use movement we are going to use and object in the game engine called an InputMonitor which monitors things like keyboard presses and mouseclicks that the user makes and allows our program to react when something is pressed. We will also use an object called a KeyboardEvent which identifies the particular key that is pressed.
In the starting code, we have already included the use statement that you will need and we declared the InputMonitor and the KeyboardEvent objects called monitor and keys. Our first line of code, will just check if the monitor detects if the right key is pressed with this statement:
if monitor:IsKeyPressed(keys:RIGHT)
Inside this conditional block we are goint to set the new camera position to display by first calculating the rotation, which is called yaw in the game engine like this:
yaw = yaw + 30 * seconds
camera:SetYawPitchRoll(yaw, pitch, roll)
In order to play a click every 10 degrees, we have to check if the yaw has changed by more than 10 since the last time we played a click and if it has, we play the click and then save the current value of the yaw in the lastYaw variable and output the value to the console.
if yaw > (lastYaw + 10) or yaw < (lastYaw - 10)
clickSound:Play()
lastYaw = math:Round(yaw,-1)
output lastYaw
end
Now all we have to do is close the first conditional statement with an end:
end
Now you are ready to Run your program and rotate the camera with the right arrow key to view your skybox. You can also press the space key to have the current rotation displayed in the console. In order to have the game engine respond to your keyboard input you need to make sure that the visual output window has focus by either clicking on it or tabbing in to it.
Exploration Challenge (Optional):
Add keyboard controls for the other arrow keys so that you can move the camera in other directions. You will have to change the formula slightly to go left instead of right. To move up and down you will need to set the pitch and not the yaw variable. If you want to make the camera move faster or slower, change the constant value in the yaw formula which is set at 30 to start. If you add a control for the pitch, see what happens if you press up until you feel like you flip over backwards.
Next Tutorial
In the next tutorial, we will discuss Astronomy Hour of Code | Activity 0, which describes Accessible astronomy themed Hour of Code.