const createPlayer = (x, y) => ({
x,
y,
width: 32,
height: 32,
velocityX: 0,
velocityY: 0,
speed: 300,
jumping: false
});
const updatePlayer = (player, deltaTime) => {
const keys = getKeys();
const seconds = deltaTime / 1000;
let velocityX = 0;
let velocityY = player.velocityY;
// Horizontal movement
if (keys.ArrowLeft) velocityX -= player.speed;
if (keys.ArrowRight) velocityX += player.speed;
// Simple jumping (can be improved)
if (keys.ArrowUp && !player.jumping) {
velocityY = -500;
}
// Apply gravity
velocityY += 980 * seconds; // 980 pixels/second²
// Update position
const x = player.x + velocityX * seconds;
const y = player.y + velocityY * seconds;
// Create updated player state
let updatedPlayer = {
...player,
x,
y,
velocityX,
velocityY
};
// Handle collisions with the world
return handleWorldCollisions(updatedPlayer, window.gameState.world);
};
const renderPlayer = (ctx, player) => {
ctx.fillStyle = '#f00';
ctx.fillRect(player.x, player.y, player.width, player.height);
};
// Key handling
const keys = {};
window.addEventListener('keydown', (e) => {
keys[e.key] = true;
});
window.addEventListener('keyup', (e) => {
keys[e.key] = false;
});
const getKeys = () => ({...keys});