Platformer Game Example
class GameObject {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
// Method to check if this object is colliding with another object
isCollidingWith(otherObject) {
return (
this.x < otherObject.x + otherObject.width &&
this.x + this.width > otherObject.x &&
this.y < otherObject.y + otherObject.height &&
this.y + this.height > otherObject.y
);
}
}
class Player extends GameObject {
constructor(x, y, width, height, speed) {
super(x, y, width, height);
this.speed = speed;
}
moveLeft() {
this.x -= this.speed;
}
moveRight() {
this.x += this.speed;
}
jump() {
this.y -= this.speed * 2;
}
}
class Platform extends GameObject {
constructor(x, y, width, height) {
super(x, y, width, height);
}
}
const player = new Player(100, 100, 50, 50, 5);
const platform = new Platform(200, 150, 100, 10);
// Check if the player is colliding with the platform
console.log(player.isCollidingWith(platform)); // true
// Move the player to the left
player.moveLeft();
// Check if the player is colliding with the platform
console.log(player.isCollidingWith(platform)); // false
// Jump the player
player.jump();
// Check if the player is colliding with the platform
console.log(player.isCollidingWith(platform)); // falseLast updated