Bouncing
Algorithm
By:
Peter Kuchnio
The
bouncing ball algorithm will do precisely that, bounce a ball within preset
boundaries. The algorithm is absurdly simple. The direction variables are
set to one. This is added to the coordinates of the ball until a wall is
hit. Once this happens one of the coordinates becomes a -1. If it hits
the wall again it becomes 1.
Here
is the code:
Private
Sub Command1_Click()
'Setting
the coordinates
Xcoor
= 16
Ycoor
= 16
'Ball
direction. It works like this:
'if
it is 1 then the ball moves up and right
'if
it hits the barrier it changes into -1 and
'reverses
direction either horizontally, vertically
'
or both
dX
= 1
dY
= 1
Do
DoEvents
'If the *wall* is hit reverse the number
If Ycoor > 325 Or Ycoor < 1 Then dY = -dY
If Xcoor > 525 Or Xcoor < 1 Then dX = -dX
'These variables are used to erase the previous ball.
oldxcoor = Xcoor
oldycoor = Ycoor
'Increment position
Ycoor = Ycoor + dY
Xcoor = Xcoor + dX
'Draw ball
Picture1.Circle (Xcoor, Ycoor), 4, , , , 0.5
Picture1.Circle (oldxcoor, oldycoor), 4, RGB(255, 255, 255), , , 0.5
Loop
End
Sub
|