JSFiddle - React, Tailwind, and code Playground

by giperon

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Three.js PointerLockControls Example</title>
  <style>
    body { margin: 0; }
    canvas { display: block; }
  </style>
</head>
<body>
  <script src="https://unpkg.com/[email protected]/build/three.min.js"></script>
  <script src="https://unpkg.com/[email protected]/examples/js/controls/PointerLockControls.js"></script>

</body>
</html>

JavaScript

// 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);
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  // Add a basic geometry
  const geometry = new THREE.BoxGeometry();
  const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
  const cube = new THREE.Mesh(geometry, material);
  scene.add(cube);

  // Position the camera
  camera.position.z = 5;

  // Set up PointerLockControls
  const controls = new THREE.PointerLockControls(camera, renderer.domElement);

  document.addEventListener('click', () => {
    controls.lock();
  });

  // Add a basic light source
  const light = new THREE.AmbientLight(0xffffff); // Ambient light
  scene.add(light);

  // Render loop
  function animate() {
    requestAnimationFrame(animate);
    //controls.update();
    renderer.render(scene, camera);
  }
  animate();

  // Handle window resize
  window.addEventListener('resize', () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  });

  // Handle PointerLockControls exit
  document.addEventListener('pointerlockchange', () => {
    if (document.pointerLockElement === renderer.domElement) {
      console.log('Pointer locked');
    } else {
      console.log('Pointer unlocked');
    }
  });