I am working through “Coding Art” and there is an extra task I am not able to solve until now. I am really a beginner and this task seems quite hard without coding experience at all.
I have Particles moving in a circle and changing directions when their distance from center greater than 150:
//reserve memory for 4000 particles
Particle[] particles = new Particle [40];
void setup() {
size(600, 600);
smooth();
noStroke();
//loop through all 4000 particles an initialize
for (int i = 0; i < 40; i++) {
particles[i] = new Particle();
}
}
void draw() {
//dark background
background(35, 27, 105);
//always draw from center of canvas
translate(width/2, height/2);
//loop through all particles
for (Particle p : particles) {
//change position and draw particle
p.move();
p.show();
}
}
//create new class for our particle
class Particle {
float x, y, size, directionX, directionY, shape;
//initialize (called 'constructor')
public Particle() {
this.size = random(1, 17);
this.directionX = random(-1, 1);
this.directionY = random(-1, 1);
}
//function to move the particle position in direction
public void move() {
//calculate distance from center
if (dist(this.x, this.y, 0, 0) > 150) {
//create position and new random target position
PVector position = new PVector(this.x, this.y);
PVector target = new PVector(random(-250, 250), random(-250, 250));
//calculate direction vecotr betwenn current and target position
PVector direction = PVector.sub(target, position);
//divide direction by 300 to make the steps small
direction.div(300);
//set new direction for the particle
directionX = direction.x;
directionY = direction.y;
}
this.x += directionX;
this.y += directionY;
}
//draw the particle on the Processing canvas
public void show() {
//set individual particle color
fill(195, 215, 112);
//draw particle shape
ellipse(this.x, this.y, this.size, this.size);
//draw circle
noFill();
stroke(250);
ellipse(0, 0, 310, 310);
noStroke();
}
}
And the task is to change the ellipses to a rectangle when they change directions. It’s mentioned that it must be done in the show() function. But I have no clue how to do it.
It’s clear to me that I have to do something like:
- if direction changes
- then change the shape to rectangle.
But how do I know, when direction has changed?
I think it must something be like
- store the direction information of each particle in an array
- when a direction changes, change the shape in the show function.
Is this path going in the right direction? Grateful for any suggestions how to solve this.
Thanks in advance.