HTML Platformer Game Code: Build Your Own 2D Jump'n'Run
<!DOCTYPE html>
<html>
<head>
<title>My Platformer</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #f0f0f0;
}
#canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// set up the canvas
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
<pre><code> // game variables
var playerX = width / 2;
var playerY = height / 2;
var playerWidth = 10;
var playerHeight = 10;
var gravity = 0.2;
var velocityY = 0;
var jumpForce = 4;
var leftPressed = false;
var rightPressed = false;
var blocks = [
{
x: width/2,
y: height/2,
width: 20,
height: 20
},
{
x: width/3,
y: height/3,
width: 20,
height: 20
},
{
x: width/1.5,
y: height/1.5,
width: 20,
height: 20
}
];
// game loop
function loop() {
context.fillStyle = 'white';
context.fillRect(0, 0, width, height);
// player movement
if (leftPressed) {
playerX -= 5;
}
if (rightPressed) {
playerX += 5;
}
// player gravity
velocityY += gravity;
playerY += velocityY;
// block collision
var block;
for (var i = 0; i < blocks.length; i++) {
block = blocks[i];
if (playerX + playerWidth > block.x &&
playerX < block.x + block.width &&
playerY + playerHeight > block.y &&
playerY < block.y + block.height) {
velocityY = -jumpForce;
}
}
// draw blocks
context.fillStyle = 'black';
for (var i = 0; i < blocks.length; i++) {
block = blocks[i];
context.fillRect(block.x, block.y, block.width, block.height);
}
// draw player
context.fillStyle = 'red';
context.fillRect(playerX, playerY, playerWidth, playerHeight);
// loop
requestAnimationFrame(loop);
}
loop();
// keyboard input
document.addEventListener('keydown', function(event) {
if (event.keyCode == 37) {
leftPressed = true;
}
if (event.keyCode == 39) {
rightPressed = true;
}
if (event.keyCode == 32) {
velocityY = -jumpForce;
}
});
document.addEventListener('keyup', function(event) {
if (event.keyCode == 37) {
leftPressed = false;
}
if (event.keyCode == 39) {
rightPressed = false;
}
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnRx 著作权归作者所有。请勿转载和采集!