Hello! Can you create sample site with use Three.JS for fps like game in B&W style?
- User
Hello! Can you create sample site with use Three.JS for fps like game in B&W style?
- Assistant
Hello! I'd be happy to help you create a sample site using Three.js for a first-person shooter (FPS) style game in a black and white (B&W) aesthetic. Below, I'll guide you step-by-step on how to set up a basic Three.js scene with FPS controls and style it in black and white.
Table of Contents
- Project Setup
- Creating the HTML Structure
- Setting Up the Three.js Scene
- Implementing FPS Controls
- Adding the Black and White Style
- Running the Application
- Conclusion
Project Setup
1. Prerequisites
- Basic Knowledge: Familiarity with JavaScript, HTML, and CSS.
- Code Editor: Use an editor like VSCode, Sublime Text, or Atom.
- Local Server: For serving the files (since we'll be dealing with modules), you can use a simple HTTP server.
- Optionally, install Node.js and npm for running a local server.
2. Create Project Directory
Create a new directory for your project:
mkdir threejs-fps-bw cd threejs-fps-bw3. Initialize npm (Optional)
If you plan to use npm packages:
npm init -y
Creating the HTML Structure
Create an
index.htmlfile with the following content:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Three.js FPS B&W Game</title> <style> body { margin: 0; overflow: hidden; background-color: #000; } #instructions, #blocker { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } #blocker { background-color: rgba(0,0,0,0.5); } #instructions { display: flex; flex-direction: column; justify-content: center; align-items: center; color: #fff; font-size: 24px; } </style> </head> <body> <div id="blocker"> <div id="instructions"> <span>Click to play</span> <br /> <span style="font-size:14px;">Move: WASD, Look: Mouse</span> </div> </div> <!-- Include Three.js Library --> <script src="https://cdn.jsdelivr.net/npm/three@0.151.3/build/three.min.js"></script> <!-- Include PointerLockControls --> <script src="https://cdn.jsdelivr.net/npm/three@0.151.3/examples/js/controls/PointerLockControls.js"></script> <!-- Include App Script --> <script src="app.js"></script> </body> </html>Explanation:
- We include the Three.js library and the
PointerLockControlsfor FPS controls. - The
#instructionsand#blockerdivs provide instructions and block the view until the player clicks to start.
Setting Up the Three.js Scene
Create an
app.jsfile where we'll set up the scene, camera, renderer, and objects.// app.js let camera, scene, renderer; let controls, raycaster; let moveForward, moveBackward, moveLeft, moveRight; let prevTime = performance.now(); let velocity = new THREE.Vector3(); let direction = new THREE.Vector3(); const objects = []; init(); animate(); function init() { // Camera camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 ); // Scene scene = new THREE.Scene(); scene.background = new THREE.Color(0xffffff); // White background // Light const light = new THREE.HemisphereLight(0xffffff, 0x444444); light.position.set(0, 200, 0); scene.add(light); // Floor const floorGeometry = new THREE.PlaneGeometry(2000, 2000, 100, 100); const floorMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, wireframe: true }); const floor = new THREE.Mesh(floorGeometry, floorMaterial); floor.rotation.x = -Math.PI / 2; // Rotate to horizontal scene.add(floor); // Random Boxes const boxGeometry = new THREE.BoxGeometry(20, 20, 20); const boxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, wireframe: true }); for (let i = 0; i < 500; i++) { const box = new THREE.Mesh(boxGeometry, boxMaterial); box.position.x = Math.floor(Math.random() * 2000 - 1000); box.position.y = Math.floor(Math.random() * 100 + 10); box.position.z = Math.floor(Math.random() * 2000 - 1000); scene.add(box); objects.push(box); } // Renderer renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // Controls controls = new THREE.PointerLockControls(camera, document.body); // Pointer Lock const blocker = document.getElementById('blocker'); const instructions = document.getElementById('instructions'); instructions.addEventListener('click', function () { controls.lock(); }); controls.addEventListener('lock', function () { instructions.style.display = 'none'; blocker.style.display = 'none'; }); controls.addEventListener('unlock', function () { blocker.style.display = 'block'; instructions.style.display = ''; }); scene.add(controls.getObject()); // Event Listeners document.addEventListener('keydown', onKeyDown); document.addEventListener('keyup', onKeyUp); window.addEventListener('resize', onWindowResize); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); }Explanation:
- We set up a basic scene with a camera, renderer, and controls.
- Added a floor and random boxes to populate the scene.
- Configured the pointer lock controls for FPS movement.
Implementing FPS Controls
Add the movement handling in
app.js:// Movement Flags moveForward = false; moveBackward = false; moveLeft = false; moveRight = false; function onKeyDown(event) { switch (event.code) { case 'ArrowUp': case 'KeyW': moveForward = true; break; case 'ArrowLeft': case 'KeyA': moveLeft = true; break; case 'ArrowDown': case 'KeyS': moveBackward = true; break; case 'ArrowRight': case 'KeyD': moveRight = true; break; } } function onKeyUp(event) { switch (event.code) { case 'ArrowUp': case 'KeyW': moveForward = false; break; case 'ArrowLeft': case 'KeyA': moveLeft = false; break; case 'ArrowDown': case 'KeyS': moveBackward = false; break; case 'ArrowRight': case 'KeyD': moveRight = false; break; } }Update the
animatefunction:function animate() { requestAnimationFrame(animate); if (controls.isLocked === true) { const time = performance.now(); const delta = (time - prevTime) / 1000; // seconds velocity.x -= velocity.x * 10.0 * delta; velocity.z -= velocity.z * 10.0 * delta; direction.z = Number(moveForward) - Number(moveBackward); direction.x = Number(moveRight) - Number(moveLeft); direction.normalize(); const speed = 400.0; if (moveForward || moveBackward) velocity.z -= direction.z * speed * delta; if (moveLeft || moveRight) velocity.x -= direction.x * speed * delta; controls.moveRight(-velocity.x * delta); controls.moveForward(-velocity.z * delta); prevTime = time; } renderer.render(scene, camera); }Explanation:
- We calculate the movement based on key presses.
- The
velocityanddirectionvectors control the movement speed and direction. - The controls are updated according to the calculated velocity.
Adding the Black and White Style
To maintain a black and white aesthetic:
- Use
MeshBasicMaterialwith colors set to black (0x000000). - Set the scene's background to white (
0xffffff). - Utilize
wireframe: truein materials to create an outline effect.
We've already set the scene background to white and materials to black with wireframe enabled:
scene.background = new THREE.Color(0xffffff); const floorMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, wireframe: true }); const boxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, wireframe: true });Optional Enhancements:
- Adjust the thickness of wireframes using custom shaders (advanced).
- Introduce grayscale textures if you want to add more detail.
Running the Application
Since modern browsers enforce strict policies on loading local files, especially when using modules or dynamic imports, it's best to run a local server to serve the files.
Using Node.js and npm:
-
Install
live-serverGlobally (if not already installed):npm install -g live-server -
Run the Local Server:
live-server -
Access the Application:
Open your browser and navigate to
http://127.0.0.1:8080(or the URL provided bylive-server).
Using Python:
For Python 3.x users, you can use:
python -m http.server 8000Then navigate to
http://localhost:8000.Using VSCode Extension:
If you're using VSCode, you can install the Live Server extension and run it directly from the editor.
Conclusion
You've now created a basic FPS-like game using Three.js in a black and white style! This sample demonstrates:
- Setting up a Three.js scene with basic geometries.
- Implementing FPS controls using
PointerLockControls. - Styling the scene to achieve a black and white aesthetic.
Next Steps and Enhancements:
- Collision Detection: Prevent the player from walking through objects.
- Use
Raycasterto detect intersections.
- Use
- Add Interactivity: Allow the player to interact with objects (e.g., pick up items).
- Enhance the Environment: Add more geometries or create a maze-like structure.
- Styling: Experiment with different shapes and patterns to enhance the visual appeal.
Feel free to ask if you have any questions or need further assistance with any part of the code!