Thursday, 20 August 2015

HOW TO CHECK FOR COLLISION BETWEEN TWO OBJECTS IN VB 6

Collision is always an event occur when two or more moving objects meets with each other.
To check for collision between two objects we must check for certain conditions to fullfil
The condition is as follows -

If Shape1.Left < Shape2.Left + Shape2.Width And Shape2.Left < Shape1.Left + Shape1.Width Then

If Shape1.Top < Shape2.Top + Shape2.Height And Shape2.Top < Shape1.Top + Shape1.Height Then
  
                 'Collision

End If
End If

Here, shape1 is one object and shape2 is another other object

There are some points that must be note for understanding the above condition

- The object as it is created in the form ocuppies some space in terms of width so when we
   move the object its left property increases but for form the total space occupied is
   object.left + object.width.

- In the first if clause both the objects are checked simultaneously i.e. whenever the shape1.Left
   value is less than the sum of occupied space of left and width, the objects had not crossed each
   so until that the collision is possible. Next the same applies to the other object so the condition is
   checked for other shape also

-Similiarly, as it occupies Left and Width it also occupies Top and Width. Therefore, the
 Top and Width must also be checked

Hence the above conditions are checked then the object's collision could be detected

Lets take an example by creating two rectangle boxes , and check for collision
And if they collide they must move away from them



Here we must take two variables that changes their signs the object moves

Following is the final code for the above design..

Dim p, q As Integer

Private Sub Form_Load()
Timer1.Enabled = True
p = 150
q = -150
Timer1.Interval = 50
End Sub

Private Sub Timer1_Timer()
Shape1.Left = Shape1.Left + p
Shape2.Left = Shape2.Left + q
If Shape2.Left <= -480 Then                        ' It is the left most position
q = 150
End If
If Shape1.Left >= Form1.Width Then
p = -150
End If

If Shape1.Left < Shape2.Left + Shape2.Width And Shape2.Left < Shape1.Left + Shape1.Width Then

If Shape1.Top < Shape2.Top + Shape2.Height And Shape2.Top < Shape1.Top + Shape1.Height Then
    p = 150                                  'Collision
    q = -150
End If
End If
End Sub

Here, as soon as the direction is reversed the value of p and q are swapped (or assigned swapped values)

OK, We are done here

No comments:

Post a Comment