PDA

View Full Version : Example: Section 8.2 (page 261), A little Gravity!



Michael Clease
27-02-2010, 03:26
' Example: Section 8.2 (page 261), A little Gravity!

' From Stan Blank's Book:
' "Python Programming in OpenGL
' "A Graphical Approach to Programming

' Converted by Michael Clease (Stolen timing ideas from Petr..hehe)
' Last modified: February 27, 2010

Uses "TBGL"

' Handle for our window
Global hWnd As DWord
Global Width As Long
Global Height As Long
Global x,y As Double
Global dx,dy As Double
Global anim As Long
Global axrng As Double
Global hvel As Double
Global vvel As Double
Global radius As Double
Global xborder As Double
Global yborder As Double
Global dtime As Double
Dim Title As String Value "A little Gravity! - Press 'A' to start, 'S' to stop or 'Esc' to quit"
width = 600
height = 600
'
' Create and show window
hWnd = TBGL_CreateWindowEx(Title, Width, Height, 32, %TBGL_WS_WINDOWED )
TBGL_ShowWindow

Init()'Anim,x,y,dx,dy,axrng)
' Define "Callback" to be fired + that it should be fired each 10ms
TBGL_BindPeriodicFunction(hWnd, "PlotFunc", 10)

' -- Once the command below is executed, further script execution
' -- is halted and only periodic calling of the bound function is performed
TBGL_ProcessPeriodicFunction(hWnd)

TBGL_DestroyWindow

Sub Init() 'ByRef anim,ByRef x,ByRef y,ByRef dx,ByRef dy,axrng)
'# initial position of the ball
x = -0.67
y = 0.34
dtime = 0.005
radius = 0.1
hvel = 0.75
vvel = 3.0
'# Direction "sign" of the ball's motion
dx = 1
dy = 1
'# Window dimensions
xborder = 1.0
yborder = 1.0
axrng = 1.0
'# No animation To start
anim = 0
TBGL_Color(255,0,0)
TBGL_BackColor(0,0,0)
' Resets status of all keys
TBGL_ResetKeyState()
End Sub

Sub PlotFunc()
' -- Which window is calling?
Local hWnd As DWord = TBGL_CallingWindow

If Anim Then
TBGL_ClearFrame
TBGL_RenderMatrix2D(-axrng, -axrng, axrng, axrng)

vvel = vvel - 9.8*dtime
y += vvel*dtime
If y <= (-axrng + radius) Then y = -axrng + radius
x += hvel*dtime

TBGL_PushMatrix
TBGL_Translate(x,y,0)
TBGL_Sphere(Radius)
TBGL_PopMatrix
If x >= (xborder - radius) Or x <= (-xborder + radius) Then hvel = -1*hvel
If y >= (yborder - radius) Or y <= (-yborder + radius) Then vvel = -1*vvel

TBGL_DrawFrame
EndIf
If TBGL_GetWindowKeyState(hWnd, %VK_A) Then Anim = 1
If TBGL_GetWindowKeyState(hWnd, %VK_S) Then Anim = 0

' ESCAPE key to disable callback
If TBGL_GetWindowKeyState(hWnd, %VK_ESCAPE) Then
TBGL_UnBindPeriodicFunction( hWnd )
Exit Sub
End If

End Sub

kryton9
27-02-2010, 03:59
Another really useful function and can be used in so many game types. This is really great having you guys join in on the conversions and doing such a great job!