Untitled

 avatar
unknown
javascript
2 years ago
2.1 kB
5
Indexable
<!DOCTYPE html>
<html>
<head>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400"></canvas>

    <script>
        const canvas = document.getElementById('myCanvas');
        const ctx = canvas.getContext('2d');

        // Game state
        let gameObjects = [];

        // Game loop variables
        let lastTime = 0;
        let deltaTime = 0;

        function update(deltaTime) {
            // Update game logic, physics, etc. based on the deltaTime
            gameObjects.forEach(gameObject => {
                // Example: Move the game object
                gameObject.x += gameObject.velocityX * deltaTime;
                gameObject.y += gameObject.velocityY * deltaTime;
            });
        }

        function render() {
            // Clear canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // Render game objects
            gameObjects.forEach(gameObject => {
                // Example: Draw a rectangle for each game object
                ctx.fillRect(gameObject.x, gameObject.y, gameObject.width, gameObject.height);
            });
        }

        function gameLoop(timestamp) {
            // Calculate deltaTime
            deltaTime = (timestamp - lastTime) / 1000; // Convert to seconds

            // Update game logic
            update(deltaTime);

            // Render game objects
            render();

            // Store current timestamp as lastTime for the next frame
            lastTime = timestamp;

            // Request the next frame
            requestAnimationFrame(gameLoop);
        }

        // Example usage:
        // Create game objects
        gameObjects.push({ x: 50, y: 50, width: 50, height: 50, velocityX: 100, velocityY: 80 });
        gameObjects.push({ x: 200, y: 100, width: 80, height: 40, velocityX: -60, velocityY: 120 });

        // Start the game loop
        requestAnimationFrame(gameLoop);
    </script>
</body>
</html>
Editor is loading...