Custom Code Blocks: Functions with Parameters

Last week we covered an important computer science concept, Variables, and how to use them in a simple jump example. Variables gives us the ability to store a value and track/modify/use it throughout the program. Additionally, last month, we had covered the concept of functions. Functions are a great way to organize your program, bring structure to it, and remove redundancy in writing the same/similar lines of code over and over.

Today, let’s discuss how can we combine the power of functions and variables to re-create the example of a sprite jump where user inputs the height and length of the sprite jump. Here is the script for sprite jump, where user input is defining the height and length of the jump:

Custom Code Blocks: Functions with Parameters

Now let’s see how we can update the Jump function we had created the this blog. This is what it looked like:

Custom Code Blocks: Functions with Parameters - Block Editor

Now, to update it to use the length and height variables we created in the previous blog, we need Jump to be aware of those values. To do that, click on the small plus sign on the right of Jump in Block Editor window. A window asking to Create input name will show up. Enter “Height” in the text box and click OK. The new input name will show up next to Jump like:

Custom Code Blocks: Functions with Parameters - Custom Block with Input

Repeat the same steps to create another input name Length, and update the glide task to use Height and Length variables. This is what the final block will look like:

Custom Code Blocks: Functions with Parameters - Customer Block with Multiple Input Parameters

Click OK.

Now instead of using the glide tasks in the main script, update your program to use the new Jump function block created, to look like:

Custom Code Blocks: Functions with Parameters

Adding input names, Height and Length, to the Jump function block made Jump block (and the tasks defined in the block) aware of the new parameters we had created. We pass our script the height and length values at the time of calling the function and then let the tasks in the function act accordingly the values passed.

It is not necessary to get the values of Height and Length from user input. We can define that in our script as well. For example, we wanted the sprite to jump initially to the height and length of 10, then 20 and then 30, we can use the same Jump function 3 times with different values. In that case, our function would have looked like:

I hope you enjoyed this post. If so, please share your feedback in the comments below.

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *