Introduction:
We have a Shape Control named 'Shp1'...we are goin' to provide it some speed and then code it in a way such that when it collides with the borders of the form, it undergoes a perfect collision.
Concept:
1) Providing Speed : Using a timer control and 'Left' And 'Top' properties of shape control we can easily do this.
NOTE: Timer1's intervel is set to be '1'
CODE
Private Sub Timer1_Timer()
'===========Coding for moving the shape control===========
shp1.Left = shp1.Left + X 'Velocity vector along X-axis. 'X' variable is magnitude of velocity.
shp1.Top = shp1.Top + Y 'Velocity vector along Y-axis. 'Y' variable is magnitude of velocity.
'==========Coding for trigerring collisions================
If shp1.Top + 1000 > Form1.Height Then 'When shp1 reaches bottom of the form
Call fnReflect(1)
ElseIf shp1.Top <= 0 Then 'When shp1 reaches top edge of the form
shp1.Top = 30
Call fnReflect(2)
ElseIf shp1.Left + 600 > Form1.Width Then 'When shp1 reaches right edge of the form
Call fnReflect(3)
ElseIf shp1.Left <= 0 Then 'When shp1 reaches LEFT edge of the form
shp1.Left = 30
Call fnReflect(4)
End If
End Sub
Explanation :
As the timer is executed after 1 millisecond, both coordinates(X and Y) gets changed by some value, depending on 'X' and 'Y' variables.
As its clear from the comments in above code, we are calling a procedure fnreflect with passing a parameter through which it can recognize that which event has occured.
2)Procedure coding
CODE
Private Sub fnReflect(iDd As Integer)
If iDd = 1 Then
Y = Y - 2 * (Y) 'The velocity along Y direction gets Inverted(Instead of going down, shp1 will rise UP
Beep 'A little sound is Nice
ElseIf iDd = 2 Then
Y = Abs(Y) 'Instead of going UP, it'll descend DOWN
Beep
ElseIf iDd = 3 Then
X = X - 2 * (X) 'Instead of going RIGHT, it'll go LEFT
Beep
ElseIf iDd = 4 Then
X = Abs(X) 'Instead of going LEFT, it'll go RIGHT
Beep
End If
End Sub
Explanation : On a collision, only one component of velocity gets changed.
I guess this is a bit confusing.
I'll explain
Lets say the particle is goin' with velocity "RIGHT-DOWN"wards , therefore, it'll collide probable, lets say BOTTOM.
Then it should still move in RIGHT direction, but the motion should be, now, "RIGHT-UP"wards.
I thing after understanding the concept the above coding is clear, we are just reverting appropriate Velocity Components.
For Demonstration of this code, Download the *.zip file attached with this turorial.