reflection of a particle
@author
int COUNT = 200;
PVector loc, vel;
float circleR = 30;
void setup(){
size(500, 500);
noStroke();
initialize();
}
void initialize(){
loc = new PVector(width / 2, height / 2);
float velSize = 10;
float velAng = random(TWO_PI);
vel = new PVector(velSize * cos(velAng), velSize * sin(velAng));
}
void draw(){
if(frameCount % COUNT == COUNT - 1){
initialize();
}
background(#CAE7F2);
fill(#A52175, map(frameCount % COUNT, 0, COUNT - 1, 255, 0));
float r = float(frameCount % COUNT) / COUNT < 0.1 ? map(float(frameCount % COUNT) / COUNT, 0, 0.1, 0, circleR): circleR;
ellipse(loc.x, loc.y, r * 2, r * 2);
loc.add(vel);
PVector n = null;
if(loc.x < circleR){
reflect(new PVector(1, 0));
}
if(loc.x > width - circleR){
reflect(new PVector(-1, 0));
}
if(loc.y < circleR){
reflect(new PVector(0, 1));
}
if(loc.y > height - circleR){
reflect(new PVector(0, -1));
}
}
void reflect(PVector n){
PVector vn = PVector.mult(n, PVector.dot(vel, n));
PVector vt = PVector.sub(vel, vn);
vel = PVector.add(PVector.mult(vn, -1), vt);
loc.add(vel);
}