Operators and Variables

Display messages on the console – print() command

You can use the print() command to display messages on the console.

For example : - print(20);  // will display 20 on the console

Literals

Literal is short for literal value. Literal value means actual value and not a name of anything. For example in the code below ‘size’ is the name of a command and not an actual value. Similarly print is the name of a command and not an actual value. But 600 is an actual value. So is 21.5

In P5JS there are 4 types of literals that you can use in your code as described below

    1. Whole number – Integer literal – eg. 600

    2. Decimal number – float literal – eg. 20.52

    3. Text (words) – String literal (enclosed in double quotes) – eg. “My age is 10”

    4. Boolean – true or false literal

                        Sketch         

 1

 2

 3

 4

 5

 6

 7

 8

 9

function setup() {

  createCanvas(600,400);

  background(220);

  print(21);          // 21 is whole number (integer literal)

  print(21.5);  // decimal number (float literal)

  print("my age is 10");  // text (String literal)

  print(true);  // boolean literal true

  print(false); // boolean literal false

}

                


Arithmetic Operators

Arithmetic operators allow you to add, subtract, multiply, divide and find remainder. The values on which the operator does the calculation are known as operands

Operator

Description

Example

Result

+

Add

21 + 5

26

-

Subtract

20 – 5

15

*

Multiply

5 * 10

50

/

Divide

55 / 10

5

%

Remainder

11  % 3

2

%

Remainder

10 % 5

0

Note: 11 % 3 will give the remainder of 11 divide by 3.  If we divide 11 by 3 then what will be the remainder? Ans:  2

What will be the result of 10 % 4?

                        

Drawing a cart using operators

                        Sketch Draw Cart with operators

 1

 2

 3

 4

 5

 6

 7

 8

 9

10

11

function setup() {

  createCanvas(600,400);

  background(220);

  rectMode(CENTER);

  // left wheel 60 pixels left of centre

  ellipse(300 - 60, 200, 50, 50);

  // right wheel 60 pixels right of centre

  ellipse(300 + 60, 200, 50, 50);

  // cart body 25 pixels above centre

  rect(300, 200-25, 200, 20);

}

                        


Variables

A variable is a tiny portion of the computer’s memory in which we can store a value. Every variable is has a name and its value can keep changing

Below Diagram shows 4 variables created in the computer’s memory or RAM.

The names of the variables are length, gender, width and weight. We have stored 14 in the variable length, “Male” in the variable gender, 14 in width and 64.5 in the variable weight.


Creating a variable in RAM

We can tell the computer to create a variable with the var command. The below lines create 3 variables.

var length;

var gender;

var weight;

Changing the value of a variable (Assigning a value to a variable)

We can change the value of a variable by assigning a value to it. You can assign a value to a variable with the assignment operator ‘=’.

Eg.

length=14;   //  assigns 14 to the variable length  or stores 14 in the variable length

gender=”Male”;  // assigns ”Male”  to the variable gender

width=length;   // assigns the value of the variable length (ie. 14) to the variable width


Draw cart using variables

                        Sketch Draw Cart using variables

 1

 2

 3

 4

 5

 6

 7

 8

 9

10

11

12

13

function setup() {

  createCanvas(600,400);

  background(220);

  rectMode(CENTER);

  var xCenter = 600 / 2;

  var yCenter = 400 / 2;

  // wheel1 60 pixels left of center

  ellipse(xCenter - 60, yCenter, 50, 50);

  // wheel2 60 pixels right of center

  ellipse(xCenter + 60, yCenter, 50, 50);

  // cart body 25 pixels above center

  rect(xCenter, yCenter - 25, 200, 20);

}

Coding in Active Mode

P5JS executes sketches in 2 separate modes: Static or Active. All our previous sketches have been executed in Static mode.

In active mode your code is divided into 2 functions: setup()  and draw().

Let us divide our draw cart sketch into these 2 functions

                        Sketch Draw Cart in Active mode

 1

 2

 3

 4

 5

 6

 7

 8

 9

10

11

12

function setup() {

  createCanvas(600, 400);

  rectMode(CENTER);

}

