This is how I do it:
I have a "force"-Variable the pushes the sprite down.
This variable is fed by a gravity constant. I simply add this constant to the force every cycle. Otherwise it would just be a linear speed, but gravity is ofcourse an accelerator.
Then I have a jumping force. This is simply a constant (much higher that the gravity constant, but negative, because we want to go up).
When I want to jump, I give the force-variable the value of the jumping force constant.
Add a restriction so that you can't jump in mid-air or fly away by pushing space all the time and you're done.
If you want the sprite to reach a certain jumping height, you have to play around with the constants a bit.
Code: Select all
EnableExplicit
InitSprite()
InitKeyboard()
Define hWnd = OpenWindow(#PB_Any, 0, 0, 800, 600, "Fenster", #PB_Window_ScreenCentered|#PB_Window_MinimizeGadget)
OpenWindowedScreen(WindowID(hWnd), 0, 0, 800, 600, 0, 0, 0)
Define y.f=-100 ;Starting position of the sprite
Define x.f=300
Define downforce.f;actual "force" that pulls the sprite downwards
Define touchingGround.i ;1 or 0 to disallow jumping in mid-air and continuous acceleration (=flying)
Define isJupming.i ;1 or 0
#Gravity = 1.0 ;gravity constant (known as 'g' in physics)
#JumpForce = -20 ;Jupming force of the sprite (much higher than gravity, but negative)
CreateSprite(0, 40, 80) ;Create a little sprite
StartDrawing(SpriteOutput(0))
Box(0, 20, 40, 60, $FF0000)
Circle(20,10,9,$DDCCFF)
StopDrawing()
Repeat
If WaitWindowEvent(20) = #PB_Event_CloseWindow
End
Else
ExamineKeyboard()
If KeyboardPushed(#PB_Key_Space) And touchingGround = 1
isJupming = 1
touchingground=0
EndIf
ClearScreen(0)
If isJupming=1
downforce = #JumpForce
isJupming=0
EndIf
If touchingGround = 1
downforce = 0
Else
downforce + #Gravity
EndIf
If y<=520
y+downforce
EndIf
If y>=520
y=520
TouchingGround=1
EndIf
DisplaySprite(0, x, y)
FlipBuffers()
Delay(5)
EndIf
ForEver