Most computer games use either the keyboard or joystick to control the game. In this section, we are going to learn how to accept input from a joystick and output the results on the screen. Adding support for a joystick is very simple using Phrogram and is just as easy as input from a keyboard. Because some users may not have a joystick, it is good practice to support both the keyboard and the joystick.
To begin using the joystick, you must first declare a new variable defined as an array of Joysticks. Your computer may have more than one joystick attached to the computer at a single time, but for this example, we are going to assume the user is using the first joystick connected to the computer.
Define myJoysticks As Joystick[1]
If you wanted your game to accept input from multiple joysticks connected to the computer, enter the maxium number of joysticks to search for. For example, the following declares a new array of 5 joysticks.
Define myJoysticks As Integer = 5
Define myJoysticks As Joystick[MaximumJoysticks]
For now, we are going to keep things simple and check only one joystick. Now that we have defined a new joystick, we can display the properties of the joystick and add decision logic using If/Then/else to direct the computer program.
In this next example, we will write a computer program that displays the name of the joystick and list the values of the thumb stick if connected. This will continue until the user presses Q on the keyboard.
Method Main()
Define myJoysticks As Joystick[1]
If myJoysticks[1].IsConnected Then
Alert ("Joystick 1 is a " + _
myJoysticks[1].MakeAndModel , "Joystick Name")
While IsKeyDown("Q") = False
If myJoysticks[1].IsConnected Then
ConsoleWriteLine("Thumbstick X=" + _
myJoysticks[1].Stick1.X + _
" Y=" + myJoysticks[1].Stick1.Y)
End If
End While
Else
ConsoleWriteLine ("The joystick is not connected.")
End If
End Method
First, we check to see if the joystick is connected. This is done by checking the Joysticks’s IsConnected property. If the value of this property is True, then the joystick is connected. If the joystick is not connected, this will return false.
In this example, we want to display an alert with the name of the joystick of the joystick is connected. First we use the IF/THEN statement to test if the joystick is connected.
If myJoysticks[1].IsConnected Then
If myJoysticks[1].IsConnected Returns TRUE, then the computer executes the next line of code. In this case, the next line is the alert method. If myJoysticks[1].IsConnected = False, then the line after ELSE executed. In this example, that would be ConsoleWriteLine ("The joystick is not connected.")
No comments:
Post a Comment