B CUSP 110B – Digital Thinking Exercise 6:
Defining and Using Functions |
|
In this exercise we will practice with three aspects of working with functions in C#:
· Defining a function based on our needs
· Calling the function
· Defining a function that accepts parameters and experimenting with passing parameters
Please work with the person next to you, start with this source code. Download compile and run this program to see a simple bee where you cannot do anything with. Examine the source code: remember what we always do when examining source code:
· Look at variable declarations
· Variable initialization
· Variable update
Step 1: Defining a function to move the bee …
Define a new function:
After you have done with defining this function, compile and run, can you control your circle/bee now? Why not? Modify your code so that you can control the circle/bee with right thumbstick (arrow keys).
Here we see a function is defined/called at every Update!
Step 2: Define a function to be called conditionally. Let’s find a way for the bee to drop something …
Define a new function:
Now, let’s drop a new square every time Button-A is pressed:
Here, we defined a new behavior (drop the square), and only perform this
behavior when the player tells us to.
Click the A-button (K-Key) a few times, not very interesting is it? All the squares landed in the exactly same place! No fun!!
Step 3: Well, let’s parameterize the dropping of square to the location of
the bee!!
Let’s define a new function that parameterizes
the dropping of squares …
Notice that this function drops a rectangle at the specified location (xPos, yPos). Now modify you code to call DropASquare() to (myCircle.CenterX, myCircle.CenterY) whenever the B-Button (L-Key) is clicked.
In this
exercise you have practiced:
· defining a function
· calling the function you have defined
· passing parameters to a function