Lessons
|
Sensing Blocks
Sensing blocks are one of the eight categories of Scratch blocks. They are color-coded light-blue, and are used to detect things. They can be used to determine the location of the mouse-pointer, its distance from other sprites, and whether a sprite is touching another sprite.
An important part of programming is to give your sprites the ability to sense when things happen. For example, it is important for a sprite to know when it collides with another sprite or when the user presses a key. User Input
The important characteristic of sensing blocks is that they allow for user input and for the program to change or adjust itself according to that user input. The block sense when the user has inputted data into the program. User input can be the click of the mouse, using the arrow keys on the keyboard to make a sprite move around the stage, or when a user types an answer into a question box. The sensing blocks allow the program to sense when user input happens and it can respond to that input.
Sensing a Mouse Click
This sensing block will respond when the right mouse button is clicked. This means that you can have a sprite or part of your program respond to user interaction. This is another example of event driven programming. The script will execute when the mouse button is clicked.
Following the Mouse
Click for Larger Image
One way you can use sensing blocks is to build a script (see left) that will use the mouse pointer to control the movement of the sprite. The code shown on the left will continually have the sprite go to the location of the mouses x and y co-ordinates. (Remember that the sprite's location on the stage is based on x and y co-ordinates.) It has to be in a forever loop to make sure that the sprite continually follows the mouse.
When a Key is Pressed
This block can be used to detect when the users presses a specific key on the keyboard.
When Sprites Collide With the Edge
click for Larger Image
Another way that you can use sensing blocks is to build a script that will have the sprite respond to touching another sprite or the edge of the stage. The script shown on the left is an example of a sprite being programmed to respond to touching the edge of the stage. The sprite will follow the mouse pointer around the stage and when it touches the edge of the stage it will play a sound of a cat meowing.
When 2 Sprites Collide
Click for a Larger Image
Using another sensing code block, you can set up an application to detect a collision for when any part of a sprite comes into contact with a specific color on the stage. This is used to have a sprite detect and respond to contact with another sprite on the stage. This is done by telling the sprite to do something when one color touches another color. For example, the code on the left tells the sprite to change to the next costume when the color black touches the color white.
Asking a question
|