Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Hello! Create a mini game on js and html with 3d graphict and open active generating world

  1. User

    Hello! Create a mini game on js and html with 3d graphict and open active generating world

  2. Assistant

    Creating a mini 3D game with an open, actively generating world is an exciting project! We'll use Three.js, a powerful JavaScript library for 3D graphics, to handle the rendering and scene management. This example will create a simple endless runner-style game where the world (a series of platforms) is procedurally generated as the player moves forward.

    Features:

    • 3D Graphics: Utilizes Three.js for rendering.
    • Procedural Generation: Continuously generates platforms ahead as the player moves.
    • Basic Controls: Allows the player to move forward automatically and navigate the platforms.

    Setup Instructions

    1. Create Project Files:

      • index.html
      • style.css (optional for basic styling)
      • script.js
    2. Include Three.js: We'll use the Three.js CDN for simplicity.

    Complete Code Example

    1. index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Mini 3D Game</title>
        <style>
            body { margin: 0; overflow: hidden; }
            canvas { display: block; }
            #info {
                position: absolute;
                top: 10px;
                left: 10px;
                color: white;
                font-family: Arial, sans-serif;
                z-index: 100;
            }
        </style>
    </head>
    <body>
        <div id="info">Use Arrow Keys to Move</div>
        <!-- Three.js CDN -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r150/three.min.js"></script>
        <!-- Main Script -->
        <script src="script.js"></script>
    </body>
    </html>
    

    2. script.js

    // Scene Setup
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x87ceeb); // Sky blue
    
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.set(0, 5, 10);
    camera.lookAt(0, 0, 0);
    
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    
    // Resize Handling
    window.addEventListener('resize', () => {
        renderer.setSize(window.innerWidth, window.innerHeight);
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
    });
    
    // Lighting
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
    scene.add(ambientLight);
    
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.6);
    directionalLight.position.set(50, 50, 50);
    scene.add(directionalLight);
    
    // Player (a simple cube)
    const playerGeometry = new THREE.BoxGeometry(1, 1, 1);
    const playerMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 });
    const player = new THREE.Mesh(playerGeometry, playerMaterial);
    player.position.y = 1;
    scene.add(player);
    
    // Ground
    const groundGeometry = new THREE.PlaneGeometry(1000, 1000);
    const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x228B22 });
    const ground = new THREE.Mesh(groundGeometry, groundMaterial);
    ground.rotation.x = -Math.PI / 2;
    scene.add(ground);
    
    // Controls
    const keys = {
        left: false,
        right: false
    };
    
    window.addEventListener('keydown', (e) => {
        if (e.code === 'ArrowLeft') keys.left = true;
        if (e.code === 'ArrowRight') keys.right = true;
    });
    
    window.addEventListener('keyup', (e) => {
        if (e.code === 'ArrowLeft') keys.left = false;
        if (e.code === 'ArrowRight') keys.right = false;
    });
    
    // Procedural Generation Variables
    let lastPlatformZ = 0;
    const platformLength = 10;
    const platformWidth = 5;
    const platformHeight = 1;
    const platforms = [];
    
    // Function to create a new platform
    function createPlatform(z) {
        const geometry = new THREE.BoxGeometry(platformWidth, platformHeight, platformLength);
        const material = new THREE.MeshStandardMaterial({ color: 0x8B4513 });
        const platform = new THREE.Mesh(geometry, material);
        platform.position.set(0, 0, z);
        scene.add(platform);
        platforms.push(platform);
    }
    
    // Initial Platforms
    for (let i = 0; i < 5; i++) {
        createPlatform(lastPlatformZ - i * platformLength);
    }
    
    // Game Variables
    const playerSpeed = 0.2;
    let playerZ = 0;
    let playerX = 0;
    
    // Animation Loop
    function animate() {
        requestAnimationFrame(animate);
    
        // Move Player Forward
        playerZ -= playerSpeed;
        player.position.z = playerZ;
    
        // Handle Left/Right Movement
        if (keys.left) {
            playerX -= 0.1;
        }
        if (keys.right) {
            playerX += 0.1;
        }
        player.position.x = playerX;
    
        // Camera follows the player
        camera.position.z = player.position.z + 10;
        camera.position.x = player.position.x;
        camera.lookAt(player.position.x, player.position.y, player.position.z);
    
        // Procedural Generation: Add new platforms ahead
        while (lastPlatformZ - playerZ < 50) {
            lastPlatformZ -= platformLength;
            createPlatform(lastPlatformZ);
        }
    
        // Remove platforms that are far behind the player
        for (let i = platforms.length - 1; i >= 0; i--) {
            if (platforms[i].position.z - playerZ > 100) {
                scene.remove(platforms[i]);
                platforms.splice(i, 1);
            }
        }
    
        // Simple Collision Detection (staying on the platform)
        const currentPlatformZStart = Math.floor(playerZ / platformLength) * platformLength;
        const currentPlatform = platforms.find(p => p.position.z === currentPlatformZStart);
        if (currentPlatform) {
            player.position.y = platformHeight / 2 + 0.5; // 0.5 is half of player height
        } else {
            // Player has fallen off
            alert("Game Over!");
            window.location.reload();
        }
    
        renderer.render(scene, camera);
    }
    
    animate();
    

    3. style.css (Optional)

    In this example, basic styling is included within the <style> tags in index.html. If you prefer to separate styles, you can create a style.css file and link it in the HTML.

    How It Works

    1. Scene Setup:

      • Initializes the Three.js scene, camera, and renderer.
      • Adds ambient and directional lighting for better visibility.
    2. Player:

      • Represented by a red cube (player).
      • Positioned slightly above the ground to simulate standing on a platform.
    3. Ground and Platforms:

      • A large plane serves as the ground.
      • Platforms are generated as boxes positioned along the z-axis.
      • Initial platforms are created to start the game.
    4. Controls:

      • Listens for left and right arrow key presses to move the player horizontally.
      • Updates the player's position based on input.
    5. Procedural Generation:

      • Continuously generates new platforms ahead of the player as they move forward.
      • Removes platforms that are far behind the player to optimize performance.
    6. Camera:

      • Follows the player from behind, maintaining a consistent view.
    7. Collision Detection:

      • Simple check to ensure the player stays on platforms.
      • If the player falls off a platform, the game alerts "Game Over!" and reloads.

    Running the Game

    1. Local Setup:

      • Ensure you have all three files (index.html, script.js, and optionally style.css) in the same directory.
      • Due to browser security restrictions, it's recommended to run this game on a local server.
    2. Running a Local Server:

      • Using VS Code Live Server Extension:
        • Install the Live Server extension in Visual Studio Code.
        • Right-click index.html and select "Open with Live Server".
      • Using Python (if installed):
        • Open a terminal in the project directory.
        • For Python 3:
          python -m http.server 8000
          
        • Open http://localhost:8000 in your browser.
    3. Play the Game:

      • Use the left and right arrow keys to move the player cube across platforms.
      • The platforms are generated ahead as you move, creating an endless path.
      • Avoid falling off the platforms!

    Further Enhancements

    This is a basic example to get you started. Here are some ideas to expand the game:

    • Textures and Materials: Apply textures to the player and platforms for a more polished look.
    • Obstacles and Enemies: Introduce obstacles or enemies that the player must avoid or defeat.
    • Jump Mechanic: Allow the player to jump to navigate gaps or reach higher platforms.
    • Scoring System: Implement a score based on distance traveled or platforms successfully navigated.
    • Sound Effects and Music: Add audio to enhance the gaming experience.
    • Advanced Procedural Generation: Create more varied and complex environments with different platform types and arrangements.

    Learning Resources

    Feel free to modify and expand upon this example to create a more intricate and engaging game. Happy coding!