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

make an html5 script that makes a 3d cube with physics and u can move the camera on the…

  1. User

    make an html5 script that makes a 3d cube with physics and u can move the camera on the x axis using wasd and on the z axis with arrow keys (one script)

  2. Assistant

    Sure! Below is an HTML5 script that creates a 3D cube with physics using Three.js and Cannon.js. You can move the camera along the X-axis using the W, A, S, and D keys and along the Z-axis using the arrow keys. The entire code is contained within one script.

    Note: This script uses external libraries (Three.js and Cannon.js) linked via CDN. Ensure you have an internet connection to load these libraries.

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>3D Cube with Physics</title>
      <style>
        body { margin: 0; overflow: hidden; }
      </style>
    </head>
    <body>
      <!-- Include Three.js -->
      <script src="https://threejs.org/build/three.min.js"></script>
      <!-- Include Cannon.js -->
      <script src="https://cdn.jsdelivr.net/npm/cannon-es@0.19.0/dist/cannon-es.js"></script>
      <script>
        // Set up the scene, camera, and renderer
        const scene = new THREE.Scene();
    
        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);
    
        // Add lighting
        const ambientLight = new THREE.AmbientLight(0x404040, 1); // Soft white light
        scene.add(ambientLight);
    
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
        directionalLight.position.set(5, 10, 7.5);
        scene.add(directionalLight);
    
        // Create a cube (Three.js mesh)
        const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
        const cubeMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
        const cubeMesh = new THREE.Mesh(cubeGeometry, cubeMaterial);
        scene.add(cubeMesh);
    
        // Create a ground plane (Three.js mesh)
        const groundGeometry = new THREE.PlaneGeometry(10, 10);
        const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x808080 });
        const groundMesh = new THREE.Mesh(groundGeometry, groundMaterial);
        groundMesh.rotation.x = -Math.PI / 2; // Rotate to make it horizontal
        scene.add(groundMesh);
    
        // Set up the physics world (Cannon.js)
        const world = new CANNON.World({
          gravity: new CANNON.Vec3(0, -9.82, 0), // Earth's gravity in m/s^2
        });
    
        // Create a cube (Cannon.js body)
        const cubeShape = new CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5)); // Half extents
        const cubeBody = new CANNON.Body({
          mass: 1, // kg
          shape: cubeShape,
          position: new CANNON.Vec3(0, 5, 0), // Initial position
        });
        world.addBody(cubeBody);
    
        // Create a ground plane (Cannon.js body)
        const groundShape = new CANNON.Plane();
        const groundBody = new CANNON.Body({
          mass: 0, // mass = 0 makes the body static
          shape: groundShape,
        });
        groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0); // Rotate to be horizontal
        world.addBody(groundBody);
    
        // Handle window resize
        window.addEventListener('resize', onWindowResize, false);
        function onWindowResize(){
          camera.aspect = window.innerWidth / window.innerHeight;
          camera.updateProjectionMatrix();
          renderer.setSize(window.innerWidth, window.innerHeight);
        }
    
        // Controls
        const keys = {};
    
        window.addEventListener('keydown', function(event) {
          keys[event.key.toLowerCase()] = true;
        });
    
        window.addEventListener('keyup', function(event) {
          keys[event.key.toLowerCase()] = false;
        });
    
        function updateCameraPosition() {
          // Move camera along X-axis with WASD keys
          if (keys['a']) {
            camera.position.x -= 0.1;
          }
          if (keys['d']) {
            camera.position.x += 0.1;
          }
          if (keys['w']) {
            camera.position.x -= 0.1;
          }
          if (keys['s']) {
            camera.position.x += 0.1;
          }
    
          // Move camera along Z-axis with arrow keys
          if (keys['arrowup']) {
            camera.position.z -= 0.1;
          }
          if (keys['arrowdown']) {
            camera.position.z += 0.1;
          }
          if (keys['arrowleft']) {
            camera.position.z -= 0.1;
          }
          if (keys['arrowright']) {
            camera.position.z += 0.1;
          }
    
          camera.lookAt(cubeMesh.position);
        }
    
        // Animation loop
        function animate() {
          requestAnimationFrame(animate);
    
          // Step the physics world
          world.step(1/60);
    
          // Copy coordinates from physics world to the Three.js mesh
          cubeMesh.position.copy(cubeBody.position);
          cubeMesh.quaternion.copy(cubeBody.quaternion);
    
          // Update camera position based on input
          updateCameraPosition();
    
          // Render the scene
          renderer.render(scene, camera);
        }
        animate();
      </script>
    </body>
    </html>
    

    Explanation:

    • Three.js Scene Setup:

      • We create a scene, a camera, and a renderer.
      • The camera is positioned at (0, 5, 10) and looks at the origin.
      • Ambient and directional lights are added for illumination.
      • A cube mesh and a ground plane mesh are created and added to the scene.
    • Cannon.js Physics Setup:

      • A physics world is created with Earth's gravity.
      • A cube body is created with the same dimensions as the Three.js cube and is given mass so it can fall under gravity.
      • A static ground plane body is created to catch the falling cube.
    • Linking Physics and Graphics:

      • In the animation loop, after updating the physics world, the position and rotation (quaternion) of the cube mesh are updated to match those of the physics body.
    • Controls:

      • Keyboard event listeners track which keys are pressed.
      • The updateCameraPosition function adjusts the camera's position based on the current state of the keys.
        • W, A, S, D keys move the camera along the X-axis.
        • Arrow keys move the camera along the Z-axis.
      • The camera always looks at the cube.
    • Animation Loop:

      • The animate function updates the physics, camera position, and renders the scene on each frame.

    How to Use:

    1. Open the HTML file in a modern web browser (e.g., Chrome, Firefox).
    2. Use the W, A, S, and D keys to move the camera left and right along the X-axis.
    3. Use the arrow keys to move the camera forward and backward along the Z-axis.
    4. Watch the cube fall under gravity and interact with the ground plane.

    Note: Ensure that the browser allows WebGL content and that there are no ad blockers or scripts preventing external library loading.

    Feel free to customize the cube's properties, the camera's speed, or any other aspect to suit your needs!