xxxxxxxxxx
62
let cars = [];
function setup() {
createCanvas(400, 400);
// 15.. because we want to have 15 cars
for (let i=0; i < 15; i++) {
// pick a random color and put it into a single value
let randomColor = color(random(255), random(255), random(255));
// create a new car instance
// and store it in the array
cars[i] = new Car(random(width), 200, 40, randomColor);
}
}
function draw() {
background(220);
for (let i=0; i < cars.length; i++) {
cars[i].move();
cars[i].display();
}
}
// "Blueprint" (cookie cutter) for a car
class Car {
constructor(startX, startY, wheelSize, carColor) {
this.x = startX;
this.y = startY;
this.wheelSize = wheelSize;
this.color = carColor;
this.speed = random(0, 2);
console.log('Creating a new car at ' + startX + ', ' + startY);
}
move() {
if (this.x > width || this.x < 0) {
this.speed = this.speed * -1;
}
this.x = this.x + this.speed;
}
display() {
push();
translate(this.x, this.y);
// body
fill(this.color);
noStroke();
rect(-75, -25, 150, 50);
rect(-55, -55, 100, 50);
// wheels
fill(255);
ellipse(-35, 25, this.wheelSize, this.wheelSize);
ellipse(35, 25, this.wheelSize, this.wheelSize);
pop();
}
}