HTML Platformer Game Tutorial: Create a Simple Platformer Game
<!DOCTYPE html>
<html>
<head>
<title>Platformer Game</title>
<style>
body {
background-color: #000;
font-family: sans-serif;
}
canvas {
border: 1px solid #ccc;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas width='400' height='400'></canvas>
<script>
// Get canvas element
let canvas = document.querySelector('canvas');
<pre><code>// Get canvas context
let ctx = canvas.getContext('2d');
// Set the game map
let gameMap = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 2, 2, 2, 2, 2, 2, 2, 0],
[0, 2, 1, 0, 0, 0, 0, 1, 2, 0],
[0, 2, 0, 0, 0, 0, 0, 0, 2, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 2, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 2, 0],
[0, 2, 0, 0, 0, 0, 0, 0, 2, 0],
[0, 2, 1, 0, 0, 0, 0, 1, 2, 0],
[0, 2, 2, 2, 2, 2, 2, 2, 2, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
// Set game constants
let TILE_SIZE = 40;
let MAP_NUM_ROWS = 10;
let MAP_NUM_COLS = 10;
// Set game variables
let playerX;
let playerY;
// Set game objects
let player = {
x: 0,
y: 0,
width: TILE_SIZE,
height: TILE_SIZE,
color: '#ff0000'
};
// Set game functions
function drawGame() {
// Clear canvas
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw game map
for(let row = 0; row < MAP_NUM_ROWS; row++) {
for(let col = 0; col < MAP_NUM_COLS; col++) {
let tile = gameMap[row][col];
// Set fill style
if(tile === 0) {
// Empty space
ctx.fillStyle = '#000';
} else if (tile === 1) {
// Wall
ctx.fillStyle = '#999';
} else if (tile === 2) {
// Floor
ctx.fillStyle = '#444';
}
// Draw tile
ctx.fillRect(col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
// Draw player
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}
// Set game event listeners
document.onkeydown = function(e) {
// Handle key presses
switch(e.keyCode) {
case 37: // Left
if(player.x > 0) {
player.x -= TILE_SIZE;
}
break;
case 38: // Up
if(player.y > 0) {
player.y -= TILE_SIZE;
}
break;
case 39: // Right
if(player.x < MAP_NUM_COLS * TILE_SIZE - player.width) {
player.x += TILE_SIZE;
}
break;
case 40: // Down
if(player.y < MAP_NUM_ROWS * TILE_SIZE - player.height) {
player.y += TILE_SIZE;
}
break;
}
}
// Initialize game
function init() {
// Put player in the middle of the map
player.x = MAP_NUM_COLS/2 * TILE_SIZE;
player.y = MAP_NUM_ROWS/2 * TILE_SIZE;
// Start game loop
loop();
}
// Main game loop
function loop() {
drawGame();
// Call game loop
requestAnimationFrame(loop);
}
// Start game
init();
</code></pre>
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnQ9 著作权归作者所有。请勿转载和采集!