Recitation:
In today’s recitation, we are expected to practice the function and arrays, especially the loop and arrays, they are two great function to shorter the code. I used them to build an animation with many elements.
step 1
In the first step, I use the arc(); to build an eater.
step2
using for loop(); to build 100 elements.
put the loop under the void draw();
step3&step4
int eaters = 100; float[] x = new float [eaters]; float[] y = new float [eaters]; color[] c = new color [eaters]; float [] speedX = new float [eaters]; float [] speedY = new float [eaters]; float[]size=new float[eaters]; void setup() { size(600, 600); background(255); ellipseMode(RADIUS); for (int i=0; i<x.length; i++){ x[i]=random(width); y[i]= random(height); speedX[i]= random(-5, 5); speedY[i]= random(-5, 5); size[i]= random(10,200); c[i]= color(random(255),random(255),random(255));}} void draw(){ background(255); for (int i=0; i<x.length; i++) { eater(x[i], y[i], size[i], c[i]); x[i]= x[i] + speedX[i]; y[i]= y[i] + speedY[i]; if (x[i] > width || x[i]< 0) { speedX[i] = -speedX[i];} if (y[i] > height || y[i]< 0) { speedY[i] = -speedY[i];}} } void eater(float x, float y, float size, color c) { noStroke(); fill(c); arc(x*10+15, y*10+10, size, size, 0.52, 5.76); fill(255); ellipse(x*10-size*0.3, y*10-size*0.4, size*0.1, size*0.1); rectMode(CENTER); fill(c); rect(x*10+15+size*1.2, y*10+10, size*0.5, size*0.5);} optional: use the keypressed to control it.
if (keyPressed==false){ } else{
Question1: If the for loop under the 'setup', it can only run once.So the image stay still. But if you put it under the draw();, the loop will run over and over again, so the image will be given different position, and at last the image will display everywhere. Question2: In my animation, there are 100 elements, if I don't use the arrays, I have to control every elements individually, and this will lead to a very complex code. Thanks to the arrays I can make it clear and understanding.