Here are some other ping pong routines that you may find useful.
The first is a ping pong using a procedure, everytime it is called the value is increased or decreased if it has reached its max :
#maxCount = 500
Procedure PingPong()
Static _count = #maxCount - 1
_count = (_count + 1) % (#maxCount << 1)
ProcedureReturn Abs(_count - #maxCount)
EndProcedure
Repeat
Debug PingPong()
Delay (5)
ForEver
Then we have one which looks much more complex but has the benefit of being autonomous, and you can have multiple pong pongs being managed with the same procedure :
; With this one you can set a min, a max, and you can keep track of more then one ping-pong at the time.
Structure T_PINGPONG
min.i
max.i
counter.i
direction.i
EndStructure
Procedure.i PingPong (*p.T_PINGPONG)
If *p\direction = 0
*p\direction = 1
*p\counter = *p\min
Else
*p\counter + *p\direction
If *p\counter = *p\min Or *p\counter = *p\max
*p\direction = -*p\direction
EndIf
EndIf
ProcedureReturn *p\counter
EndProcedure
;****************************
; DEMO
;****************************
Define pp1.T_PINGPONG
Define pp2.T_PINGPONG
pp1\min = 1
pp1\max = 10
pp2\min = -5
pp2\max = 5
Repeat
Debug "pp1 = " + PingPong(@pp1) + ", pp2 = " + PingPong(@pp2)
Delay (500)
ForEver
And put into your demo, as you can see the logic loop is much simpler now :
InitSprite()
UseJPEGImageDecoder()
UsePNGImageDecoder()
InitKeyboard()
Global timer= 1
Structure T_PINGPONG
min.i
max.i
counter.i
direction.i
EndStructure
Procedure.i PingPong (*p.T_PINGPONG)
If *p\direction = 0
*p\direction = 1
*p\counter = *p\min
Else
*p\counter + *p\direction
If *p\counter = *p\min Or *p\counter = *p\max
*p\direction = -*p\direction
EndIf
EndIf
ProcedureReturn *p\counter
EndProcedure
Define pp1.T_PINGPONG
Define pp2.T_PINGPONG
pp1\min = 0
pp1\max = 50
pp2\min = 0
pp2\max = 50
OpenScreen(800,600,32,"PBWINDOW")
wave = LoadSprite (#PB_Any, "wave.png")
Repeat
ExamineKeyboard()
TransparentSpriteColor(wave,#White)
ClearScreen($0)
DisplayTransparentSprite(wave, 50-PingPong(@pp1)-100,300)
DisplayTransparentSprite(wave,PingPong(@pp2)-50,400)
FlipBuffers()
Until KeyboardPushed (#PB_Key_Escape)
End