Functions and Variables CHAPTER 3 Variables Variables are
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 mouse. X float mouse. Y
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 1. Return value type 2. Name of the function 3. Parameters 4. { } scope operator 5. Statements to be executed when the function is called. �Two examples for functions we have already used: setup(), draw(), mouse. Pressed()
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 = load. Image(“animal. jpg”); �Write the image on the screen: image( animal, position. X, position. Y, scale. X, scale. Y);
Load Animal function float pos. X; float pos. Y; float scalex; float scale. Y; void load. Animal() { image(animal, pos. X, pos. Y, scale. X, scale. Y); }
Parameters �The animal function can be parameterized. void load. Animal(Pimage animal, float x, float y, float scale. X, float scale. Y) { image(animal, x, y, scale. X, scale. Y); } 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.
- Slides: 7