Build a Simple HTML Platformer Game - Beginner's Guide
<!DOCTYPE html>
<html>
<head>
<title>Simple HTML Platformer</title>
<style>
body {
margin: 0;
padding: 0;
}
#game {
position: relative;
width: 800px;
height: 600px;
background-color: #aaa;
}
#player {
position: absolute;
width: 20px;
height: 20px;
background-color: #000;
}
</style>
<script>
function movePlayer(e) {
var player = document.getElementById("player");
var game = document.getElementById("game");
<pre><code> switch(e.keyCode) {
case 37: // left
if (player.offsetLeft > 0) {
player.style.left = player.offsetLeft - 10 + 'px';
}
break;
case 39: // right
if (player.offsetLeft + player.offsetWidth < game.offsetWidth) {
player.style.left = player.offsetLeft + 10 + 'px';
}
break;
case 38: // up
if (player.offsetTop > 0) {
player.style.top = player.offsetTop - 10 + 'px';
}
break;
case 40: // down
if (player.offsetTop + player.offsetHeight < game.offsetHeight) {
player.style.top = player.offsetTop + 10 + 'px';
}
break;
}
}
</script>
</code></pre>
</head>
<body>
<div id="game">
<div id="player"></div>
</div>
<script>
document.addEventListener('keydown', movePlayer);
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmmE 著作权归作者所有。请勿转载和采集!