xxxxxxxxxx
163
let character;
let platforms = [];
let platformSpeed = 1;
let score = 0;
let gameOver = false;
let right;
let left;
let charsize = 25;
class Character {
constructor(x, y) { //initializes the variables
this.x = x;
this.y = y;
this.velocity = 0; //the vertical movement of the character
this.gravity = 0.5; //the speed at which it falls
this.jump = -10; //the speed at which it jumps
this.speed = 5; //horizontal movement of character
}
display() {
fill(0);
ellipse(this.x, this.y, charsize);
}
jumpCharacter() {
this.velocity = this.jump;
}
moveleft(){
this.x -= this.speed;
if (this.x < 0) {
this.x = 0;
}
}
moveright(){
this.x+=this.speed;
if (this.x > width) {
this.x = width;
}
}
moveCharacter(direction) {
if (direction === "left") {
this.x -= this.speed;
} else if (direction === "right") {
this.x += this.speed;
}
}
update() {
this.velocity += this.gravity;
this.y += this.velocity;
if (this.x < 0) {
this.x = 0;
} else if (this.x > width) {
this.x = width;
}
if (this.y > height - charsize/2) {
this.y = height - charsize/2;
this.velocity = 0;
}
}
hits(platform) {
return (this.y + charsize/2 > platform.y && this.y + charsize/2 < platform.y + platform.height &&
this.x > platform.x && this.x < platform.x + platform.width);
}
}
class Platform {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
display() {
noStroke();
fill(255);
rect(this.x, this.y, this.width, this.height);
}
update() {
this.y -= platformSpeed;
}
}
function setup() {
createCanvas(350, 500);
character = new Character(width/2, height/2, charsize);
platforms.push(new Platform(random(0, width-50), height, 100, 10));
}
function draw() {
background(230);
if (!gameOver) {
for(let y = 0 ; y<platforms.length ;y++){
if (character.hits(platforms[y])) {
console.log("hit", y);
character.jumpCharacter();
score += 1;
}
}
if(keyIsDown(LEFT_ARROW)){
character.moveleft();
}
else if (keyIsDown(RIGHT_ARROW)){
character.moveright();
}
character.display();
character.update();
for (let i = platforms.length - 1; i >= 0; i--) {
platforms[i].display();
platforms[i].update();
if (character.hits(platforms[i])) {
//console.log("hit", i);
character.jumpCharacter();
score += 1;
}
if (platforms[i].y <= 0) {
platforms.splice(i, 1);
}
}
if (frameCount % 60 == 0) {
platforms.push(new Platform(random(0, width-50), height, 100, 10));
}
if (character.y > height) {
gameOver = true;
}
platformSpeed += 0.0001;
textSize(32);
text("Score: " + score, 10, 30);
} else {
textSize(32);
text("Game Over! Final Score: " + score, width/2 - 160, height/2);
}
}