1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
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});
|