Lesson 19: Collision Detection

Overview

Question of the Day: How can programming help make complicated problems more simple?

Students learn about collision detection on the computer. Working in pairs, they explore how a computer could use sprite location and size properties and math to detect whether two sprites are touching. They then use the isTouching() block to create different effects when sprites collide, and practice using the block to model various interactions.

Purpose

This lesson formally introduces the use of abstractions, simple ways of representing underlying complexity.

In the last lesson, students were exposed to the idea of using one block to represent complex code. Students further explore this idea in the context of the intentionally complex mathematical challenge of determining whether two sprites are touching. By using a single block to represent this complexity, in this case the isTouching block, it becomes much easier to write and reason about code, and students can appreciate the value of using abstractions. In later lessons, students will continue to build on the isTouching() abstraction to create more complex sprite interactions.

Assessment Opportunities

  1. Detect when sprites are touching or overlapping, and change the program in response.

    See Level 7 in Code Studio.

  2. Describe how abstractions help to manage the complexity of code

    In the Wrap Up discussion, make sure students can identify how more abstract blocks can help with creating larger or more complex programs.

Agenda

Lesson Modifications

Warm Up (10 min)

Activity (30 min)

Wrap Up (5 min)

View on Code Studio

Objectives

Students will be able to:

  • Detect when sprites are touching or overlapping, and change the program in response.
  • Describe how abstractions help to manage the complexity of code

Preparation

  • Print copies of the activity guide such that each pair of students has a part A and a part B

Links

Heads Up! Please make a copy of any documents you plan to share with students.

For the Teachers

For the Students

Vocabulary

  • Abstraction - a simplified representation of something more complex. Abstractions allow you to hide details to help you manage complexity, focus on relevant concepts, and reason about problems at a higher level.

Introduced Code

Support

Report a Bug

Teaching Guide

Lesson Modifications

Attention, teachers! If you are teaching virtually or in a socially-distanced classroom, please see these modifications for Unit 3.

Warm Up (10 min)

Teaching Tip

Showing the Game: Avoid signing students into Code Studio at this point to play the game themselves. They have a fairly significant unplugged activity immediately afterwards and it will likely lead to difficulties in transitioning.

Display: On a projector or a computer screen, demonstrate the game that appears in the first level in Code Studio for this lesson.

Discussion Goal

Goal: The purpose of this discussion is just to get some ideas on the board for students to use in the next activity. There's no need to actually evaluate or try them, because students will be working together to do so immediately after the discussion.

Prompt: An interesting aspect of this animation is that the sprites change when they touch each other. Can you think of any way that the computer could use the sprites’ properties to figure out whether they are touching each other?

Discuss: Allow the students to brainstorm ideas for how the computer could determine whether the two sprites are touching. List their ideas on the board and tell them that they’ll have a chance to try out their theories in a moment.

Remarks

This is a tough problem, and we're going to get to dig into it today. As we work on it, we're also going to look at ways that the computer can help us make these tough, complicated problems more simple.

Question of the Day: How can programming help make complicated problems more simple?

Activity (30 min)

Collisions Unplugged

Group: Group students into pairs.

Remarks

Now you’re going to have a chance to try out the strategies that you came up with as a group. Each activity guide has four sheets of paper. One partner should take the papers with the “A” on the top, and the other should take the papers with the “B” on the top. You’re each going to draw two secret sprites on the chart, and your partner will try to figure out whether or not they are touching, based on the same information that the computer will have about each sprite’s properties. Don’t let your partner see what you are drawing.

Distribute the activity guides to each set of partners. Ensure that one partner has taken Version A and the other has taken Version B.

Each student will have a line on which to draw two squares. The student chooses the location and the size of each of the squares, and then records the information about the squares in a table. They then switch tables (not drawings) and try to determine whether or not the two sprites are touching based on the width of each sprite and the distance between them.

