Multiple keys pressed at the same time

Started by paulvern, June 25, 2020, 13:54:29

Previous topic - Next topic

paulvern

I'm back to Blitz after almost 30 years! (yes, I used it back in Amiga times... a age ago).
Many things are not the same but many others didn't change a lot during this time.
I don't understand what's wrong with this little piece of code:
Strict
Graphics 800,600
SetClsColor 255,255,255
AutoMidHandle(True)
Global My_Image:TImage=LoadAnimImage("h:/Cockroach.png",32,32,0,4)
Local Rota:Int=90
Local frame:Int=0
Local x#
Local y#
While Not KeyDown(Key_Escape)
Cls
If KeyDown(Key_Right)
Rota:+1
frame:+1
EndIf
If KeyDown(Key_Left)
Rota:-1
frame:+1
EndIf
If KeyDown(Key_up)
frame:+1
x=x+2*Cos(Rota-90)
y=y+2*Sin(Rota-90)
EndIf
SetRotation( Rota)
DrawImage( My_image,200+x,200+y,frame )
If frame=3 Then frame=0
Flip
Wend


I'm loading the image of a cockroach and trying to get key inputs. Everything works fine as long as I don't press two keys at the same time. If I try to press two keys I receive the following error message: attempt to index array element beyond array length.
Can't multiple key presses be handled this way?
I hope I'm missing something.

Juiceter

#1
maybe try a flushkeys after the initial key has been chosen? No two key strokes are ever done at (exactly) the same time! And yes, I used to code in blitz basic on the amiga too. Heady days eh?!  ;)

TomToad

You are updating frame with each keypress.  So if you press left and up at the same time, frame gets updated twice causing it to exceed 3 and causing the index error when you try DrawImage().  You should instead set a flag, update frame only when the flag is set, and make sure it is within 0-3 before the draw.
Code (blitzmax) Select
Strict
Graphics 800,600
SetClsColor 255,255,255
AutoMidHandle(True)
Global My_Image:TImage=LoadAnimImage("h:/Cockroach.png",32,32,0,4)
Local Rota:Int=90
Local frame:Int=0
Local x#
Local y#
Local Animate:Int = False
While Not KeyDown(Key_Escape)
Cls
If KeyDown(Key_Right)
Rota:+1
Animate = True
EndIf
If KeyDown(Key_Left)
Rota:-1
Animate = True
EndIf
If KeyDown(Key_up)
Animate = True
x=x+2*Cos(Rota-90)
y=y+2*Sin(Rota-90)
EndIf
SetRotation( Rota)
If Animate
Animate = False
frame :+ 1
If frame >= 4 Then frame = 0
EndIf
DrawImage( My_image,200+x,200+y,frame )
Flip
Wend
------------------------------------------------
8 rabbits equals 1 rabbyte.

Derron

The issue was resolved one day after posting here. He posted in the "bmx ng"-discord channel and I (and others) gave already quick hints on what is faulty in his code.

Maybe he will post here once he runs into the next problem (he did not post since short after that issue so maybe he is just busy doing other stuff).


bye
Ron

paulvern

Sorry for the long delay in my reply here. I've been away for vacations. Thank you all for the tips. And yes, the problem is fixed now.