xxxxxxxxxx
95
let myCars = [];
let myCar;
function setup() {
createCanvas(400, 400);
//setup the car
rectMode(CENTER);
for( let i=0; i<4; i++){
// lanes
let y = height * 0.2;
if (i % 2 == 0) {
y = height *.4;
}
if (i % 3 == 0) {
y = height *.60;
}
if (i % 4 == 0) {
y = height *.80;
}
myCars.push(new Car(0, y, color (random(0,255), random(0,255), random(0,255))));
}
myCar= new Car(0, 200, color(255,0,0));
}
function draw() {
background(255);
myCar.run();
for( let i = 0 ; i < myCars.length; i++){
myCars[i].run();
}
}
class Car {
constructor(x, y, c) {
this.posX = x ;
this.posY = y ;
this.carWidth = 100;
this.carHeight = this.carWidth/2.5;
this.carColor = c;
this.wheelWidth = this.carWidth * .2;
this.wheelHeight = this.wheelWidth/2.5;
this.speed = random (5,7);
}
run(){
this.drawCar();
this.updateCar();
}
drawCar() {
//car body
fill(this.carColor);
noStroke();
rect(this.posX, this.posY, this.carWidth, this.carHeight);
fill(0);
//left top wheel
rect(this.posX-this.carWidth/2 + this.wheelWidth/2, this.posY - this.carHeight/2-this.wheelHeight/2, this.wheelWidth, this.wheelHeight);
//right top wheel
rect(this.posX+this.carWidth/2 - this.wheelWidth/2, this.posY - this.carHeight/2-this.wheelHeight/2, this.wheelWidth, this.wheelHeight);
//left bottom wheel
rect(this.posX-this.carWidth/2 + this.wheelWidth/2, this.posY + this.carHeight/2+this.wheelHeight/2, this.wheelWidth, this.wheelHeight);
//right bottom wheel
rect(this.posX+this.carWidth/2 - this.wheelWidth/2, this.posY + this.carHeight/2+this.wheelHeight/2, this.wheelWidth, this.wheelHeight);
}
updateCar() {
//drive the car
this.posX += this.speed;
if (this.posX > width + this.carWidth/2) {
this.posX = -this.carWidth/2;
}
if (this.posY = height * .5 ) {
this.posY = mouseY;
}
}
}