Ch. 1
Ch. 2

# Lesson 16: Collision Detection

## Overview

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, including playing sounds. Last, they use their new skills to improve the sidescroller game that they started in the last lesson.

## 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.

## Objectives

### Students will be able to:

• Use the isTouching block to determine when two sprites are touching
• Describe how abstractions help to manage the complexity of code

## Preparation

Heads Up! Please make a copy of any documents you plan to share with 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.
• Debugging - Finding and fixing problems in an algorithm or program.
• If-Statement - The common programming structure that implements "conditional statements".

## Introduced Code

• ``` sprite.isTouching(target) ```
• ``` sprite.debug ```

# Teaching Guide

## Warm Up (10 min)

Review: Briefly remind students of the side scroller game they made in the last lesson, and ask them to share out any ideas they had for improving their game in the future.

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 just a computer screen demonstrate the game that appears in the first level in Code Studio for this lesson. The teacher or a student can control the frog to jump over a mushroom. Make sure at least some jumps are successful and some are not to see that the collision detection is working.

Discussion Goal

Goal: This 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 improvement in this game is that the mushroom moves when the frog touches it. 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.

## Activity

### 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, so don’t let your partner see what you are drawing.

Distribute: The Collision Detection - Activity Guide to each set of partners. Ensure that one partner has taken the pages with "A" on the top and the other has taken the pages with "B" on the top.

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: Have the class log onto Unit 3 - Code Studio Levels for Lesson 16.

Display: Show bubble 2, and allow students to look in and discuss in pairs how they might code the behavior that they see in the program.

Discussion Goal

Goal: The goal of this discussion is for students to see that the math in the code is the same math described in the unplugged activity. The code combines the tests for x and y in nested "if" statements.

The purpose of this level is for students to see that they can test whether two sprites are touching with the blocks that are already available to them. The code is complicated, but it only uses blocks students have already learned to detect when two sprites are touching.

Discuss: Ask the students how the code below relates to what they did in the unplugged activity.

Remarks

Even though this code works, it can be hard to read, and it would be easy to make a careless error when you’re writing it. It would also take some time to write out every single time, so a programmer saved the code into one block that we can use to figure out whether two sprites are touching, and we don’t need to write all of this code. Because this is something a programmer wants to do over and over again, someone has created a block called `isTouching()` that already has all of the math inside of it. Hiding the details of how something is done to make it easier to program is called abstraction.

Circulate: Support students as they work through levels 3-8. Level 8 allows students to work on the side scroller that they created in the last lesson. It is very open, so encourage students to be creative and try to code sprite interactions that they haven’t seen before. Students who complete the level early can continue to add new interactions or improve their games in other ways.

## Wrap Up (5 min)

Prompt: What were some different things that your sprites did when they interacted? What is one type of interaction you’d like, but you haven’t seen yet? Do you have any ideas for how you might write the code for that type of interaction?

Share: Once students have finished journaling, allow them to share out the different type of interactions they’d like to see. Let them know that you will be learning more ways for sprites to interact later in the unit.

View on Code Studio

# Frog Jump

Look at the frog jumping game to the left. It looks like the game from the last lesson, but the frog moves the mushroom if it hits it. What code do you think would help the computer to know whether two sprites are touching?

View on Code Studio

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.

View on Code Studio

# Balloon

The code below uses the sprites' x and y positions to check whether they are touching. It will change the balloon sprite's animation when the tack touches it. Use the arrow keys to move the tack until it touches the balloon.

# Do This

• You do not need to change any code on this level.
• 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. Would you want to write this code every time you checked whether sprites were touching?
View on Code Studio

# 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 "balloon" and the "target" to "tack".

View on Code Studio

# Applesauce

When the apple hits the blender, the blender should turn on.

# Do This

Use the `isTouching` block to make the blender shake back and forth when the apple sprite touches the blender sprite. The shaking motion is already coded using the random block, so you just have to check when the two sprites are touching.

Challenge: Can you make the apple disappear when it touches the blender?

View on Code Studio

# Making Sounds

You can also use code to play a blender sound.

# Do This

Use the `playSound` block from the "World" drawer to play the "https://docs.code.org/sounds/blender.mp3" sound when the apple touches the blender. You will need to paste the address of the sound into the block, so it looks like this:

View on Code Studio

# Rainbow Horse

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

# Do This

Use the `if`, `isTouching`, and `setAnimation` blocks to change the horse sprite's image when the rainbow touches it. The unicorn image is already loaded in the animations tab for you.

View on Code Studio

# Debugging Collisions

The balloon is popping before the tack touches it. When sprites aren't doing what you expect, you can use the `debug` block to get more information about why the sprites are behaving that way. Can you find out what's wrong in the code below?

# 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.

Challenge: Can you use the animations tab to resize the balloon picture so it pops at the correct time?

• Collisions in Games
• 9
• 10
• (click tabs to see student view)
View on Code Studio

# Scoreboard

You can also use `isTouching` to decide whether you should increase the score. In this game, the score is stored inside the 'score' variable. It is displayed on the screen using the `text` block. ( Show me where )

# Do This

• Use the `if` and `isTouching` blocks to determine whether the bunny has caught the carrot. ( Show me where )
• If it has, do the following three things:
• Use the counter pattern on the score variable to increase the score.
• Reset the carrot's x position off the right-hand side of the screen.
• Set the carrot's y position to a random number between 10 and 390.
View on Code Studio

### Student Instructions

Now that you know how to use `isTouching` and `playSound`, you can make some fun things happen when your sprites run into each other.

Note: The `playSound` block now has an extra parameter called "loop" that can be set to true or false. If this parameter is true, the sound will continue to play in a loop.

# Do This

• Levels
• Extra
• (click tabs to see student view)
View on Code Studio

# 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

#### 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.