Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash-lite-preview-06-17-thinking· GoogleHugging Face LMArena Human Preference 140K

Make a 3d FPS using Three.js, css, and html in one file. Make it to where i can move…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-7-sonnet-20250219-thinking-32k’s answer.
  1. User

    Make a 3d FPS using Three.js, css, and html in one file. Make it to where i can move using WASD, theres a gun that i can shoot. A simple crosshair with a HUD system. Very nice UI.

  2. Gemini Assistant

    Okay, here is a single HTML file containing a basic 3D FPS structure using Three.js, CSS, and HTML. It includes WASD movement, mouse-look, a simple gun visual, a raycasting shooting mechanic, a basic crosshair, and a simple HUD.

    Key Features Implemented:

    1. Three.js Setup: Basic scene, camera, renderer, and animation loop.
    2. Environment: A simple floor and walls to provide boundaries.
    3. First-Person Controls:
      • Uses PointerLockAPI for intuitive mouse-based looking.
      • WASD keys for movement relative to the camera's direction.
    4. Gun: A simple geometric shape attached to the camera.
    5. Shooting:
      • Click to shoot.
      • Uses Raycaster to detect hits.
      • Changes the color of hit objects.
      • Adds a simple visual "hit" indicator.
    6. HUD:
      • A central crosshair using CSS.
      • A simple ammo counter (static text in this example).
    7. UI: Basic styling for the HUD and the initial "Start" button.

    How to Use:

    1. Save the code below as an HTML file (e.g., fps.html).
    2. Open the file in your web browser.
    3. Click the "Start" button to enable the first-person controls and lock the mouse.
    4. Use W, A, S, D to move.
    5. Move your mouse to look around.
    6. Click the left mouse button to shoot.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Simple 3D FPS</title>
        <style>
            body {
                margin: 0;
                overflow: hidden; /* Prevent scrollbars */
                font-family: Arial, sans-serif;
                background-color: #222;
                color: #eee;
                cursor: default; /* Default cursor */
            }
            canvas {
                display: block; /* Remove extra space below canvas */
            }
            #hud {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                pointer-events: none; /* Allows clicks to pass through to the scene */
                display: flex;
                flex-direction: column;
                justify-content: flex-end; /* Align items to the bottom */
                align-items: center; /* Center horizontally */
                box-sizing: border-box;
                padding-bottom: 20px; /* Space from bottom */
            }
            #crosshair {
                width: 10px;
                height: 10px;
                border: 2px solid rgba(255, 255, 255, 0.8);
                background-color: transparent;
                border-radius: 50%;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                margin-top: -7px; /* Adjust slightly for perfect centering */
                margin-left: -7px; /* Adjust slightly for perfect centering */
                pointer-events: none;
                z-index: 10;
            }
            /* Optional: Lines for the crosshair */
            #crosshair::before,
            #crosshair::after {
                content: '';
                position: absolute;
                background-color: rgba(255, 255, 255, 0.8);
                pointer-events: none;
            }
            #crosshair::before { /* Horizontal line */
                top: 50%;
                left: -3px; /* Adjust position relative to crosshair size */
                width: 16px; /* Make it slightly longer */
                height: 2px;
                transform: translateY(-50%);
            }
            #crosshair::after { /* Vertical line */
                top: 50%;
                left: 50%;
                width: 2px;
                height: 16px; /* Make it slightly longer */
                transform: translate(-50%, -50%);
            }
    
            #ammo {
                position: absolute;
                bottom: 20px;
                left: 20px;
                font-size: 1.2em;
                background-color: rgba(0, 0, 0, 0.5);
                padding: 5px 10px;
                border-radius: 5px;
                pointer-events: none;
                z-index: 10;
            }
            #startButton {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                padding: 15px 30px;
                font-size: 1.5em;
                cursor: pointer;
                background-color: #4CAF50;
                color: white;
                border: none;
                border-radius: 8px;
                z-index: 20;
                transition: background-color 0.3s ease;
            }
            #startButton:hover {
                background-color: #45a049;
            }
            #hitMarker {
                position: absolute;
                top: 50%;
                left: 50%;
                width: 20px;
                height: 20px;
                border: 3px solid rgba(255, 0, 0, 0.7);
                transform: translate(-50%, -50%) rotate(45deg) scale(0); /* Start hidden and small */
                opacity: 0;
                transition: opacity 0.1s ease-out, transform 0.2s ease-out;
                pointer-events: none;
                z-index: 15; /* Above crosshair */
                border-radius: 2px; /* Slightly rounded corners */
            }
            #hitMarker.visible {
                opacity: 1;
                transform: translate(-50%, -50%) rotate(45deg) scale(1);
            }
        </style>
    </head>
    <body>
        <button id="startButton">Start FPS</button>
        <div id="hud">
            <div id="crosshair"></div>
            <div id="hitMarker"></div>
            <div id="ammo">Ammo: 10</div>
        </div>
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
        <script>
            // --- Basic Setup ---
            const scene = new THREE.Scene();
            const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
            const renderer = new THREE.WebGLRenderer({ antialias: true });
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.shadowMap.enabled = true; // Enable shadows
            document.body.appendChild(renderer.domElement);
    
            // --- Player and Movement ---
            const player = {
                height: 1.6,
                speed: 0.2,
                turnSpeed: Math.PI * 0.015,
                jumpSpeed: 0.3,
                gravity: -0.015,
                velocity: new THREE.Vector3(0, 0, 0),
                onGround: false,
                moveDirection: new THREE.Vector3(),
                keys: { forward: false, backward: false, left: false, right: false }
            };
            player.velocity.y = -0.1; // Start slightly down
    
            // Position camera relative to player model (if we had one)
            // For now, camera IS the player view
            camera.position.y = player.height;
            camera.rotation.order = "YXZ"; // Important for movement logic
    
            // --- Pointer Lock ---
            const startButton = document.getElementById('startButton');
            const canvas = renderer.domElement;
            let isPointerLocked = false;
    
            function requestPointerLock() {
                canvas.requestPointerLock();
            }
    
            function exitPointerLock() {
                document.exitPointerLock();
            }
    
            function onPointerlockChange() {
                isPointerLocked = document.pointerLockElement === canvas;
                if (isPointerLocked) {
                    startButton.style.display = 'none'; // Hide button when locked
                    hud.style.cursor = 'crosshair'; // Show crosshair cursor
                } else {
                    startButton.style.display = 'block'; // Show button when unlocked
                    hud.style.cursor = 'default'; // Restore default cursor
                }
            }
    
            function onKeyDown(event) {
                if (!isPointerLocked) return;
    
                switch (event.code) {
                    case 'KeyW': player.keys.forward = true; break;
                    case 'KeyS': player.keys.backward = true; break;
                    case 'KeyA': player.keys.left = true; break;
                    case 'KeyD': player.keys.right = true; break;
                    case 'Space':
                        if (player.onGround) {
                            player.velocity.y = player.jumpSpeed;
                            player.onGround = false;
                        }
                        break;
                }
            }
    
            function onKeyUp(event) {
                 if (!isPointerLocked) return;
    
                switch (event.code) {
                    case 'KeyW': player.keys.forward = false; break;
                    case 'KeyS': player.keys.backward = false; break;
                    case 'KeyA': player.keys.left = false; break;
                    case 'KeyD': player.keys.right = false; break;
                }
            }
    
            function onMouseMove(event) {
                if (!isPointerLocked) return;
    
                const movementX = event.movementX;
                const movementY = event.movementY;
    
                // Horizontal rotation (Yaw)
                camera.rotation.y -= movementX * player.turnSpeed;
    
                // Vertical rotation (Pitch)
                camera.rotation.x -= movementY * player.turnSpeed;
                camera.rotation.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, camera.rotation.x)); // Clamp pitch
            }
    
            function onMouseDown(event) {
                if (!isPointerLocked) return;
                if (event.button === 0) { // Left mouse button
                    shoot();
                }
            }
    
            document.addEventListener('pointerlockchange', onPointerlockChange, false);
            startButton.addEventListener('click', requestPointerLock);
            document.addEventListener('keydown', onKeyDown, false);
            document.addEventListener('keyup', onKeyUp, false);
            document.addEventListener('mousemove', onMouseMove, false);
            document.addEventListener('mousedown', onMouseDown, false);
    
            // --- Environment Geometry ---
            const floorGeometry = new THREE.PlaneGeometry(50, 50);
            const floorMaterial = new THREE.MeshStandardMaterial({ color: 0x404040, side: THREE.DoubleSide });
            const floor = new THREE.Mesh(floorGeometry, floorMaterial);
            floor.rotation.x = -Math.PI / 2; // Rotate to be horizontal
            floor.receiveShadow = true;
            scene.add(floor);
    
            // Walls
            const wallMaterial = new THREE.MeshStandardMaterial({ color: 0x777777 });
            const wallThickness = 0.5;
            const wallHeight = 10;
            const wallWidth = 50;
    
            const wall1 = new THREE.Mesh(new THREE.BoxGeometry(wallWidth, wallHeight, wallThickness), wallMaterial);
            wall1.position.set(0, wallHeight / 2 - 0.5, -wallWidth / 2); // Positioned wall
            wall1.receiveShadow = true;
            wall1.castShadow = true;
            scene.add(wall1);
    
            const wall2 = new THREE.Mesh(new THREE.BoxGeometry(wallWidth, wallHeight, wallThickness), wallMaterial);
            wall2.position.set(0, wallHeight / 2 - 0.5, wallWidth / 2); // Positioned wall
            wall2.receiveShadow = true;
            wall2.castShadow = true;
            scene.add(wall2);
    
            const wall3 = new THREE.Mesh(new THREE.BoxGeometry(wallThickness, wallHeight, wallWidth), wallMaterial);
            wall3.position.set(-wallWidth / 2, wallHeight / 2 - 0.5, 0); // Positioned wall
            wall3.receiveShadow = true;
            wall3.castShadow = true;
            scene.add(wall3);
    
            const wall4 = new THREE.Mesh(new THREE.BoxGeometry(wallThickness, wallHeight, wallWidth), wallMaterial);
            wall4.position.set(wallWidth / 2, wallHeight / 2 - 0.5, 0); // Positioned wall
            wall4.receiveShadow = true;
            wall4.castShadow = true;
            scene.add(wall4);
    
            // Add some cubes to shoot at
            const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
            const cubeMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
            const shootableObjects = [];
    
            for (let i = 0; i < 10; i++) {
                const cube = new THREE.Mesh(cubeGeometry, cubeMaterial.clone()); // Clone material to allow individual color changes
                cube.position.set(
                    (Math.random() - 0.5) * 30,
                    0.5,
                    (Math.random() - 0.5) * 30
                );
                cube.castShadow = true;
                cube.receiveShadow = true;
                scene.add(cube);
                shootableObjects.push(cube);
            }
    
            // --- Gun Visual ---
            const gunGeometry = new THREE.CylinderGeometry(0.05, 0.1, 0.5, 8);
            const gunMaterial = new THREE.MeshBasicMaterial({ color: 0x808080 });
            const gun = new THREE.Mesh(gunGeometry, gunMaterial);
            gun.rotation.x = Math.PI / 2; // Point forward initially
            gun.position.set(0.2, -0.3, -0.8); // Position relative to camera
            camera.add(gun); // Attach gun to camera
    
            // --- Lighting ---
            const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
            scene.add(ambientLight);
    
            const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
            directionalLight.position.set(5, 10, 7.5);
            directionalLight.castShadow = true;
            directionalLight.shadow.mapSize.width = 1024;
            directionalLight.shadow.mapSize.height = 1024;
            directionalLight.shadow.camera.near = 0.5;
            directionalLight.shadow.camera.far = 50;
            directionalLight.shadow.focus = 1;
            scene.add(directionalLight);
    
            // --- Raycasting for Shooting ---
            const raycaster = new THREE.Raycaster();
            const shootDistance = 100; // How far the ray travels
            let ammo = 10;
            const ammoDisplay = document.getElementById('ammo');
            const hitMarker = document.getElementById('hitMarker');
    
            function shoot() {
                if (ammo <= 0) return; // No ammo left
    
                ammo--;
                ammoDisplay.textContent = `Ammo: ${ammo}`;
    
                // Set the raycaster from the camera's perspective
                raycaster.setFromCamera(camera, scene);
    
                // Find intersections
                const intersects = raycaster.intersectObjects(shootableObjects);
    
                if (intersects.length > 0) {
                    const intersection = intersects[0];
                    const hitObject = intersection.object;
    
                    // Apply visual feedback to the hit object
                    if (hitObject.material.color) {
                        hitObject.material.color.set(0xff0000); // Turn red on hit
                    }
    
                     // Show hit marker briefly
                    hitMarker.classList.add('visible');
                    setTimeout(() => {
                        hitMarker.classList.remove('visible');
                    }, 150); // Duration the marker is visible
    
                    // Optional: Remove object after hit, or reset color after delay
                    // setTimeout(() => {
                    //     hitObject.visible = false;
                    //     scene.remove(hitObject);
                    //     shootableObjects.splice(shootableObjects.indexOf(hitObject), 1);
                    // }, 500);
                    // setTimeout(() => {
                    //      if (hitObject.material.color) {
                    //         hitObject.material.color.set(0x00ff00); // Reset color
                    //      }
                    // }, 300);
    
    
                } else {
                    // Optional: Show miss effect or just nothing happens
                    // Hit marker still shows briefly on miss
                    hitMarker.classList.add('visible');
                    setTimeout(() => {
                        hitMarker.classList.remove('visible');
                    }, 150);
                }
            }
    
            // --- Animation Loop ---
            const clock = new THREE.Clock();
            function animate() {
                requestAnimationFrame(animate);
    
                const delta = clock.getDelta();
    
                // Player Movement Update
                player.moveDirection.z = Number(player.keys.forward) - Number(player.keys.backward);
                player.moveDirection.x = Number(player.keys.left) - Number(player.keys.right);
                player.moveDirection.normalize(); // Ensure diagonal movement isn't faster
    
                // Apply movement based on camera direction
                if (player.moveDirection.z !== 0) {
                    camera.getWorldPosition(player.position); // Get current position
                    const forwardVector = new THREE.Vector3();
                    camera.getWorldDirection(forwardVector); // Get forward direction
                    forwardVector.y = 0; // Ignore vertical component for horizontal movement
                    forwardVector.normalize();
                    player.position.addScaledVector(forwardVector, player.moveDirection.z * player.speed);
                    camera.position.copy(player.position); // Update camera position
                }
                 if (player.moveDirection.x !== 0) {
                    player.position.copy(camera.position); // Get current position
                    const rightVector = new THREE.Vector3();
                    rightVector.crossVectors(camera.up, forwardVector); // Get right vector (Camera up is usually Y, so cross with forward gives right)
                    rightVector.normalize();
                    player.position.addScaledVector(rightVector, player.moveDirection.x * player.speed);
                    camera.position.copy(player.position); // Update camera position
                }
    
                // Gravity and Ground Check
                player.velocity.y += player.gravity;
                camera.position.y += player.velocity.y;
    
                // Simple ground collision check
                if (camera.position.y <= player.height) {
                    camera.position.y = player.height;
                    player.velocity.y = 0;
                    player.onGround = true;
                }
    
                renderer.render(scene, camera);
            }
    
            // --- Handle Window Resize ---
            function onWindowResize() {
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                renderer.setSize(window.innerWidth, window.innerHeight);
            }
            window.addEventListener('resize', onWindowResize, false);
    
            // Start the animation loop
            animate();
    
        </script>
    </body>
    </html>
    

    Explanation:

    1. HTML Structure:

      • A <canvas> element is where Three.js renders.
      • A div#hud contains the div#crosshair, div#hitMarker, and div#ammo for the Heads-Up Display.
      • A <button id="startButton"> is used to initiate the Pointer Lock API.
    2. CSS Styling:

      • Basic resets for body and canvas.
      • #hud is positioned absolutely to cover the screen, and pointer-events: none; is crucial so that the 3D scene below it can receive mouse events when the pointer isn't locked.
      • #crosshair is styled using CSS to create a simple circular target in the center. Pseudo-elements (::before, ::after) are used to add lines extending from it, making it look more like a traditional crosshair.
      • #hitMarker is initially hidden (opacity: 0, scale(0)) and positioned in the center. A CSS class .visible is added/removed by JavaScript to make it flash red and grow slightly when shooting.
      • #ammo displays the ammo count in the bottom-left corner.
      • #startButton is centered and styled to be clickable.
    3. JavaScript Logic:

      • Three.js Core: Initializes the scene, perspective camera, and WebGL renderer.
      • Player Object: Stores player properties like speed, height, and movement state (keys).
      • Pointer Lock:
        • An event listener waits for the pointerlockchange event to know when the mouse is locked or unlocked.
        • The startButton click triggers canvas.requestPointerLock().
        • onMouseMove handles camera rotation based on mouse movement when locked.
        • onKeyDown/onKeyUp update the player.keys state.
        • onMouseDown triggers the shoot() function on left-click.
      • Environment: Creates a floor (PlaneGeometry) and four walls (BoxGeometry) with MeshStandardMaterial for basic lighting interaction. Adds shadow casting/receiving.
      • Shootable Objects: Creates several green cubes using BoxGeometry and adds them to an array shootableObjects. These are the targets.
      • Gun: A simple CylinderGeometry is created, given a basic material, and attached (camera.add(gun)) as a child of the camera. This makes the gun move and rotate with the camera.
      • Lighting: AmbientLight provides overall illumination, and DirectionalLight simulates a light source, enabling shadows.
      • Shooting (shoot function):
        • Decrements ammo and updates the display.
        • Creates a THREE.Raycaster.
        • raycaster.setFromCamera(camera) points the ray in the camera's forward direction.
        • raycaster.intersectObjects(shootableObjects) checks for collisions with the target cubes.
        • If an object is hit (intersects.length > 0), its color is changed to red, and the hitMarker is briefly shown.
        • If no object is hit, the hitMarker still shows briefly (simulating aiming/firing).
      • Animation Loop (animate function):
        • Uses requestAnimationFrame for smooth animation.
        • Calculates delta time for frame-rate independent movement.
        • Updates the camera's position based on the player.keys state and the camera's current orientation (using getWorldPosition and getWorldDirection).
        • Implements basic gravity affecting the camera's Y position.
        • Includes a simple ground collision check to prevent falling through the floor.
        • Calls renderer.render(scene, camera) to draw the frame.
      • Window Resize: The onWindowResize function ensures the camera's aspect ratio and the renderer's size update when the browser window is resized.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.