HTML Platformer Game: Create Your Own Jumping Adventure
<html>
<head>
<title>Platformer Game</title>
<style>
canvas {
background-color: #00FF00;
}
</style>
</head>
<body>
<h1>Platformer Game</h1>
<canvas id='game' width='500px' height='500px'></canvas>
<script>
// Get canvas element
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
<pre><code> // Setup game state
var game = {
width: canvas.width,
height: canvas.height,
player: {
x: 10,
y: 10,
width: 10,
height: 10,
speed: 5
},
ground: [
{x: 0, y: 400, width: 500},
{x: 300, y: 350, width: 200},
{x: 100, y: 300, width: 50}
],
keys: {
left: false,
right: false
}
};
// Setup key press listeners
window.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
game.keys.left = true;
break;
case 39:
game.keys.right = true;
break;
}
};
window.onkeyup = function(e) {
switch (e.keyCode) {
case 37:
game.keys.left = false;
break;
case 39:
game.keys.right = false;
break;
}
};
// Render the game
function render() {
context.clearRect(0, 0, game.width, game.height);
// Render the ground
for (var i = 0; i < game.ground.length; i++) {
context.fillStyle = '#333';
context.fillRect(game.ground[i].x, game.ground[i].y, game.ground[i].width, 10);
}
// Render the player
context.fillStyle = '#FF0000';
context.fillRect(game.player.x, game.player.y, game.player.width, game.player.height);
}
// Update the game
function update() {
// Move the player
if (game.keys.left) {
game.player.x -= game.player.speed;
}
if (game.keys.right) {
game.player.x += game.player.speed;
}
// Check for collision with ground
for (var i = 0; i < game.ground.length; i++) {
if (game.player.x + game.player.width > game.ground[i].x &&
game.player.x < game.ground[i].x + game.ground[i].width &&
game.player.y + game.player.height > game.ground[i].y) {
game.player.y = game.ground[i].y - game.player.height;
}
}
}
// Game loop
function loop() {
update();
render();
window.requestAnimationFrame(loop);
}
window.requestAnimationFrame(loop);
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnR4 著作权归作者所有。请勿转载和采集!