<!DOCTYPE html>
<html>
<head>
    <title>Simple HTML5 Platformer Game</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }
        canvas {
            background-color: #EEE;
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <canvas id='game'></canvas>
    <script>
        var canvas = document.getElementById('game');
        var ctx = canvas.getContext('2d');
<pre><code>    // Global Variables
    var x = canvas.width/2;
    var y = canvas.height-30;
    var dx = 5;
    var dy = -5;
    var ballRadius = 10;

    // Draw Ball
    function drawBall() {
        ctx.beginPath();
        ctx.arc(x, y, ballRadius, 0, Math.PI*2);
        ctx.fillStyle = '#0095DD';
        ctx.fill();
        ctx.closePath();
    }

    // Draw Platform
    function drawPlatform() {
        ctx.beginPath();
        ctx.rect(0, canvas.height-20, canvas.width, 20);
        ctx.fillStyle = '#0095DD';
        ctx.fill();
        ctx.closePath();
    }

    // Draw
    function draw() {
        // Clear Canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // Draw Ball and Platform
        drawBall();
        drawPlatform();

        // Move Ball
        x += dx;
        y += dy;

        // Bounce Ball off Walls
        if(x + dx &gt; canvas.width-ballRadius || x + dx &lt; ballRadius) {
            dx = -dx;
        }
        if(y + dy &gt; canvas.height-ballRadius || y + dy &lt; ballRadius) {
            dy = -dy;
        }

        // Bounce Ball off Platform
        if(y + dy &gt; canvas.height-ballRadius-20 &amp;&amp; x &gt; 0 &amp;&amp; x &lt; canvas.width) {
            dy = -dy;
        }

        // Request next animation frame
        requestAnimationFrame(draw);
    }

    requestAnimationFrame(draw);
&lt;/script&gt;
</code></pre>
</body>
</html>
Simple HTML5 Platformer Game - Code Example

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

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