Small BasicOnline > Lesson 4.3: Collision Detection

Estimated time to complete this lesson: 1 hour

### Collision Detection

In this lesson, you will learn how to:

• Use the concept of collision detection in games.

### What is Collision Detection?

In general, collision detection refers to determining the intersection of two moving objects.

Now let’s talk about collision detection in games.

Collision detection in games requires the following steps:

• Select two objects to test for collision.
• Determine whether those two objects collided.

### How to Detect Collision?

Before we discuss how to detect collisions, you should consider what happens to two objects when they collide.

Two objects are said to collide if they come in contact with each other. The objects may continue moving after collision or one may come to rest, depending on the nature of collision.

Collision detection is a basic aspect of two-dimensional and three-dimesional games. Algorithms help to detect the collision. Most games use posteriori collision detection—that is, they detect the collision after it has occurred.

### Hit the Target – The Game

Now that you understand the concept of collision detection in games, let’s make a game that uses the logic of collision detection. The game involves two objects: the turtle and the target. The player must make the turtle hit the target by specifying the correct angle and the correct distance.

You use the logic of collision detection to detect the collision between the turtle and the target. The game ends as soon as the two objects collide.

### Hit the Target – How to Play

It’s time to play the game!

Steps to play the game:

• Set the angle to specify the direction in which the turtle will move.
• Specify the distance that the turtle must cover to hit the target.
• Click the ‘Hit’ button to hit the target.
• Click the ‘Reset’ button to reset the position of the target.

### Hit the Target – The Code

Now let’s understand the code for the game in detail…

``````'  Copyright (c) Microsoft Corporation.  All rights reserved.
GraphicsWindow.Hide()
gw = 620
gh = 450

GraphicsWindow.BackgroundColor = "LightBlue"
GraphicsWindow.CanResize = "False"
GraphicsWindow.Width = gw
GraphicsWindow.Height = gh
GraphicsWindow.Top = ( Desktop.Height - gh ) / 2
GraphicsWindow.Left = ( Desktop.Width - gw ) / 2
GraphicsWindow.Title = "Hit the Target"
GraphicsWindow.Show()

Turtle.Hide()
rx = 40
ry = 20
turtlex = 315
turtley = 300
width = 550
height = 390
ScoreboxX = 400
Enterkey = "Return"

target = 10
life = 3
score = 0

GraphicsWindow.FontSize = 30
GraphicsWindow.DrawText(100, 200, "Press ENTER to start the game!")
GraphicsWindow.KeyDown = Onpress

Sub Onpress
enter = enter + 1
If GraphicsWindow.LastKey = Enterkey And enter = 1 Then
GraphicsWindow.Clear()
GraphicsWindow.FontSize = 12
GUI()
MovingShape()
ScoreShow()
Controls.ButtonClicked = hitClick
EndIf
EndSub

Sub hitClick
angle = Math.Round(Controls.GetTextBoxText(angletxt))
distance = Math.Round(Controls.GetTextBoxText(distancetxt))
clicked = Controls.GetButtonCaption(Controls.LastClickedButton)
If clicked = "Hit" Then
GraphicsWindow.PenWidth = 0
Turtle.Angle = angle
Turtle.Move(distance)
If Turtle.x > x and Turtle.x < x + 93 and Turtle.y > y and Turtle.y < y + 96 Then
Shapes.HideShape(target)
score = score + 10
scoreshow()
Program.Delay(500)
If target = score Then
GameEnd()
EndIf
Controls.SetTextBoxText(angletxt, "")
Controls.SetTextBoxText(distancetxt, "")
MovingShape()
Else
Program.Delay(1000)
If life > 1 Then
GraphicsWindow.ShowMessage("Click Ok to continue the game","Reset")
clicked = "Reset"
Else
GameEnd()
EndIf
EndIf
EndIf

If clicked = "Reset" Then
life = life - 1
If score >= 10 Then
score = score - 5
EndIf
scoreshow()
Controls.SetTextBoxText(angletxt, "")
Controls.SetTextBoxText(distancetxt, "")
MovingShape()
If life < 1 Then
GameEnd()
EndIf
EndIf
EndSub

Sub GUI
image = Program.Directory + "\cartoon.gif"
GraphicsWindow.DrawRectangle(rx, ry, width, height)
GraphicsWindow.BrushColor = "Black"
Shapes.Move(target, 100, 50)
Turtle.Show()
Turtle.X = turtlex
Turtle.y = turtley
Turtle.Angle = 0
GraphicsWindow.DrawText(rx + 5, height - 10, "Enter Angle:")
angletxt = Controls.AddTextBox(turtlex - 190, Turtley + 70)
Controls.SetSize(angletxt, 40, 30)
GraphicsWindow.DrawText(rx + 130, height - 10, "Enter Distance:")
distancetxt = Controls.AddTextBox(turtlex - 50, Turtley + 70)
Controls.SetSize(distancetxt, 40, 30)
firebutton = Controls.AddButton("Hit", turtlex + 20, Turtley + 70)
Controls.SetSize(firebutton, 80, 30)
Endsub

Sub MovingShape
Shapes.ShowShape(target)
Turtle.x = turtlex
Turtle.Y = turtley
Turtle.Angle = 0
x = Math.GetRandomNumber(450)
y = Math.GetRandomNumber(80)
If x <= 40 Then
x = 40
Shapes.Animate(target, x, y, 1000)
ElseIf y <= 20 Then
y = 20
Shapes.Animate(target, x, y, 1000)
Else
Shapes.Animate(target, x, y, 1000)
EndIf
EndSub

Sub GameEnd
GraphicsWindow.ShowMessage("Your score is:" + score, "Game Over")
Program.End()
EndSub

Sub ScoreShow
GraphicsWindow.FontSize = 14
GraphicsWindow.BrushColor = "Gray"
GraphicsWindow.FillRectangle(ScoreboxX + 50, ScoreboxX - 65, 135, 70)
GraphicsWindow.BrushColor = "White"
GraphicsWindow.DrawText(ScoreboxX + 60, ScoreboxX - 55, "Score :")
GraphicsWindow.DrawText(ScoreboxX + 110, ScoreboxX - 55, score)
GraphicsWindow.DrawText(ScoreboxX + 60, ScoreboxX - 20, "Life :")
GraphicsWindow.DrawText(ScoreboxX + 110, ScoreboxX - 20, life)
EndSub``````

This is the output you will see: • Create the user interface by using the GraphicsWindow object.
• Next, use the Controls object to add a button and a text box and to set the size of the button.
• Use the Shapes object to add an image of the shape, to move and animate the shape, and to set its opacity level.
• Use the Turtle object, and set its angle and moving distance by using the Math object.

### Let’s Summarize…

Congratulations!

Now you know how to:

• Use the concept of collision detection in games.

### It’s Time to Apply Your Learning…

Using the concept of collision detection, create a game that involves two types of objects: a bucket and apples. The apples fall randomly from the top of the graphics window. The player tries to catch the apples in the bucket. The game runs for 30 seconds. Include a score board to display the total number of apples that the player caught in 30 seconds.

Your game should resemble the example in this slide.

To see the answers to these questions, go to the Answer Key page.

Next Lesson