USING COLLISION DETECTION IN VISUAL BASIC

USING COLLISION DETECTION IN VISUAL BASIC
In many programs, particularly games, it is often important to check whether there are collisions with
other objects at certain places. For example, if you are creating a game where the objective of the game
is to avoid zombies, you will need to be able to check when the player comes into contact with a zombie
so that it could do whatever you want the game to do.
Checking collisions between objects in Visual Basic is actually quite simple.
In this example, we are going to create a character (named Jack) that the user will control with the
keyboard and an enemy character (an angry bird) that will by flying up and down the screen. The
objective of the game is for Jack to avoid the bird. Once the bird makes contact with Jack, the game
ends.
When the program starts the Jack should start at the bottom-left corner and the bird should start at the
top-right corner.
Every time either Jack moves or the bird moves, we want to check if there is any contact between Jack
and the bird. To do this we will need to get the bounds of both objects and see if they intersect using a
VB method called IntersectsWith(). So our code would look something like this:
If picBird.Bounds.IntersectsWith(picJack.Bounds) Then
tmrBird.Stop()
MsgBox("You're dead!" & vbNewLine & "Better luck next
time.", MsgBoxStyle.Information, "Runaway Jack")
StartGame()
End If
The IntersectsWith() method simply gets the bounds of the bird (that is, the x- and y-position and the
width and height) and checks to see if it intersects with the bounds of Jack. If they do intersect, then the
timer will stop and a message box will appear.
Since we want the program to be checking for a collision both when peter walks and when the bird
moves, it would be best to create a subroutine that can get called when we want it to check for a
collision. So our subroutine would look like this:
Using Collision Detection in VB
Page 1 of 6
Private Sub CheckCollision()
If picBird.Bounds.IntersectsWith(picJack.Bounds) Then
tmrBird.Stop()
MsgBox("You're dead!" & vbNewLine & "Better luck next
time.", MsgBoxStyle.Information, "Runaway Jack")
StartGame()
End If
End Sub
Now what we will want to do is make a call to this subroutine both when Jack moves (so in the
KeyDown procedure) and when the bird moves (so in the Tick procedure for the Timer that is being
used to move the bird).
Private Sub RunawayJack_KeyDown(ByVal sender As Object, ByVal
e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Left Then
picJack.Image =
Image.FromFile(Directory.GetCurrentDirectory() &
"\images\jack_left.png")
jackX -= 10
ElseIf e.KeyCode = Keys.Right Then
picJack.Image =
Image.FromFile(Directory.GetCurrentDirectory() &
"\images\jack_right.png")
jackX += 10
End If
picJack.Location = New Point(jackX, jackY)
CheckCollision()
End Sub
Private Sub tmrBird_Tick(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles tmrBird.Tick
If moveLeft = True Then
birdX -= 5
Else
birdX += 5
End If
If moveDown = True Then
birdY += 5
Using Collision Detection in VB
Page 2 of 6
Else
birdY -= 5
End If
If birdY + picBird.Height >= Me.Height - 50 Then
moveDown = False
End If
If birdY <= 0 Then
moveDown = True
End If
If birdX <= 0 Then
moveLeft = False
End If
If birdX + picBird.Width > Me.Width - 20 Then
moveLeft = True
End If
If moveLeft = True Then
picBird.Image =
Image.FromFile(Directory.GetCurrentDirectory() &
"\images\bird_left.png")
Else
picBird.Image =
Image.FromFile(Directory.GetCurrentDirectory() &
"\images\bird_right.png")
End If
picBird.Location = New Point(birdX, birdY)
CheckCollision()
End Sub
SETTING BOUNDS FOR PRECISE COLLISION CHECKING
Sometimes you may want to set the bounds of two objects yourself and the reason for this is because
when Visual Basic gets the bounds of an object it gets the location and dimensions of the PictureBox or
the canvas of the image, not the image itself. For example, take a look at the two images we’re using in
our program:
Using Collision Detection in VB
Page 3 of 6
Given the above scenario, Visual Basic would consider this a collision because the PictureBoxes are
touching. However, it is clear that Jack and the bird are not actually touching.
So to allow for more precise collision detection you can set bounds yourself using a method in Visual
Basic called SetBounds(). The SetBounds() method requires you to pass four arguments: the xposition, y-position, width and height of the object you want to set.
So, let’s say for Jack we want to set bounds so that we get something like this:
We can set the bounds of Jack by creating an imaginary rectangle that would make up what is called the
collision mask. The same can be done for the bird:
The way we would check for collision now is by using the x- and y-positions and the width and the height
of the rectangular shapes of both objects. To establish the bounds of the rectangular shapes, we will
need to import Microsoft.VisualBasic.PowerPacks and then create RectangleShape objects. We
will then initialize our RectangleShape objects in our CheckCollision() subprocedure:
Private Sub CheckCollision()
Dim birdRectangle, jackRectangle As New RectangleShape
Using Collision Detection in VB
Page 4 of 6
birdRectangle.SetBounds(birdX, birdY + 30, picBird.Width - 30,
picBird.Height - 30)
jackRectangle.SetBounds(jackX + 20, jackY, picJack.Width - 40,
picJack.Height)
If birdRectangle.Bounds.IntersectsWith(jackRectangle.Bounds)
Then
tmrBird.Stop()
MsgBox("You're dead!" & vbNewLine & "Better luck next
time.", MsgBoxStyle.Information, "Runaway Jack")
StartGame()
End If
End Sub
Now when the program runs a collision will happen if the rectangular shapes collide, not when the
PictureBox objects collide:
No collision detected
Collision detected
Using Collision Detection in VB
Page 5 of 6
USING OVAL SHAPES FOR COLLISION DETECTION
You may find it more useful to using an oval shape to set the bounds of an object. If we were to use an
oval shape to set the bounds of Jack and the bird, it would look something like this:
Depending on the images you’re using, sometimes using an oval shape allows for more accurate collision
checking than rectangles. Creating an oval shape is like creating a rectangle, the only difference being
you need to create an OvalShape object and set the x-position, y-position, width and height of the
shape:
Private Sub CheckCollision()
Dim birdOval, jackOval As New OvalShape
birdOval.SetBounds(birdX, birdY + 30, picBird.Width - 30,
picBird.Height - 30)
jackOval.SetBounds(jackX + 20, jackY, picJack.Width - 40,
picJack.Height)
If birdOval.Bounds.IntersectsWith(jackOval.Bounds) Then
tmrBird.Stop()
MsgBox("You're dead!" & vbNewLine & "Better luck next
time.", MsgBoxStyle.Information, "Runaway Jack")
StartGame()
End If
End Sub
Using Collision Detection in VB
Page 6 of 6