Run away from Diddy
runaway gameunknown
javascript
a month ago
2.9 kB
4
Indexable
// 2D Runner Game in JavaScript
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 900;
canvas.height = 400;
document.body.appendChild(canvas);
document.body.style.margin = "0";
document.body.style.overflow = "hidden";
// GAME VARIABLES
let gravity = 0.7;
let gameSpeed = 6;
let score = 0;
let gameOver = false;
// PLAYER
const player = {
x: 150,
y: 300,
width: 40,
height: 60,
velocityY: 0,
jumping: false,
draw() {
ctx.fillStyle = "blue";
ctx.fillRect(this.x, this.y, this.width, this.height);
},
update() {
this.velocityY += gravity;
this.y += this.velocityY;
// Ground collision
if (this.y >= 300) {
this.y = 300;
this.velocityY = 0;
this.jumping = false;
}
this.draw();
},
jump() {
if (!this.jumping) {
this.velocityY = -14;
this.jumping = true;
}
}
};
// CHASER
const chaser = {
x: 50,
y: 300,
width: 40,
height: 60,
draw() {
ctx.fillStyle = "black";
ctx.fillRect(this.x, this.y, this.width, this.height);
},
update() {
this.x += 0.25;
this.draw();
}
};
// OBSTACLES
let obstacles = [];
function createObstacle() {
const height = Math.random() * 40 + 30;
obstacles.push({
x: canvas.width,
y: 360 - height,
width: 30,
height: height
});
}
function drawObstacles() {
ctx.fillStyle = "green";
obstacles.forEach((obs, index) => {
obs.x -= gameSpeed;
ctx.fillRect(obs.x, obs.y, obs.width, obs.height);
// Collision detection
if (
player.x < obs.x + obs.width &&
player.x + player.width > obs.x &&
player.y < obs.y + obs.height &&
player.y + player.height > obs.y
) {
gameOver = true;
}
// Remove obstacle
if (obs.x + obs.width < 0) {
obstacles.splice(index, 1);
score++;
}
});
}
// GROUND
function drawGround() {
ctx.fillStyle = "#654321";
ctx.fillRect(0, 360, canvas.width, 40);
}
// SCORE
function drawScore() {
ctx.fillStyle = "black";
ctx.font = "24px Arial";
ctx.fillText("Score: " + score, 20, 40);
}
// GAME OVER
function drawGameOver() {
ctx.fillStyle = "red";
ctx.font = "50px Arial";
ctx.fillText("GAME OVER", 280, 180);
ctx.font = "30px Arial";
ctx.fillText("Refresh to Restart", 300, 240);
}
// MAIN GAME LOOP
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGround();
player.update();
chaser.update();
drawObstacles();
drawScore();
// Chaser catches player
if (chaser.x + chaser.width >= player.x) {
gameOver = true;
}
if (!gameOver) {
requestAnimationFrame(animate);
} else {
drawGameOver();
}
}
// CREATE OBSTACLES
setInterval(() => {
if (!gameOver) {
createObstacle();
}
}, 1500);
// CONTROLS
document.addEventListener("keydown", (e) => {
if (e.code === "Space") {
player.jump();
}
});
// START GAME
animate();Editor is loading...
Leave a Comment