Build Your Own Platformer Game with HTML, CSS & JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Platformer Game</title>
<style>
* {
box-sizing: border-box;
}
html, body {
height: 100%;
margin: 0;
}
#game {
width: 800px;
height: 600px;
background-color: #aaa;
position: relative;
}
#player {
width: 32px;
height: 32px;
background-color: #f00;
position: absolute;
left: 50px;
top: 500px;
}
</style>
</head>
<body>
<div id='game'>
<div id='player'></div>
</div>
<script>
const game = document.getElementById('game');
const player = document.getElementById('player');
<pre><code> // player movement
document.onkeydown = (e) => {
if(e.keyCode === 37) {
// left arrow
player.style.left = (player.offsetLeft - 10) + 'px';
} else if(e.keyCode === 38) {
// up arrow
player.style.top = (player.offsetTop - 10) + 'px';
} else if(e.keyCode === 39) {
// right arrow
player.style.left = (player.offsetLeft + 10) + 'px';
} else if(e.keyCode === 40) {
// down arrow
player.style.top = (player.offsetTop + 10) + 'px';
}
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnRG 著作权归作者所有。请勿转载和采集!