write a html 3d plane game.
- User
write a html 3d plane game.
Assistant
Okay, building a full-fledged 3D game in HTML/JS from scratch without libraries like Three.js or Babylon.js would be extremely complex (requiring raw WebGL knowledge). A simple, playable 3D plane game using a library like Three.js is much more feasible and commonly what people mean.
This example will create:
- A 3D environment (simple ground and sky).
- A basic 3D plane model.
- Controls to pitch (up/down) and roll (left/right) the plane.
- The plane will move forward automatically.
- A camera that follows the plane.
It's a very basic simulation, not a full game with objectives, collisions, etc.
Here's the code:
<!DOCTYPE html> <html> <head> <title>Simple 3D Plane</title> <style> body { margin: 0; overflow: hidden; background-color: #87CEEB; /* Sky blue */ } canvas { display: block; } </style> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script> // --- Scene Setup --- 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); renderer.setPixelRatio(window.devicePixelRatio); // Prevent blurry canvas document.body.appendChild(renderer.domElement); // --- Environment --- // Ground const groundGeometry = new THREE.PlaneGeometry(1000, 1000); const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x228B22, side: THREE.DoubleSide }); // Forest green const ground = new THREE.Mesh(groundGeometry, groundMaterial); ground.rotation.x = -Math.PI / 2; // Rotate to be flat scene.add(ground); // Add some simple "mountains" or bumps (optional, makes it look less flat) // This is a very basic way, more advanced techniques exist function addBumps(count, size, spread) { const bumpMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513 }); // Saddle brown for (let i = 0; i < count; i++) { const bumpGeometry = new THREE.SphereGeometry(size * (0.5 + Math.random()), 8, 8); // Simple sphere const bump = new THREE.Mesh(bumpGeometry, bumpMaterial); bump.position.x = (Math.random() - 0.5) * spread; bump.position.y = bumpGeometry.parameters.radius / 2; // Place on ground bump.position.z = (Math.random() - 0.5) * spread; scene.add(bump); } } addBumps(50, 15, 800); // Add 50 bumps, avg size 15, spread over 800x800 area // --- Lighting --- const ambientLight = new THREE.AmbientLight(0x404040); // Soft white light scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8); directionalLight.position.set(1, 1, 1).normalize(); scene.add(directionalLight); // --- Plane Model (Simple) --- const plane = new THREE.Group(); // Use a group to hold parts and rotate together // Body const bodyGeometry = new THREE.BoxGeometry(1, 0.5, 3); const bodyMaterial = new THREE.MeshStandardMaterial({ color: 0xc0c0c0 }); // Silver const body = new THREE.Mesh(bodyGeometry, bodyMaterial); plane.add(body); // Wings const wingGeometry = new THREE.BoxGeometry(4, 0.1, 1); const wingMaterial = new THREE.MeshStandardMaterial({ color: 0xc0c0c0 }); // Silver const leftWing = new THREE.Mesh(wingGeometry, wingMaterial); leftWing.position.set(-2, 0.1, 0); // Position relative to body center const rightWing = new THREE.Mesh(wingGeometry, wingMaterial); rightWing.position.set(2, 0.1, 0); // Position relative to body center plane.add(leftWing); plane.add(rightWing); // Tail fin const tailGeometry = new THREE.BoxGeometry(0.1, 1, 0.5); const tailMaterial = new THREE.MeshStandardMaterial({ color: 0xc0c0c0 }); // Silver const tailFin = new THREE.Mesh(tailGeometry, tailMaterial); tailFin.position.set(0, 0.6, -1.4); // Position relative to body plane.add(tailFin); scene.add(plane); // --- Camera Setup --- // Position camera relative to the plane, slightly behind and above const cameraOffset = new THREE.Vector3(0, 5, 15); camera.position.copy(plane.position).add(cameraOffset); camera.lookAt(plane.position); // Make camera look at the plane // --- Controls --- const keyState = {}; const rotationSpeed = 0.02; // How fast the plane rotates const forwardSpeed = 0.5; // How fast the plane moves forward window.addEventListener('keydown', (event) => { keyState[event.code] = true; }); window.addEventListener('keyup', (event) => { keyState[event.code] = false; }); // --- Game Loop (Animation) --- let lastTime = 0; function animate(currentTime) { requestAnimationFrame(animate); const deltaTime = (currentTime - lastTime) / 1000; // Convert milliseconds to seconds lastTime = currentTime; // Apply rotations based on key presses if (keyState['KeyA']) { // Roll Left plane.rotation.z += rotationSpeed; } if (keyState['KeyD']) { // Roll Right plane.rotation.z -= rotationSpeed; } if (keyState['KeyW']) { // Pitch Down (nose down) plane.rotation.x += rotationSpeed; } if (keyState['KeyS']) { // Pitch Up (nose up) plane.rotation.x -= rotationSpeed; } // Keep rotations within reasonable limits (optional but helps prevent flips) plane.rotation.x = Math.max(-Math.PI / 4, Math.min(Math.PI / 4, plane.rotation.x)); plane.rotation.z = Math.max(-Math.PI / 4, Math.min(Math.PI / 4, plane.rotation.z)); // Move the plane forward based on its current orientation // plane.translateZ(-forwardSpeed * deltaTime); // Moves along local Z axis const direction = new THREE.Vector3(0, 0, -1); // Forward direction in local space direction.applyQuaternion(plane.quaternion); // Rotate the direction vector by plane's rotation plane.position.add(direction.multiplyScalar(forwardSpeed)); // Move position in that direction // Update camera position to follow the plane const currentCameraOffset = cameraOffset.clone(); currentCameraOffset.applyQuaternion(plane.quaternion); // Rotate offset by plane's rotation camera.position.copy(plane.position).add(currentCameraOffset); camera.lookAt(plane.position); // Make camera look at the plane's current position // Render the scene renderer.render(scene, camera); } // Start the animation loop animate(); // --- Handle Window Resizing --- window.addEventListener('resize', onWindowResize, false); function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(window.devicePixelRatio); } </script> </body> </html>How to Run:
- Save the code above as an
.htmlfile (e.g.,plane_game.html). - Open the
.htmlfile in a web browser (like Chrome, Firefox, Edge).
Controls:
- W: Pitch Down (Nose goes down)
- S: Pitch Up (Nose goes up)
- A: Roll Left
- D: Roll Right
Explanation:
- HTML Structure: Sets up a basic HTML page and includes the Three.js library from a CDN (Content Delivery Network). The
<style>block makes the canvas fill the entire window and sets a background color. - Three.js Setup:
Scene: The container for all your 3D objects, cameras, and lights.Camera: Defines the viewpoint. APerspectiveCameramimics how humans see, with objects further away appearing smaller.Renderer: Takes thesceneandcameraand draws the 3D world onto the<canvas>element using WebGL.
- Environment:
- A large
PlaneGeometryrotated to be flat serves as the ground. MeshStandardMaterialis used for materials, which reacts to lights.- Simple
SphereGeometrymeshes are added randomly as "bumps" or distant hills on the ground.
- A large
- Lighting:
AmbientLightprovides a general illumination so all sides of objects are visible.DirectionalLightsimulates sunlight coming from a specific direction, creating a sense of depth.
- Plane Model:
- A
THREE.Groupis used to treat the plane's body, wings, and tail as a single unit for movement and rotation. - Simple
BoxGeometrymeshes are used to create the basic shapes of the plane parts.
- A
- Camera Follow: The camera's position is calculated in the animation loop. It starts with the plane's position and adds an
cameraOffsetvector that is rotated by the plane's current rotation. This makes the camera stay a consistent distance and angle relative to the plane, even as the plane rotates.camera.lookAt(plane.position)ensures the camera always points towards the center of the plane. - Controls:
- An object
keyStatetracks which keys are currently pressed down. - Event listeners for
keydownandkeyupupdate thekeyState.
- An object
- Game Loop (
animatefunction):requestAnimationFrameis the standard way to create an animation loop in the browser, running the function before the browser repaints.deltaTimeis calculated to ensure movement and rotation speed are consistent regardless of the frame rate.- The plane's rotation is updated based on the
keyState. - The plane is moved forward using its local Z-axis direction, ensuring it moves in the direction it's pointed.
- The camera's position and look-at point are updated to follow the plane.
renderer.render(scene, camera)draws the updated scene.
- Resize Handling: The
onWindowResizefunction updates the camera's aspect ratio and the renderer's size when the browser window is resized, preventing distortion.
Further Improvements (Complexities):
- More detailed plane model (loading 3D models).
- Obstacles and collision detection.
- Scoring system.
- Varied terrain or environment (mountains, clouds, water).
- Better camera movement (smoothing, different angles).
- Physics simulation (gravity, lift, drag).
- Animations (propeller, landing gear).
- Sound effects.
This provides a solid foundation for a simple 3D plane experience in your browser using HTML and Three.js.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.