<!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 &gt; 0) {
                    player.style.left = player.offsetLeft - 10 + 'px';
                }
                break;
            case 39: // right
                if (player.offsetLeft + player.offsetWidth &lt; game.offsetWidth) {
                    player.style.left = player.offsetLeft + 10 + 'px';
                }
                break;
            case 38: // up
                if (player.offsetTop &gt; 0) {
                    player.style.top = player.offsetTop - 10 + 'px';
                }
                break;
            case 40: // down
                if (player.offsetTop + player.offsetHeight &lt; game.offsetHeight) {
                    player.style.top = player.offsetTop + 10 + 'px';
                }
                break;
        }
    }
&lt;/script&gt;
</code></pre>
</head>
<body>
    <div id="game">
        <div id="player"></div>
    </div>
    <script>
        document.addEventListener('keydown', movePlayer);
    </script>
</body>
</html>
Build a Simple HTML Platformer Game - Beginner's Guide

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

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