xxxxxxxxxx
132
let myCars = [];
let myCar;
var img;
function preload () {
img = loadImage("trees.png");
}
function setup() {
img.resize(836,811);
createCanvas(800, 1000);
//setup the car
rectMode(CENTER);
for( let i=0; i<4; i++){
let x = width * 0.3125;
if (i % 2 == 0) {
x = width * 0.4375;
}
if (i % 3 == 0) {
x = width * 0.5625;
}
if (i % 4 == 0) {
x = width * 0.6875;
}
myCars.push(new Car(x, 1000 , color(random(0,255), random(0,255), random(0,255))));
}
myCar= new Car(250, 1000, color(255));
}
function draw() {
image(img, 0, 0, width, height);
//road
fill(100)
rect(400,0, 400, 2000)
//lanes
strokeWeight (3)
stroke(255);
line( 200, 0, 200, 1000)
line( 300, 0, 300, 1000)
line( 400, 0, 400, 1000)
line( 500, 0, 500, 1000)
line( 600, 0, 600, 1000)
myCar.running();
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 = 50;
this.carHeight = this.carWidth *2 ;
this.carColor = c;
this.wheelWidth = this.carWidth * 0.2;
this.wheelHeight = this.wheelWidth/2.5;
this.speed = random (5,7);
// car roof, make more 3D looking
// this.posA = x + 15 ;
// this.posB = y +15 ;
// this.carA = 20;
// this.carB = this.carA *2 ;
}
running(){
this.drawCar();
this.updatingCar();
}
run(){
this.drawCar();
this.updateCar();
}
drawCar() {
//car body
fill(this.carColor);
noStroke();
rect(this.posX, this.posY, this.carWidth, this.carHeight);
// fill(0);
// rect(this.posA, this.posB, this.carA, this.carB);
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.posY -= this.speed;
if (this.posY < -this.carHeight/2 ) {
this.posY = height + this.carHeight/2 ;
this.speed = random (5,9);
this.carColor= color(random(0,255), random(0,255), random(0,255))
}
}
updatingCar() {
//drive the car
this.posY -= this.speed;
this.speed = 3;
this.posX = mouseX;
if (this.posY < -this.carHeight/2 ) {
this.posY = height + this.carHeight/2 ;
}
}
}