Hello,
I try to follow the Perlin noise flow field video:
I have a weird behaviour and I don’t understand why. First, here is the code, similar to the one from the video:
flow_field file:
int cols, rows;
int scale = 20;
float inc = 0.1;
float zoff = 0;
Particles[] particle = new Particles[100];
PVector[] flowField;
void setup()
{
size(400, 400);
background(255);
cols = floor(width / scale);
// println(cols);
rows = floor(height / scale);
for(int i = 0; i < particle.length; i++)
{
particle[i] = new Particles();
}
flowField = new PVector[cols*rows];
}
void draw()
{
background(255);
float yoff = 0;
stroke(0, 50);
for(int y = 0; y < rows; y++)
{
float xoff = 0;
for(int x = 0; x < cols; x++)
{
int index = x + y * cols;
// println(index);
float angle = noise(xoff, yoff, zoff) * TWO_PI;
PVector v = PVector.fromAngle(angle);
flowField[index] = v;
pushMatrix();
translate(x * scale, y*scale);
rotate(v.heading());
strokeWeight(1);
line(0, 0, scale, 0);
popMatrix();
xoff += inc;
}
yoff += inc;
zoff += 0;
}
for(int i = 0; i < particle.length; i++)
{
particle[i].follow(flowField);
particle[i].update();
particle[i].display();
particle[i].edges();
}
}
Particles file:
class Particles
{
PVector location;
PVector velocity;
PVector acceleration;
Particles()
{
location = new PVector(random(width - 1), random(height - 1));
velocity = new PVector(0, 0);
acceleration = new PVector(0, 0);
}
void update()
{
location.add(velocity);
velocity.add(acceleration);
//velocity.limit(0.3);
acceleration.mult(0);
}
void display()
{
strokeWeight(3);
stroke(2);
point(location.x, location.y);
}
void applyForce(PVector force)
{
acceleration.add(force);
}
void follow(PVector[] flowField)
{
int x = floor(location.x / scale);
println("X: " + x);
int y = floor(location.y / scale);
println("Y: " + y);
int index = x + y * cols;
applyForce(flowField[index]);
}
void edges()
{
if (location.x < 0)
{
location.x = width;
//velocity.x *= -1;
}
if (location.x > width)
{
location.x = 0;
//velocity.x *= -1;
}
if (location.y < 0)
{
location.y = height;
// velocity.y *= -1;
}
if (location.y > height)
{
location.y = 0;
// velocity.y *= -1;
}
}
}
Now when I run this code, it gives me ArrayIndexOutOfBoundsException when I call applyForce() function.
The problem is that indeed, the value of the index calculated is over the boundaries, but I don’t understand why on the Particles file is calculating wrong and inside the flow_field file, is calculating correctly ?
Hope you can help me to clarify this.