Hello, I’m trying to write this processing code where particles are either attracted to the mouse when it’s pressed or repelled when it’s released. I have PImage representing a basic arrow in b&w, with a keypressed function I would like to make the white pixels of the image attract the particles. Do you have any solution to get to this result?
Here’s my code, a bit messy when I tried to achieve it with a spot array and if statement.
int num = 1000;
Particle[] particle = new Particle[num];
ArrayList<PVector> spots;
PImage img;
float b;
void setup(){
size(1334, 750);
smooth();
img = loadImage("lavraiefleche.png");
image(img, 0, 0);
spots = new ArrayList<PVector>();
img.loadPixels();
for (int x = 0; x < img.width; x++) {
for (int y = 0; y < img.height; y++) {
int index = x + y * img.width;
color c = img.pixels[index];
float b = brightness(c);
}
}
for(int i=0; i<particle.length; i++){
particle[i] = new Particle(new PVector(random(0, width), random(0, height)), 2, 10, 10);
colorMode(HSB);
}
}
void draw(){
background(0);
image(img,0,0)
for(int i=0; i<particle.length; i++){
particle[i].run(mouseX, mouseY);
}
}
and here’s the code of the particles :
class Particle {
PVector loc; //location vector
PVector vel; //velocity vector
PVector acc; //acceleration vector
float sz;
float gravity;
float mass;
int velocityLimit = 5;
float d;
Particle(PVector _loc, int _sz, float _gravity, float _mass){
loc = _loc.get();
vel = new PVector(0, 0);
acc = new PVector(0, 0);
sz = _sz;
gravity = _gravity;
mass = _mass;
}
void display(){
ellipseMode(CENTER);
fill(255);
ellipse(loc.x, loc.y, sz*2, sz*2);
}
void forces(float tx, float ty){
PVector targetLoc = new PVector(tx, ty);
PVector dir = PVector.sub(loc, targetLoc);
d = dir.mag();
dir.normalize();
float force = (gravity*mass) / (d*d);
if(mousePressed){
dir.mult(-1);
} else {
dir.mult(1);
}
applyForce(dir);
}
void applyForce(PVector force){
force.div(mass);
acc.add(force);
}
void update(){
vel.add(acc);
vel.limit(velocityLimit);
loc.add(vel);
acc.mult(0);
}
void bounds(){
if(loc.y > height || loc.y < 0){
vel.y *= -1;
}
if(loc.x > width || loc.x < 0){
vel.x *= -1;
}
}
void run(float tx, float ty){
forces(tx, ty);
display();
bounds();
update();
}
}