We all remember our childhood and situations when our mother invited us to the table and informed us that the food was ready. All we were asked to do was sit down and enjoy our meal. Communication is a way of transferring information between different people, and in programming, between different objects.
In Scratch, we can send messages using the broadcast component available in the Events section. Today we will create simple shapes and show/hide them as needed.
Before we start, let's check what we will do today.
Let's start by adding the first sprite called ground. As you probably guessed, this will be the lower part of our stage. When we run our program, we want to move it to the back layer so that the various sprites are not covered up.
The next step is to draw a sprite called a square-button. We can treat it as a source of communication. After clicking, the message will be initialized and sent to our program. Drag and drop the broadcast component and set square-clicked as name for the message.
Once we have a place to initiate the message flow, we need to create a destination that will respond to it. In our example, we will create a square shape that will be hidden by default. When a message is received by a square shape, we will simply show it. Sounds easy, right? Let's move some components to the code section. The most important thing is the When I receive component. We need to select the message we want to react to, which in our case is a square-clicked message.
To make our lesson more attractive, we can create another button called CIRCLE and a separate shape. Of course we need to introduce a new circle-clicked message to separate square and circle flows. At this stage, the code should be very similar and simple.
That’s all. We can test our program and check if all works as expected. Full project can be downloaded from here: broadcast-demo.
Thanks for reading!
Comments
Post a Comment