The math to determine whether the sprites are touching is as follows:

  1. Subtract the x (or y) positions of the sprites to find the distance between their centers.
  2. Divide the width (or height) of each square by 2 to get the distance from the center to the edge.
  3. If the distance between the centers of the sprites is greater than the sum of the distances from their centers to their edges, the sprites are not touching.
  4. If the distance between the centers of the sprites is equal to the sum of the distances from their centers to their edges, the sprites are barely touching.
  5. If the distance between the centers of the sprites is less than the sum of the distances from their centers to their edges, the sprites are overlapping.

Circulate: Support students as they complete the worksheet. If students are not sure how to determine whether the sprites are touching, encourage them to use one of the ideas on the board. Remind them that they are not being graded on whether they are right or wrong, but on their ability to use the problem-solving process. If any students are finished early, challenge them to find a method that will work for sprites anywhere on the grid, not just on the same line.

Share: After students have all had a chance to test their solutions, ask them to share what they discovered.

Remarks

People can use a lot of different strategies to solve a problem like this. Because computers can’t “see” the drawings in the same way that people can, they need to use math to figure out whether two things are touching. We looked at how this can work along a line, but we can combine these methods to work anywhere on the game screen.

isTouching()

Transition: Send students to Code Studio.

Wrap Up (5 min)

Question of the Day: How can programming help make complicated problems more simple?

Assessment Opportunity

Students should note that even though they could program the code to detect whether sprites are touching each time, it is error-prone and would take up more time and energy than having a block that performs the same code automatically. The new block helps them to take on more difficult challenges by reducing the risk of errors and freeing them to think about the bigger picture.

Prompt: At the beginning of the lesson, you saw that it's possible to do everything that the isTouching block does without using the block at all. What makes this block useful?

Remarks

One of the great things about programming is that once you've figured out a solution to a problem, you can often program it into the computer to be used over and over again. When you don't have to worry about the details of that particular problem, you can take on bigger challenges, as you did today. Using a simplified representation of something to hide the details so you can think about the big picture is called "abstraction", and it's a key tool programmers use to help them write complicated programs.

Key Vocabulary:

  • abstraction - a simplified representation of something more complex.
  • Lesson Overview
  • 1
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Student Instructions

  • Sample Game
  • 2
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Dinner Time!

Run the program to see the robot bring the bunny dinner. When the bunny reaches the bowl, they both stop walking and the bowl becomes empty. What code do you think would help the computer know if two sprites were touching?

View on Code Studio

Teaching Tip

The code in this level is overwhelming. The point is not that students understand every line, but that they see that it's possible to check whether sprites are touching just by using their positions. They should understand that the isTouching block used in the next level automatically runs the complicated code that they see here, but that it's hidden inside the block to make programming easier.

This code does not include the y and height properties because the two sprites are interacting on the same horizontal line. If the bunny could move diagonally, then the code would be even more complicated.

Student Instructions

Using Math to Figure it Out

Computers use math to figure out whether two things are touching. Look at the math on lines 17-18 of this program to see how the sprite properties are compared with their width to see whether they are touching.

Do This

  • Read the if statements inside the draw loop and find the different sprite properties and how they are compared.
  • Discuss the code with your partner.
  • Why does the code only use the width and x properties, and not the height and y properties?
  • Would you want to write this code every time you checked whether something was touching?
View on Code Studio

Student Instructions

isTouching()

Writing out the math each time you want to check whether two sprites are touching can take a while, so a programmer created the isTouching block, which can check whether one sprite is touching another sprite (the target). The computer is still doing the same math as in the previous program, but you don't have to worry about it because another programmer already did that work.

Do This

  • Inside the draw loop, drag the isTouching block into the if block.    ( Show me where )
  • Hint: Don't forget to change the "sprite" to "bunny" and the "target" to "dinner".
View on Code Studio

Student Instructions

Applesauce

The blender should only turn on when the apple touches it.

Do This

  • Use the new code you have learned to check whether the blender is touching the apple.
  • Use a conditional to only shake the blender when the apple is touching it.

Hint: You will need to drag two blocks into the workspace.

View on Code Studio

Teaching Tip

This level does not ask students to fix the bug in the program, which must be done in the animation tab. In order to make the collision work properly, students will need to crop the empty space around the visible part of the picture. The easiest way to do this is to click once on the "crop" icon in the animation tab, which will tightly crop to the smallest rectangle around the visible parts of the picture. Students may also use the rectangular select tool to specify what should be cropped away.

