70 likes | 217 Views
Functions and Variables. Chapter 3. Variables. Variables are used to represent data within Processing environment Defining a variable: its type, name and value Example: Position of the mouse on the screen: f loat mouseX f loat mouseY. Functions.
E N D
Functions and Variables Chapter 3
Variables Variables are used to represent data within Processing environment Defining a variable: its type, name and value Example: Position of the mouse on the screen: float mouseX float mouseY
Functions A function is coherent piece of code that can be invoked/activated/called by specifying its name. Syntax of a function/ Rules to write a function Return value type Name of the function Parameters { } scope operator Statements to be executed when the function is called. Two examples for functions we have already used: setup(), draw(), mousePressed()
Function Examples Write a function to draw an animal. Call it every time mouse is pressed. How to do this? Define a image variable: PImage animal; Load the picture file into the image variable: animal = loadImage(“animal.jpg”); Write the image on the screen: image( animal, positionX, positionY, scaleX, scaleY);
Load Animal function float posX; float posY; float scalex; float scaleY; void loadAnimal() { image(animal, posX, posY, scaleX, scaleY); }
Parameters The animal function can be parameterized. void loadAnimal(Pimage animal, float x, float y, float scaleX, float scaleY) { image(animal, x, y, scaleX, scaleY); } How do you determine values of the parameters: lets see if we can use random function.
Random pre-defined function float temp = random(0,100); float x = random(500); Lets work on the Animal example and check the functions out.