Ever wondered how animations are made ?

Well it’s simple, the picture is reshown with slight differences, giving the illusion of motion. Each time there is a change we say that a frame is being redrawn.

The number of frames drawn per second is called the frame rate and can be controlled via frameRate(30);

the default is 60 fps

We are taking a language called Processing found at http://www.processing.org

The coordinates system

In programming, often the coordinate system is taken like that :

—————> positive x-axis

|

|

|

V

positive y-axis

not the maths way

Starting animations

well let us lay out the basic structure.

void setup(){

}

void draw(){

}

setup() and draw() are two functions

codes in setup() are executed only once

codes in draw() are executed several times, so anything you want to move must be placed in the draw() function

The format is the same as Arduino setup/loop , no wonder, Arduino is based on Processing

The first thing to do is to specify a size.

size(400,400);

specifies a canva of width 400 pixels and height 400 pixels

now, let us add a background in draw()

background(0);

normally it’s in the format background(r,g,b) where rgb represent red green and blue and take values from 0 to 255 so,

background(0,255,0); will be green. However, a shortcut for black and white :

background(0);  is black and background(255); is white

Now let us draw the ball we will be moving. it is really only a circle.

 fill(255);
 ellipse(10,10,20,20);

fill sets the colour to white. fill does take rgb values like background. The parameters of ellipse are:

ellipse(x,y,x-diameter,y-diameter);

of course, for a circle, x and y radius same.

if you run the code you should see a white circle at x 10, y 10 and radius 10

Our code up to now :

void setup(){
  size(400,400);
}

void draw(){
  
 background(0);
 fill(255);
 ellipse(10,10,20,20);
  
}

Moving the circle

Let us start by variables,

you can declare variables by

data-type name;

you can have int x, String x etc.

int stands for integers

let us initialise our variable to 10

int x = 10;

let us change our circle’s x-coord to variable x

from ellipse(10,10,20,20); to ellipse(x,10,20,20);

ellipse(x,10,20,20);

if you run the script it will be the same as the previous one.

imgpr

Now to make it move, you need to make the x location be changed each time.

30 this frame, 31 next, 32 33 34 and so on.so, with each frame, the value must change, you added one to the previous value each frame.

so, x = x + 1;

if you put that sfter the circle code, the circle will move!

Now, that was a long for nothing explanation, better start coding right from :

int x = 0;

void setup(){
  size(400,400);
}

void draw(){
  
 background(0);
 fill(255);
 ellipse(x,10,20,20);
 x += 1;
  
}

// this is a commentfor one line
/*That one for several lines*/
Advertisements