Hi guys, I’m trying to write a code based on steering behaviors. And I’m having problems with a vehicle particle, when it starts to going close of the target it begins move strangely. I think something is wrong with the heading() method… but I don’t know what… Any help will be very appreciated. Thank you!
Veiculo [] v = new Veiculo [7];
Objeto [] o = new Objeto [10];
void setup() {
fullScreen();
for (int i =0; i < v.length; i ++) {
v[i] = new Veiculo (random(width), random(height));
}
for (int i = 0; i < o.length; i ++) {
o[i] = new Objeto(random(width), random(height));
}
}
void draw() {
background(0);
PVector mouse = new PVector (pmouseX, pmouseY);
for (int i = 0; i < v.length; i++) {
for (int j = 0; j < o.length; j++) {
o[j].display();
o[j].update();
o[j].chegada(mouse);
v[i].chegada(o[j]);
v[i].display();
v[i].update();
}
}
}
class Objeto {
ArrayList<PVector> hist;
PVector pos;
PVector dir;
PVector acc;
PVector vel;
int d;
float velM;
float forM;
Objeto (float x, float y) {
pos = new PVector(x, y);
vel = new PVector (random(-0.009, 0.009), random(-0.009, 0.009));
acc = new PVector (0, 0);
hist = new ArrayList<PVector>();
velM= 1.1;
forM =0.08;
d = 1;
}
void display() {
for (int i = 0; i < hist.size(); i++) {
PVector current = hist.get(i);
fill(220, i * 15);
noStroke();
ellipse(current.x, current.y, d+i, d+i);
}
}
void applyForce(PVector force) {
acc.add(force);
}
void chegada(PVector alvo) {
PVector desejo = PVector.sub(alvo, pos);
float t = desejo.mag();
if ( t < 100 ) {
float m = map(t, 0, 100, 0, velM);
desejo.setMag(m);
} else {
desejo.setMag(velM);
}
PVector steer = PVector.sub(desejo, vel);
steer.limit(velM);
applyForce(steer);
}
void update() {
vel.add(acc);
vel.limit(velM);
pos.add(vel);
acc.mult(0);
PVector v = new PVector (pos.x, pos.y);
hist.add(v);
if (hist.size() > 12) {
hist.remove(0);
}
}
}
class Veiculo {
PVector pos;
PVector acc;
PVector vel;
int d;
float velM;
float forM;
Veiculo(float x, float y) {
pos = new PVector (x, y);
vel = new PVector (random(-0.009, 0.009), random(-0.009, 0.009));
acc = new PVector (0, 0);
d = 8;
velM = 2.7;
forM = 0.08;
}
void display() {
float theta = vel.heading() + PI/2;
stroke(255);
fill(0);
pushMatrix();
translate(pos.x, pos.y);
rotate(theta);
beginShape();
vertex(-d, d);
vertex(0, -d);
vertex(d, d);
vertex (0, d*2);
endShape(CLOSE);
popMatrix();
}
void apllyForce(PVector force) {
acc.add(force);
}
void chegada (Objeto o) {
PVector desejo = PVector.sub(o.pos, pos);
float t = desejo.mag();
if ( t < 100 ) {
float m = map(t, 0, 100, 0, velM);
desejo.setMag(m);
} else {
desejo.setMag(velM);
}
PVector steer = PVector.sub(desejo, vel);
steer.limit(forM);
apllyForce(steer);
}
void update() {
vel.add(acc);
vel.limit(velM);
pos.add(vel);
acc.mult(0);
}
}