function draw() {

  var xCenter = 600 / 2;

  var yCenter = 400 / 2;

  ellipse(xCenter - 60, yCenter, 50, 50);  //left wheel

  ellipse(xCenter + 60, yCenter, 50, 50);  //right wheel

  rect(xCenter, yCenter - 25, 200, 20);    //cart body

}

From now on all our sketches will be in active mode

Local variables vs global variables

Local variables are created inside a function and can be used only inside that function.

Global variables are created outside a function, and they can be used by any function in the program or sketch.


In the below sketch we have created a local variable called x inside setup(). When you run the sketch, line 10 will give you an error on the console ‘ ReferenceError: x is not defined ’. Since x was created inside setup(), it is not available to the function draw().

                        Sketch

 1

 2

 3

 4

 5

 6

 7

 8

 9

10

11

function setup() {

  createCanvas(600, 400);

  var x;

  x=25;

}

function draw() {

  var y;

  y=400/2;

  ellipse(x, y, 50, 50);

}

Now if we create variable x outside a function as in the sketch below at line 1, the error will go away.

                        Sketch

 1

 2

 3

 4

 5

 6

 7

 8

 9

10

11

var x;

function setup() {

  createCanvas(600, 400);

  x = 25;

}

function draw() {

  var y;

  y = 400 / 2;

  ellipse(x, y, 50, 50);

}

Animation with processing

As explained earlier the computer executes the draw function 60 times in a second. What happens if each time draw is executed we draw the circle 5 pixels further to the right. To do this just before ending the function draw() let us increase the value of the variable x by 5 (see line 11).  

                        Sketch

 1

 2

 3

 4

 5

 6

 7

 8

 9

10

11

12

var x;

function setup() {

  createCanvas(600, 400);

  x = 25;

}

function draw(){

  var y;

  y = 400 / 2;

  ellipse(x, y, 50, 50);

  x = x + 5;

}


                                                Sketch Output - Canvas


Now let us make a small change in the draw function. Before drawing the circle let us erase the canvas by filling the entire canvas with a background colour using the background() command (See line 8 in the sketch below). This will erase the previous circle before drawing the next circle.

                        Sketch

 1

 2

 3

 4

 5

 6

 7

 8

 9

10

11

12

13

var x;

function setup() {

  createCanvas(600, 400);

  x = 25;

}

function draw() {

  background(225);

  var y;

  y = 400 / 2;

  ellipse(x, y, 50, 50);

  x = x + 5;

}

 

When you run the above sketch you will see the circle moving. In effect what the computer is doing is 60 times in a second erasing the canvas and then drawing a circle 5 pixels to the right thus giving us the illusion of movement.

Question:  How will you reduce the speed of the moving circle?

background() command

The background() command fills the entire canvas with a colour - in effect erasing the canvas.  The background() command recieves 1 parameter, the shade of grey between 0 and 255 where 0 is black and 255 is white.


Practice assignments

  1. Animate a circle moving from top to bottom

  1. Animate a square growing bigger and bigger – use rect() command


  1. Animate ball from right to left

  1. Define 2 variables num1=10, num2=20. Write code to swap the values of the 2 variables. i.e. num1 should become 20 and num2 should become 10. Put all the code in the setup function. Leave the draw function empty.

        

                void setup(){

                        int num1=10;

                        int num2=20;

                        // put code to swap the values of the variables num1 and num2 here

                        print(num1); // should print 20

                        print(num2); // should print 10

                }

Hint: A sketch can have as many variables as you want.


Recap


Extra Info

Note 1: A local variable is destroyed once execution of the function is over. If the function is executed again a new variable gets created. Thus local variables cannot preserve their values across function executions.  Where as global variables are not destroyed when function execution has ended. Thus global variables preserve their values across function executions.

Note 2: As far as possible create local variables, avoid creating global variables. Create a global variable only when you want the variable to be used by multiple functions or you want to preserve the value of the variable across function executions.

Note 3: Two local variables can have the same name as long as they are in different functions. Global variables cannot have the same name