class Car{
 
float x,y;
float dx = 6;
float dx2 = 0;
float trailing = 25;
float maxVel = 6.5;
float maxAccel = .15;
 
boolean distracted = false;
 
public Car(){
y = height/2 + 3 + random(-1,1);
x = -20;
}
 
void draw(Car next){
stroke(0);
maxAccel = carPower.val/100.f;
 
if (distracted) fill(255,0,0);
else fill(220,220,250);
rect(x,y,10,7);
 
if (next != null){
float P = next.x - trailing - x;
float D = next.dx - dx;
dx2 = P/7 + D/8;
 
}
 
if (dx2 > maxAccel) dx2 = maxAccel;
 
dx += dx2;
if (dx > maxVel) dx = maxVel;
if (distracted){
dx -= 2;
 
}
if (dx < 0) dx = 0;
x += dx;
 
}
}
 
 
import SGQuickVar.*;
Vector traffic;
Car staller = null;
PFont font;
 
float incidentLoc = 0;
 
SGVariable carPower,trafficRate;
 
void setup(){
size(550, 200);
font = loadFont("writing.vlw");
textFont(font);
 
frameRate(30);
traffic = new Vector();
traffic.add(new Car());
carPower = new SGVariable(this,font,"Max Accel",'a','z',15,5,0,100);
trafficRate = new SGVariable(this,font,"Traffic",'s','x',15,2,0,30);
}
 
void draw(){
background(100,200,100);
int mid = height/2;
noStroke();
 
fill(100,100,100);
rect(0,mid-20,width,40);
fill(255);
rect(0,mid-13,width,26);
fill(80,80,80);
rect(0,mid-12,width,24);
fill(255);
for (int i =0; i*7 < width; i++){
rect(i*7,mid-1,4 ,2);
}
if (random(0,1) < trafficRate.val/100.f){
if (((Car)traffic.elementAt(traffic.size()-1)).x > 0){
traffic.add(new Car());
}
}
Car curr = (Car)traffic.elementAt(0);
curr.draw(null);
for (int i = 1; i < traffic.size(); i++){
curr = (Car)traffic.elementAt(i);
curr.draw((Car)traffic.elementAt(i-1));
}
for (int i = 0; i < traffic.size(); i++){
curr = (Car)traffic.elementAt(i);
if (curr.x > width + 50) traffic.remove(i);
}
if (incidentLoc !=0 ){
noStroke();
fill(255,255,255,100);
rect(incidentLoc, mid-20,20,40);
}
 
}
 
void mousePressed(){
if (staller == null && traffic.size() > 4){
staller = (Car)traffic.elementAt(3);
staller.distracted = true;
incidentLoc = staller.x;
}
}
 
void mouseReleased(){
if (staller.distracted != false){
staller.distracted = false;
staller = null;
}
}