Using Graphics: Making a Lander Game - Part 2
The horizontal movement of our spaceship will be implemented in a similar way to the vertical movement. Each time the timer event is raised, we will use the API to check whether the left of right arrows have been pressed, and if they have, apply the neccessary acceleration to the horizontal speed.
To trap the left and right key presses, we will need these constants:
Private Const VK_LEFT = &H25 Private Const VK_RIGHT = &H27
We will also need these variables to store the speed and position of the craft. Paste these also into the declarations section:
' The x coordinate of the craft Private LandX As Double ' Horizontal speed of the craft Private hSpeed As Double
Since our pilot is going to want to know how fast he is moving, draw a text box called txthspeed and an accompanying label. The default values for the horizontal speed should be set in the form's load event:
hSpeed = 0 LandX = 150 ' Update text boxes txthspeed.Text = Format(hSpeed, "0.0")
That's the easiest bits out of the way now, but the rest is not that hard really. The first modifications to be made to the timer will be to change the default X coordinate of 150 to the variable value, LandX. Therefore, go through each BitBlt API call (there are four in total), changing the second parameter from 150 to LandX. For example, the first call should read:
BitBlt picEarth.hdc, LandX, LandY, _ piclander.ScaleWidth, piclander.ScaleHeight, _ piclander.hdc, 0, 0, vbSrcInvert
Now that we have the basic framework for controling the horizontal movement, it is almost a matter of copy and pasting the code for monitoring the down arrow key to extend it to watch the left and right arrow keys:
' Apply left and right movement If GetAsyncKeyState(VK_RIGHT) <> 0 Then If Fuel > 0 Then dothrust = True ' Apply thrust: 15 is the acceleration produced hSpeed = hSpeed - ((timediff / 1000) * 15) Fuel = Fuel - ((timediff / 1000) * 150) ' Check that fuel does not go below 0 If Fuel < 0 Then Fuel = 0 Else Beep End If End If If GetAsyncKeyState(VK_LEFT) <> 0 Then If Fuel > 0 Then dothrust = True ' Apply thrust: 15 is the acceleration produced hSpeed = hSpeed + ((timediff / 1000) * 15) Fuel = Fuel - ((timediff / 1000) * 150) ' Check that fuel does not go below 0 If Fuel < 0 Then Fuel = 0 Else Beep End If End IfLandX = LandX + hSpeed
And there you have it! Just think, you have double the number of dimensions in your game with just a few easy steps! Before we move on, we mustn't forget to tell the user how fast they are going. Add this with the other statements that update the text box:
txthspeed.Text = Format(hSpeed, "0.0")
And now for some sound!
Page 2 of 5
This article was originally published on November 20, 2002