Hi there,
I am working on a random walker through points, and I am struggling to get the next closest point in the walker class.
The idea is to have one or few random walkers going from point to point until there is no point left.
void update(ArrayList<Anchor> anchors) {
if (anchors.size()>0) {
int idx = getNearest(anchors);
println(""+idx);
Anchor a = anchors.get(idx);
PVector move = a.pos;
previousPos.set(pos);
pos.add(move);
anchors.remove(idx);
}
}
int getNearest(ArrayList<Anchor> anchors) {
float record = 1000;
int idx = 0;
for (int i = 0; i >= anchors.size(); i++) {
Anchor anchor = anchors.get(i);
float dist = pos.dist(anchor.pos);
if (dist < record) {
dist = record;
idx = i;
}
}
return idx; // give index of nearest target
}
It seem that the int idx never really update in the int getNearest(ArrayList anchors) function
Bellow the complete code;
ArrayList<Walker> walkers;
ArrayList<Anchor> anchors;
PVector pos;
int walkerCount = 1;
int anchorCount = 500;
float x = 0;
float y = 0;
void setup() {
size(800, 800);
background(51);
frameRate(60);
walkers = new ArrayList<Walker>();
anchors = new ArrayList<Anchor>();
for (int i = 0; i < walkerCount; i++) {
PVector origin = new PVector(random(width), 0);
walkers.add(new Walker(origin, color(random(256), random(256), random(256))));
}
for (int i = 0; i < anchorCount; i++) {
PVector position = new PVector(random(width), random(height));
anchors.add(new Anchor(position));
}
}
void draw() {
for (int i = 0; i < walkers.size(); i++) {
Walker w = (Walker) walkers.get(i);
w.update(anchors);
w.show();
}
for (int i = 0; i < anchors.size(); i++) {
Anchor a = (Anchor) anchors.get(i);
a.show();
}
}
class Walker {
PVector pos;
PVector previousPos;
color col;
Walker(PVector position, color c) {
col = c;
pos = new PVector(position.x, position.y);
previousPos = pos.copy();
}
void show() {
strokeWeight(4);
stroke(col);
//point(pos.x, pos.y);
line(previousPos.x, previousPos.y, pos.x, pos.y);
}
void update(ArrayList<Anchor> anchors) {
if (anchors.size()>0) {
int idx = getNearest(anchors);
println(""+idx);
Anchor a = anchors.get(idx);
PVector move = a.pos;
previousPos.set(pos);
pos.add(move);
anchors.remove(idx);
}
}
int getNearest(ArrayList<Anchor> anchors) {
float record = 1000;
int idx = 0;
for (int i = 0; i >= anchors.size(); i++) {
Anchor anchor = anchors.get(i);
float dist = pos.dist(anchor.pos);
if (dist < record) {
dist = record;
idx = i;
}
}
return idx; // give index of nearest target
}
}
class Anchor {
PVector pos;
color col;
Anchor(PVector position) {
col = color(0);
pos = new PVector(position.x, position.y);
}
void show() {
strokeWeight(4);
stroke(col);
point(pos.x, pos.y);
}
void update() {
}
}
I am very grateful for any advice,
Many thanks