Lesson
More Inputs
✕
Last topic gave your functions two inputs and left them with one thing they still could not do. Every tree came out the same size, so a tree meant to be far away looked like a tree standing close.
Nothing about an input says it has to be a position. It is just a value the call hands over, and the body can use it for anything at all. Add a third name and use it as a size:
function drawTree(x, y, size) {
shapeColour(BROWN);
rectangle(x - size / 10, y - size, size / 5, size);
shapeColour(GREEN);
circle(x, y - size, size);
}
drawTree(100, 380, 150);
drawTree(330, 240, 70);
A big tree low down and a small one high up, from one set of drawing lines. That is depth, and one input bought it.
The catch is the same catch as before, one step further on. Every part of the drawing that should grow has to mention size. The trunk's width is written size / 5 and its height size, so both follow the call. Write a plain 20 in there instead and every tree gets the same trunk however big its leaves are.
Writing the parts as sums of size is what makes a drawing scale rather than stretch. A snowman's head written size / 2 is half its body at any size you ask for.
An input does not even have to be a number. A colour is a value too:
function drawTree(x, y, size, colour) {
shapeColour(BROWN);
rectangle(x - size / 10, y - size, size / 5, size);
shapeColour(colour);
circle(x, y - size, size);
}
drawTree(160, 350, 110, ORANGE);
Four inputs, and nothing new to learn. Each name is a box, the call fills them in order, and the body uses each one where it needs it.
The order still decides everything, and it bites harder now that the inputs mean different kinds of thing. Hand over a size where the down number belongs and you get a sun that fills the sky, with no error to tell you: the numbers were all fine, they just landed in the wrong boxes.
And an argument can still be worked out rather than typed. A variable works, size / 2 works, and one number in a variable can decide a whole row of sizes at once.
One thing is starting to nag. A house needs a wall, a roof and two windows, and you find yourself calling the same handful of functions in the same order over and over. Next topic, a function gets to call another function — so drawHouse can put its own windows in.