Vb6 Tutorial - Rectangle Collision Detection
Vb6 Tutorial - Rectangle Collision Detection
This tutorial will teach you how to use collision detection in Visual Basic 6.
To find out if two rectangles have collided, first we need to check 4 things:
1. If the right side of rectangle 1 is greater than the left side of rectangle 2
2. If the left side of rectangle 1 is less than the right side of rectangle 2
3. If the bottom side of rectangle 1 is greater than the top side of rectangle 2
4. If the top side of rectangle 1 is less than the bottom side of rectangle 2
In this example I will use two shapes as my rectangles. To find the right side of a rectangle, we need
to add the width of the rectangle to the left value of the rectangle. For example:
Now we need to do the math. First, find if the right of shape 1 is greater than the left side of shape 2:
Now, use the same method for top and bottom sides:
If (Shape1.Left + Shape1.Width) > Shape2.Left AND Shape1.Left < (Shape2.Left + Shape2.Width) AND
(Shape1.Top + Shape1.Height) > Shape2.Top AND Shape1.Top < (Shape2.Top + Shape2.Height)
then...
COLLISION!
Another way to do this is to call the API IntersectRect. We do this by first creating a type called RECT.
This is done by starting your code with:
Option Explicit
Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
This creates the type called RECT. RECT has properties Left, Right, Top and Bottom. You can create a
new RECT by typing:
For example:
To change the properties of rect1, for example, the top property, we type:
rect1.top = 5
This declares the Function IntersectRect so we can use it later. Before we call the function
IntersectRect, we first need to create a variable of variable type Boolean. A Boolean can be used
ONLY to store the value TRUE of FALSE. To do this, type:
Dim as Boolean
Then, we type:
An example is:
Rect1.left = 5
Rect1.right = 10
Rect1.top = 5
Rect1.bottom = 10
Rect2.left = 7
Rect2.right = 12
Rect2.top = 7
Rect2.bottom = 12
Intersect will work out the intersection between Rect1 and Rect2 and returns it in Rect3. Rect3 will
become the rectangle where it was intersected. So Rect3 will have:
Left – 7
Top – 7
Right – 10
Bottom – 10
To sum it all up, I will show you how to use this to find an intersection between two shapes:
Rect1.Left = Shape1.Left
Rect1.Top = Shape1.Top
Rect1.Right = Shape1.Left + Shape1.Width
Rect1.Bottom = Shape1.Top + Shape1.Height
Rect2.Left = Shape2.Left
Rect2.Top = Shape2.Top
Rect2.Right = Shape2.Left + Shape2.Width
Rect2.Bottom = Shape2.Top + Shape2.Height
If there is an intersection, Collision will be TRUE, else it will be FALSE. In this case, because there
was an intersection, Collision will be TRUE.
Both theses ways can be used to find Rectangle Collision Detection. Use whichever you find
easiest.