Having real trouble figuring out how to apply acceleration and friction to my boid. I would be using traer.physics but I want to be able to transfer this into Flash (easier to do the science here).
How can I drive my boid like a go cart? (w, a, s, d)
Code:
Boid boid = new Boid(50, 50);
int timer = 0;
void setup(){
size(400, 400);
smooth();
frameRate(24);
boid.f = 0.1;
background(250);
}
void draw(){
boid.tick();
if(mousePressed){
boid.heading(mouseX, mouseY, 5.0);
println(boid.xV + " " + boid.yV);
}
if(keyPressed){
switch(key){
case 'a':
boid.turn(-0.1);
break;
case 'd':
boid.turn(0.1);
break;
case 'w':
boid.accelerate(0.5);
break;
}
}
boid.draw();
}
class Boid{
float x, y, xV, yV, xA, yA, t, s, f;
Boid(float x, float y){
this.x = x;
this.y = y;
xV = 0.0f; // x velocity
yV = 0.0f; // y velocity
xA = 0.0f; // x acceleration
yA = 0.0f; // y acceleration
t = random(TWO_PI); // theta - angle of rotation
s = 0.0f; // speed
f = 0.0f; // friction
}
void tick(){
xV += xA;
yV += yA;
x += xV;
y += yV;
if(xV != 0.0f) xV += xV > 0.0f ? -f : f;
if(yV != 0.0f) yV += yV > 0.0f ? -f : f;
}
void setV(float x, float y){
xV = x;
yV = y;
}
void turn(float r){
t += r;
if(s != 0.0){
xV = cos(t) * s;
yV = sin(t) * s;
}
}
void accelerate(float a){
xA = cos(t) * a;
yA = sin(t) * a;
}
void heading(float x, float y, float speed){
float xD = x - this.x;
float yD = y - this.y;
float vL = sqrt((xD * xD) + (yD * yD));
s = speed;
xV = (xD / vL) * s;
yV = (yD / vL) * s;
t = theta(x, y);
}
void draw(){
ellipse(x, y, 20, 20);
float xt = x + cos(t) * 30;
float yt = y + sin(t) * 30;
line(x, y, xt, yt);
}
float theta(float x, float y){
return atan2(y - this.y, x - this.x);
}
}