xxxxxxxxxx
/**
* Cars Saying Hello! (v2.2.1) [Java/Pjs]
* by LightPost101 (2013/Nov)
* mod GoToLoop
*
* Forum.Processing.org/two/discussion/1250/
* how-to-draw-an-orange-line-between-cars-
* when-they-are-4-pixels-horizontally-of-each-other#Item_1
*/
final Car car1 = new Car(#FF0000, 150, 30, 3);
final Car car2 = new Car(#00A0FF, 0, 120, 1.5);
void setup() {
size(400, 150);
rectMode(CENTER);
strokeWeight(1.5);
}
void draw() {
background(0300);
stroke(0);
car1.drive();
car1.display();
car2.drive();
car2.display();
if (car1.checkHozNear(car2)) car1.drawContactLine(car2);
}
final class Car {
static final short W = 20, H = 10, D = 8;
static final color LINE_C = #FFA500;
color c;
float x, y;
final float spd, slow;
boolean isNear;
Car(final color cc, final float xx, final float yy, final float ss) {
c = cc;
x = xx;
y = yy;
spd = ss;
slow = ss/3;
}
void drive() {
if ((x += isNear? slow : spd) > width + W) x = -W;
}
void display() {
fill(c);
rect(x, y, W, H);
}
boolean checkHozNear(final Car other) {
return other.isNear = isNear =
x > other.x - W - D & x < other.x + W + D;
}
void drawContactLine(final Car other) {
stroke(LINE_C);
line(x, y, other.x, other.y);
}
}