VB: Keyboard problem

Started by
1 comment, last by Toolmaker 18 years, 11 months ago
Im programming a game in VisualBasic. The problem: To move around you use the keyboard. However lets say if youre moving right and then jump up the chara stops moving right even though you are still holding the right key down. http://www.reilsson.com/malo/game.zip This includes what I got so far in the game and if you try it out you can see the problem. Also I got the code that i use for the keys. I dont think any other code is necessary. Use arrow keys for Luigi and W-D-A for toad. Anyone know how this can be fixed? >< Thanks in advance.
Advertisement
Well, this is the first VB code I've ever seen. It looks like a switch statement. That won't work. That's like saying this:

if left then move-left
else if right then move-right
else if up then jump

When you need this:

if left then move-left
if right then move-right
if up then jump

However, to get a more desirable effect, you should make the character keep moving at the same speed he was moving when he jumped. So if the right key was down when he pressed jump, he keeps moving right while he's in the air, regardless of the right key's state.

I hope that helps. I can't help with code specifics.
Your problem can be explained simply:

You're pressing the right button, and when you do so, it will trigger a OnKeydown (or something like that). However, when you press space, it will trigger ANOTHER OnKeydown. The previous key(The movement) is still down, so it won't trigger a keydown event.

Your solution is not to rely on the events for this, but to use the GetAsynchKeyState function. This function will ask Windows about the state of a specific key. So, if the key is down, Windows will tell you so.

Declare this in the file where you check for the key down:
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer


Now, in order to check if a key is pressed, use this code:
Private Function KeyDown(key As Integer) As Boolean    KeyDown = (GetAsyncKeyState(vbKeyW) And &H8000)End Functionif KeyDown(vbKeyW) then    ' OMG, the W key is pressed at the moment, do something!end ifif KeyDown(vbKeyA) then    ' You get the idea I guessend if


To get a complete list of avaliable keys you can get:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vb98/html/vbidxKeyCodeConstants.asp

Sorry if I made code errors, I'm rusty on Visual Basic since I programmed in VB at least 2 years ago.

Toolmaker

This topic is closed to new replies.

Advertisement