Hello! Create a mini game on js and html with 3d graphict and open active generating world
- User
Hello! Create a mini game on js and html with 3d graphict and open active generating world
- Assistant
Creating a mini 3D game with an open, actively generating world is an exciting project! We'll use Three.js, a powerful JavaScript library for 3D graphics, to handle the rendering and scene management. This example will create a simple endless runner-style game where the world (a series of platforms) is procedurally generated as the player moves forward.
Features:
- 3D Graphics: Utilizes Three.js for rendering.
- Procedural Generation: Continuously generates platforms ahead as the player moves.
- Basic Controls: Allows the player to move forward automatically and navigate the platforms.
Setup Instructions
-
Create Project Files:
index.htmlstyle.css(optional for basic styling)script.js
-
Include Three.js: We'll use the Three.js CDN for simplicity.
Complete Code Example
1.
index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Mini 3D Game</title> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #info { position: absolute; top: 10px; left: 10px; color: white; font-family: Arial, sans-serif; z-index: 100; } </style> </head> <body> <div id="info">Use Arrow Keys to Move</div> <!-- Three.js CDN --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r150/three.min.js"></script> <!-- Main Script --> <script src="script.js"></script> </body> </html>2.
script.js// Scene Setup const scene = new THREE.Scene(); scene.background = new THREE.Color(0x87ceeb); // Sky blue 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); // Resize Handling window.addEventListener('resize', () => { renderer.setSize(window.innerWidth, window.innerHeight); camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); }); // Lighting const ambientLight = new THREE.AmbientLight(0xffffff, 0.7); scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.6); directionalLight.position.set(50, 50, 50); scene.add(directionalLight); // Player (a simple cube) const playerGeometry = new THREE.BoxGeometry(1, 1, 1); const playerMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 }); const player = new THREE.Mesh(playerGeometry, playerMaterial); player.position.y = 1; scene.add(player); // Ground const groundGeometry = new THREE.PlaneGeometry(1000, 1000); const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x228B22 }); const ground = new THREE.Mesh(groundGeometry, groundMaterial); ground.rotation.x = -Math.PI / 2; scene.add(ground); // Controls const keys = { left: false, right: false }; window.addEventListener('keydown', (e) => { if (e.code === 'ArrowLeft') keys.left = true; if (e.code === 'ArrowRight') keys.right = true; }); window.addEventListener('keyup', (e) => { if (e.code === 'ArrowLeft') keys.left = false; if (e.code === 'ArrowRight') keys.right = false; }); // Procedural Generation Variables let lastPlatformZ = 0; const platformLength = 10; const platformWidth = 5; const platformHeight = 1; const platforms = []; // Function to create a new platform function createPlatform(z) { const geometry = new THREE.BoxGeometry(platformWidth, platformHeight, platformLength); const material = new THREE.MeshStandardMaterial({ color: 0x8B4513 }); const platform = new THREE.Mesh(geometry, material); platform.position.set(0, 0, z); scene.add(platform); platforms.push(platform); } // Initial Platforms for (let i = 0; i < 5; i++) { createPlatform(lastPlatformZ - i * platformLength); } // Game Variables const playerSpeed = 0.2; let playerZ = 0; let playerX = 0; // Animation Loop function animate() { requestAnimationFrame(animate); // Move Player Forward playerZ -= playerSpeed; player.position.z = playerZ; // Handle Left/Right Movement if (keys.left) { playerX -= 0.1; } if (keys.right) { playerX += 0.1; } player.position.x = playerX; // Camera follows the player camera.position.z = player.position.z + 10; camera.position.x = player.position.x; camera.lookAt(player.position.x, player.position.y, player.position.z); // Procedural Generation: Add new platforms ahead while (lastPlatformZ - playerZ < 50) { lastPlatformZ -= platformLength; createPlatform(lastPlatformZ); } // Remove platforms that are far behind the player for (let i = platforms.length - 1; i >= 0; i--) { if (platforms[i].position.z - playerZ > 100) { scene.remove(platforms[i]); platforms.splice(i, 1); } } // Simple Collision Detection (staying on the platform) const currentPlatformZStart = Math.floor(playerZ / platformLength) * platformLength; const currentPlatform = platforms.find(p => p.position.z === currentPlatformZStart); if (currentPlatform) { player.position.y = platformHeight / 2 + 0.5; // 0.5 is half of player height } else { // Player has fallen off alert("Game Over!"); window.location.reload(); } renderer.render(scene, camera); } animate();3.
style.css(Optional)In this example, basic styling is included within the
<style>tags inindex.html. If you prefer to separate styles, you can create astyle.cssfile and link it in the HTML.How It Works
-
Scene Setup:
- Initializes the Three.js scene, camera, and renderer.
- Adds ambient and directional lighting for better visibility.
-
Player:
- Represented by a red cube (
player). - Positioned slightly above the ground to simulate standing on a platform.
- Represented by a red cube (
-
Ground and Platforms:
- A large plane serves as the ground.
- Platforms are generated as boxes positioned along the z-axis.
- Initial platforms are created to start the game.
-
Controls:
- Listens for left and right arrow key presses to move the player horizontally.
- Updates the player's position based on input.
-
Procedural Generation:
- Continuously generates new platforms ahead of the player as they move forward.
- Removes platforms that are far behind the player to optimize performance.
-
Camera:
- Follows the player from behind, maintaining a consistent view.
-
Collision Detection:
- Simple check to ensure the player stays on platforms.
- If the player falls off a platform, the game alerts "Game Over!" and reloads.
Running the Game
-
Local Setup:
- Ensure you have all three files (
index.html,script.js, and optionallystyle.css) in the same directory. - Due to browser security restrictions, it's recommended to run this game on a local server.
- Ensure you have all three files (
-
Running a Local Server:
- Using VS Code Live Server Extension:
- Install the Live Server extension in Visual Studio Code.
- Right-click
index.htmland select "Open with Live Server".
- Using Python (if installed):
- Open a terminal in the project directory.
- For Python 3:
python -m http.server 8000 - Open
http://localhost:8000in your browser.
- Using VS Code Live Server Extension:
-
Play the Game:
- Use the left and right arrow keys to move the player cube across platforms.
- The platforms are generated ahead as you move, creating an endless path.
- Avoid falling off the platforms!
Further Enhancements
This is a basic example to get you started. Here are some ideas to expand the game:
- Textures and Materials: Apply textures to the player and platforms for a more polished look.
- Obstacles and Enemies: Introduce obstacles or enemies that the player must avoid or defeat.
- Jump Mechanic: Allow the player to jump to navigate gaps or reach higher platforms.
- Scoring System: Implement a score based on distance traveled or platforms successfully navigated.
- Sound Effects and Music: Add audio to enhance the gaming experience.
- Advanced Procedural Generation: Create more varied and complex environments with different platform types and arrangements.
Learning Resources
- Three.js Documentation: https://threejs.org/docs/
- Three.js Examples: https://threejs.org/examples/
- Tutorials:
Feel free to modify and expand upon this example to create a more intricate and engaging game. Happy coding!