Week 05
Functions: the basics

# 1. Function we are calling 'ellipse function" to make ellipse..

1
ellipse(100,100,100,100);
Copied!

# 2. Function setup started functioning when the page opens without calling it...

1
function setup() {
2
createCanvas(500, 500);
3
}
Copied!

# Function needs "Define" and "Call"

### We defined setup:

1
function setup(){
2
ellipse(10,10,10,10);
3
}
Copied!

1
setup();
2
Copied!

### ellipse()

We did not define:
1
function ellipse(){
2
stroke(10,10,10,10);
3
rotate(1,1,1,10);
4
}
5
Copied!
But we called:
1
ellipse(10,10,10,10);
2
Copied!

# Let's 'Define' and 'Call' Your Own Function.

1. 1.
Modular
2. 2.
Reusable

## We made ball bouncing with ball object.

1
var ball = {
2
x : 300,
3
y : 200,
4
xspeed : 4,
5
yspeed : -5
6
}
7
8
function setup() {
9
createCanvas(400, 400);
10
}
11
12
function draw() {
13
background(220);
14
ellipse(ball.x,ball.y,20,20);
15
16
17
if (ball.x>width || ball.x<0){
18
ball.xspeed = ball.xspeed*-1;
19
}
20
if (ball.y>height || ball.y<0){
21
ball.yspeed = ball.yspeed*-1;
22
}
23
24
ball.y = ball.y + ball.yspeed;
25
ball.x = ball.x + ball.xspeed;
26
27
}
Copied!

1. 1.
Drawing
2. 2.
Bouncing
3. 3.
Moving

## Let's make with functions.

### function move

1
function move(){
2
ball.y = ball.y + ball.yspeed;
3
ball.x = ball.x + ball.xspeed;
4
}
Copied!

### function bounce

1
function bounce(){
2
if (ball.x>width || ball.x<0){
3
ball.xspeed = ball.xspeed*-1;
4
}
5
if (ball.y>height || ball.y<0){
6
ball.yspeed = ball.yspeed*-1;
7
}
8
}
Copied!

### function display

1
function display(){
2
ellipse(ball.x,ball.y,20,20);
3
}
Copied!

### ​https://editor.p5js.org/kdoodoo/sketches/ByW1H_x9X​

1
var ball = {
2
x : 300,
3
y : 200,
4
xspeed : 4,
5
yspeed : -5
6
}
7
8
function setup() {
9
createCanvas(400, 400);
10
}
11
12
function draw() {
13
background(220);
14
move();
15
bounce();
16
display();
17
}
18
19
function move(){
20
21
ball.y = ball.y + ball.yspeed;
22
ball.x = ball.x + ball.xspeed;
23
}
24
25
function bounce(){
26
if (ball.x>width || ball.x<0){
27
ball.xspeed = ball.xspeed*-1;
28
}
29
if (ball.y>height || ball.y<0){
30
ball.yspeed = ball.yspeed*-1;
31
}
32
}
33
34
function display(){
35
ellipse(ball.x,ball.y,20,20);
36
}
Copied!

# Define and Call

### Define

Define functions:
1
function move(){
2
3
ball.y = ball.y + ball.yspeed;
4
ball.x = ball.x + ball.xspeed;
5
}
6
7
function bounce(){
8
if (ball.x>width || ball.x<0){
9
ball.xspeed = ball.xspeed*-1;
10
}
11
if (ball.y>height || ball.y<0){
12
ball.yspeed = ball.yspeed*-1;
13
}
14
}
15
16
function display(){
17
ellipse(ball.x,ball.y,20,20);
18
}
Copied!

Call functions:
1
move();
2
bounce();
3
display();
Copied!