problem with stacking "KeyHits"
Blitz3D Forums/Blitz3D Beginners Area/problem with stacking "KeyHits"
| ||
I've just encounter an odd problem, never happened to me before. It seems that "KeyHits" for the same key, no longer stack. Say ou have two "If" loops, both need a KeyHit(28) [enter], but both have differing conditions needed... If selectpos = 3 And KeyHit(28) ; For options Goto options EndIf If selectpos = 1 And KeyHit(28) ; For game start Goto gamestart EndIf Only the first one will work when Enter is hit with the right conditions (goto otpions). The second loop ignores your keyhit(28), even if selectpos = 1. I tried inversing the order of the loops: If selectpos = 1 And KeyHit(28) ; For game start Goto gamestart EndIf If selectpos = 3 And KeyHit(28) ; For options Goto options EndIf Now only the "Goto gamestart" loop works, when KeyHit(28) happens. The second loops is yet again, ignored. As if the KeyHit(28) worked only for the first loop, and was ignored for any following loops. Is this a bug? or am I missing something? Thanks for any insight :) |
| ||
That's normal. What you have to do is set the returned value from KeyHit(28) to a variable and then test the variable. Like so: KH28 = KeyHit(28) If selectpos = 1 And KH28 ; For game start Goto gamestart EndIf If selectpos = 3 And KH28 ; For options Goto options EndIfor a little more optimized: KH28 = KeyHit(28) If KH28 If selectpos = 1 ; For game start Goto gamestart EndIf If selectpos = 3 ; For options Goto options EndIf EndIf(A little note: The KeyHit command actually returns the NUMBER of keyhits since the last time it was checked. So, in my example above, KH28 could actually contain a value higher than 1 depending on how often you check it's returned value.) |
| ||
Ah I see, thanks :). I'm surprised I never came across this same problem before though. Never replaced keyhits with variables before.. guess it's a habit I need to get used to. |
| ||
The problem is that KeyHit returns the number of times the key was hit since last time you called the command. If you call KeyHit multiple times a frame, it'll return the keypress the first time but none of the other times (ie. the key was hit 0 times since the last time you called KeyHit.) Thus it is vital to only call KeyHit once a frame. Either do what WolRon suggested of storing the keyhits in variables, or nest your if statements. His second code snippet uses nested if statements; storing KeyHit in a variable is unnecessary in that case. It would look like: If KeyHit(28) If something If something else EndIf Thus KeyHit is only called once. |