<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Platformer</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #87CEEB;
}
canvas {
display: block;
margin: auto;
background-color: #fff;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const PLAYER_SIZE = 20;
const PLATFORM_WIDTH = 100;
const PLATFORM_HEIGHT = 20;
const GRAVITY = 0.5;
const JUMP_FORCE = -10;
const PLAYER_SPEED = 3;
let player = {
x: 50,
y: 50,
vx: 0,
vy: 0,
grounded: false,
width: PLAYER_SIZE,
height: PLAYER_SIZE,
jumping: false
};
let platforms = [
{ x: 100, y: 500, width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT },
{ x: 300, y: 400, width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT },
{ x: 500, y: 300, width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT },
{ x: 0, y: 580, width: 800, height: 20 } // Platform for the player to land on
];
function drawPlayer() {
ctx.fillStyle = '#FF0000';
ctx.fillRect(player.x, player.y, player.width, player.height);
}
function drawPlatforms() {
ctx.fillStyle = '#000000';
platforms.forEach(platform => {
ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
});
}
function applyGravity() {
if (!player.grounded) {
player.vy += GRAVITY;
}
}
function applyVelocity() {
player.x += player.vx;
player.y += player.vy;
}
function checkCollisions() {
platforms.forEach(platform => {
if (
player.x + player.width > platform.x &&
player.x < platform.x + platform.width &&
player.y + player.height >= platform.y && // Change here
player.y < platform.y + platform.height
) {
player.vy = 0;
player.y = platform.y - player.height;
player.grounded = true;
}
});
// Check if player falls off the platform
if (player.y + player.height >= canvas.height) {
player.grounded = false;
}
}
function handleInput() {
if (keys['a']) {
player.vx = -PLAYER_SPEED;
} else if (keys['d']) {
player.vx = PLAYER_SPEED;
} else {
player.vx = 0;
}
if (keys['w'] && player.grounded) {
player.vy = JUMP_FORCE;
player.grounded = false;
}
}
let keys = {};
document.addEventListener('keydown', e => {
keys[e.key] = true;
});
document.addEventListener('keyup', e => {
keys[e.key] = false;
});
function update() {
applyGravity();
applyVelocity();
checkCollisions();
handleInput();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
drawPlatforms();
requestAnimationFrame(draw);
}
function gameLoop() {
update();
draw();
}
setInterval(gameLoop, 1000 / 60);
</script>
</body>
</html>
1
1
1KB
4KB
133.0ms
172.0ms
133.0ms