Collision Detection for 2D Physics
-
Introduction
Collision detection is a very commonly used technique for handling interaction between objects. In traditional Scratch, we often use the “touching object” or “touching color” sensing blocks to detect if 2 objects are overlapping. When we are using the 2D physics engine, we have a new way of detecting and handling collisions.
Broadcast a Message When There is a Collision
When you run a 2D physics project, there can be a lot of collisions between objects. To tell the physics engine which collisions you are interested in, you can ask the physics engine to broadcast a message when the current sprite collides with another sprite. It’s like telling the physics engine “Hey, whenever I collide with the box, please let me know right away!”.
To specify the message, you should add a “when I receive” block first, then define a new message using the dropdown, such as “hit box”.
After that, you can add the following block to tell the physics engine you want to broadcast this message whenever the current sprite collides with another sprite:
The first input is a dropdown of all the messages available, and you can choose the new message type you have just added.The second input is a dropdown of all the sprites in the project, and you need to pick which collision target you are interested in.
After running this block, you can handle the collision in the “when I receive” block.
Example 1
In this project, we have 2 sprites: "monkey’ and “box”.
In the monkey sprite, we ask the physics engine to broadcast the “hit box” message when the monkey hits the box. And whenever it receives that message, it will make the monkey jump up and say “Yeah!”.
Here is the result:
Here is the shared project:https://play.creaticode.com/projects/15694ee9118e145f69780147
Collision Message Parameters (Advanced)
To get more information about the collision, you can use the “when I receive with parameter” block. You need to define a new variable first, such as “info”, then select it in the dropdown:
When the message is received, the “info” parameter will contain a 4-part text like this:
The 4 parts are separated by commas between them.The first part is the name of the target sprite that we are colliding with.
The second and third parts are the x and y positions of the target sprite we are colliding with.
Lastly, the fourth part is the “clone ID” of that sprite. This is useful when the target sprite has multiple clones.
Example 2
In this project, we have 2 sprites: “monkey” and “balloons”.
In the balloons sprite, we create 7 clones with IDs of 1 to 7. So when the monkey collides with any balloon, the “info” variable will contain the ID for the specific clone we are hitting.
Here is what it looks like:
Here is the shared project:https://play.creaticode.com/projects/3a79ec89ac27ccb38bb7e20e