Skip to main content
3 of 3
converted url to linked text; removed comments from code to make more minimal

Creating terrain

I am working on creating a 2D side-scrolling car game. My problem is generating the terrain. When creating the terrain, I need to have it random and recorded, so I can create collisions at a later point. I can't use any external assets.

var keys = [];

var keyPressed = function() {
    keys[keyCode] = true;
};

var keyReleased = function() {
    keys[keyCode] = false;
};

var car = function(locatio, accel, image, dragcoof) {
    this.loc = locatio;
    this.accel = accel;
    this.image = image;
    this.volocity = new PVector(0, 0);
    this.acceleration = new PVector(0, 0);
    this.drag = new PVector(0, 0);
    this.dragcoof = new PVector(dragcoof.x, dragcoof.y);
};

car.prototype.draw = function() {
    if (this.image === null) {
        fill(255, 0, 0);
        rect(this.loc.x, this.loc.y, 50, 10);
    } 
    else {
        this.image(this.loc.x, this.loc.y);
    }
};

car.prototype.update = function() {
    if (this.volocity.x >= 10) {
        this.volocity.x = 9.99;
    }

    if (this.volocity.x <= 0.1) {
        this.volocity.x = 0;
    }

    this.volocity.add(this.acceleration);
    this.loc.add(this.volocity);
    this.drag = PVector.mult(this.volocity, this.dragcoof);
    this.volocity.sub(this.drag);

    if (this.loc.x >= 600) {
        this.loc.x = 0;
    }
};

car.prototype.move = function(keycodeLeft, keycodeRight) {
    if (keys[RIGHT] && this.volocity.x < 10) {
        this.acceleration.add(this.accel.x,0);
    }

    if (!keys[RIGHT] && !keys[LEFT]) {
        this.acceleration.set(0, 0);
    }

    if (keys[LEFT] && this.volocity.x >= 0.5) {
        this.acceleration.set(-0.1, 0);
    }
};

var a = new car(new PVector(10, 200), new PVector(0.01,0), null, new PVector(0.022, 0));

var draw = function() {
    background(255, 255, 255);
    a.draw();
    a.update();
    a.move();
    text(a.acceleration + "\n" + a.volocity+"\n"+a.drag, 25, 25);
};