Lesson 16: Collision Detection
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.
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.
Warm Up (10 min)
Wrap Up (5 min)
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
- Print copies of Collision Detection - Activity Guide such that each pair of students has a part A and a part B
For the Teacher
- Collision Detection - Exemplar
For the Students
- Collision Detection - Activity Guide
- 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".
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.
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.
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.
Group: Group students into pairs.
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:
- Subtract the x (or y) positions of the sprites to find the distance between their centers.
- Divide the width (or height) of each square by 2 to get the distance from the center to the edge.
- 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.
- 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.
- 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.
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.
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.
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.
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.
- Sample Game
- Student Overview
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?
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.
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.
- 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?
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.
Hint: Don't forget to change the "sprite" to "balloon" and the "target" to "tack".
When the apple hits the blender, the blender should turn on.
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?
You can also use code to play a blender sound.
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:
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?
- Run the code and use the arrow keys to move the tack to pop the balloon.
- In the code below, change
balloon.debug = falseto
balloon.debug = true.
- Add a new
debugblock to the code and set the tack sprite's debug property to
- 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?
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 )
- Use the
isTouchingblocks 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.
Improve Your Game
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.
- Add at least two effects when your sprites collide.
Challenge: Add a scoreboard to the top of your screen.
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.