<< Chapter < Page | Chapter >> Page > |
This process of providing information to a function when you call it is commonly referred to as passing parameters to the function. For the square-root function, you need to pass a parameter whose value is the value ofthe number for which you need the square root.
You call the built-in square root function in Scratch 2.0 by dragging the bottom block shown in Image B into the programming panel and selecting sqrt in the pull down list. You pass the parameter by entering a literal value or dragging a variable block into the white areathat contains the 9 character in Image B .
A function or method will usually
You might think of performing an action as something like causing a Scratch sprite to move to the right and change color.
None of the Scratch 2.0 mathematical functions shown in Image C perform an action. One of the purposes of this module is to teach you how to create customblocks that do perform an action.
On the other hand, a function that is designed to calculate the square root of a number needs to be able to send the square-root value back to the programthat called the function. After all, it wouldn't be very useful if the function calculated the square root and then kept it a secret. The process of sendingback an answer is commonly referred to as returning a value .
All of the Scratch mathematical functions shown in Image C return a value.
It appears that there is no straightforward way for you to cause a custom block that you design to return a value. However, I will show you a workaroundfor that situation later.
The best explanation that I have found for the mechanics of creating a custom block is contained in the document titled How Do I Use the New Blocks? on the MIT website. Go to that webpage and scroll down to the section titled Make Your Own Blocks . Follow the instructions that you find there to create your own custom blocks.
With that as an introduction, this section will present and explain two Scratch 2.0 programs built around custom blocks.
This is the simplest custom block that I could come up with that:
This program contains the two scripts and a variable shown in Image D . These scripts are tied to the cat sprite.
The variable named var shown on the left in Image D is a global variable. That means that it is accessible by any code in the program.
The custom block named test is shown in the bottom script in Image D . When called, this block receives an incoming numeric parameter known locally as number1 . The code in the block multiplies that value by a factor of 2 and stores the resulting product in the variable named var , making it available to the code that called the custom block.
Notification Switch
Would you like to follow the 'Teaching beginners to code' conversation and receive update notifications?