<!DOCTYPE html>
<html>
	<head>
		<title>Platformer</title>
		<style>
			body {background-color: #f1f1f1; margin: 0; padding: 0; font-family: sans-serif;}
			#canvas {background-color: #000; border: 1px solid #000;}
			#score {position: absolute; top: 0; left: 0; font-size: 10px; color: #fff;}
		</style>
	</head>
	<body>
		<div id='score'>Score: 0</div>
		<canvas id='canvas' width='500' height='500'></canvas>
		<script>
			//Canvas
			let canvas = document.getElementById('canvas');
			let ctx = canvas.getContext('2d');
			let scoreElem = document.getElementById('score');
			let score = 0;
<pre><code>		//Global variables
		let x = 0;
		let y = 0;
		let w = 50;
		let h = 50;
		let speed = 3;

		//Controls
		document.addEventListener('keydown', keyDownHandler, false);
		document.addEventListener('keyup', keyUpHandler, false);

		//Keydown functions
		function keyDownHandler(e) {
			if (e.keyCode == 39) {
				x += speed;
			} else if (e.keyCode == 37) {
				x -= speed;
			} else if (e.keyCode == 38) {
				y -= speed;
			} else if (e.keyCode == 40) {
				y += speed;
			}
		}

		//Keyup functions
		function keyUpHandler(e) {
			if (e.keyCode == 39) {
				x += 0;
			} else if (e.keyCode == 37) {
				x -= 0;
			} else if (e.keyCode == 38) {
				y -= 0;
			} else if (e.keyCode == 40) {
				y += 0;
			}
		}

		//Draw the player
		function drawPlayer() {
			ctx.beginPath();
			ctx.rect(x, y, w, h);
			ctx.fillStyle = '#33cc33';
			ctx.fill();
			ctx.closePath();
		}

		//Draw the platforms
		function drawPlatforms() {
			ctx.beginPath();
			ctx.rect(0, 300, 500, 10);
			ctx.rect(150, 200, 200, 10);
			ctx.fillStyle = '#fff';
			ctx.fill();
			ctx.closePath();
		}

		//Update position of player
		function update() {
			ctx.clearRect(0, 0, 500, 500);
			drawPlayer();
			drawPlatforms();
			scoreElem.innerHTML = 'Score: ' + score;
			requestAnimationFrame(update);
		}
		update();
	&lt;/script&gt;
&lt;/body&gt;
</code></pre>
</html>
HTML Platformer Game Code: Simple 2D Movement

原文地址: https://www.cveoy.top/t/topic/lnRh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录