Student Instructions

Debugging Collisions

The balloon is popping before the tack touches it. You can use the debug block to get more information about the bug in the program?

Do This

  • Run the code and use the arrow keys to move the tack to pop the balloon.
  • In the code below, change balloon.debug = false to balloon.debug = true.
  • Add a new debug block to the code and set the tack sprite's debug property to true.
  • Run the code again, then discuss with your partner why the balloon is popping early.
View on Code Studio

Student Instructions

Practice using collision detection with these activities.


Choose from the following activities:
a
Debug: isTouching

Figure out why this code is not detecting the collision, even though it calls isTouching.

b
Circle Colliders

Improve collisions for sprites with circular animations.

View on Code Studio

Student Instructions

Debug: isTouching

The bunny sprite should change to a new animation when it touches the sun sprite. Figure out why the bunny doesn't react to the collision.

Do This

  • Modify the code so that the collision is detected within the draw loop.
View on Code Studio

Student Instructions

Circular Collider

These coins are supposed to stop when they touch, but the colliders are the wrong shape. Change the collider of each coin to a circle.

Do This

  • Use .setCollider() to change the collider of each sprite to a circle.

  • Assessment
  • 8
  • (click tabs to see student view)
View on Code Studio

Assessment Opportunities

Key Concepts:

Create and modify objects (sprites) to manage the complexity of on-screen elements.

Assessment Criteria:
Extensive Evidence

The horse turns into a unicorn when the rainbow touches it. There are no extra blocks in the program.

Convincing Evidence

The program reacts in some way when the rainbow touches the horse.

Limited Evidence

The program uses a conditional and detects when the rainbow touches the horse, but there are enough errors that it does not react in any way.

No Evidence

The program does not detect when the rainbow touches the horse, or there is no conditional in the program.

Student Instructions

Rainbow Horse

When the rainbow touches the horse, it should turn into a unicorn.

Do This

  • Add code that changes the horse sprite's appearance into a unicorn when the rainbow touches it.
View on Code Studio

Student Instructions

Try out these new blocks and challenges with collisions.


Choose from the following activities:
a
Collider at an Angle

Improve collisions for sprites with angled animations.

b
Debug: Add Points on Collision

Figure out why this code is adding way more points than we want it to

c
Free Play

None

View on Code Studio

Student Instructions

Collider at an Angle

Angle the collider to fit the rolling pin.

.setCollider() with multiple parameters

.setCollider() can take more parameters than just the shape. It also takes parameters to specify the x, y offset, width and height, and angle. Check out the documentation for an example.

Do This

  • Use .setCollider() with 6 parameters to give the cucumber a collider that fits it well.

Hint: Hover over the setCollider() block in the toolbox to see an example of how to do this.

View on Code Studio

Student Instructions

Debug: Add Points on Collision

Games often give you points when two sprites touch. This program does that, but notice what happens to the score as the sprites continue to touch. Your challenge is too get it so only one point is scored. There are multiple ways to do this, but the easiest way is to move one or both sprites to a different location right when the score increases.

Do This

  • Read and run the code to understand how it works, and what is going wrong.
  • Identify the line of code that increases the score.
  • Add an additional line of code so that at least one sprite moves to a new (random location).
View on Code Studio

Student Instructions

Free Play

Use what you've learned to create whatever you like. When you're finished, you can click to send your creation to a friend, or to send it to your Projects Gallery.

Standards Alignment

View full course alignment

CSTA K-12 Computer Science Standards (2017)

AP - Algorithms & Programming
  • 2-AP-11 - Create clearly named variables that represent different data types and perform operations on their values.
  • 2-AP-12 - Design and iteratively develop programs that combine control structures, including nested loops and compound conditionals.
  • 2-AP-13 - Decompose problems and subproblems into parts to facilitate the design, implementation, and review of programs.
  • 2-AP-16 - Incorporate existing code, media, and libraries into original programs, and give attribution.
  • 2-AP-17 - Systematically test and refine programs using a range of test cases.