Using HTML + JS and babylon.js create a 3d scene where our character can moves, provide…
- User
Using HTML + JS and babylon.js create a 3d scene where our character can moves, provide full code in one file
- Assistant
Sure! Below is a complete HTML file that uses Babylon.js to create a simple 3D scene where you can control a character (represented by a box) using the W, A, S, and D keys for movement. This example includes camera setup, lighting, ground plane, and basic character movement with smooth controls.
Complete HTML + JavaScript Code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Babylon.js 3D Scene with Moving Character</title> <style> /* Ensure the canvas takes up the full screen */ html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; } #renderCanvas { width: 100%; height: 100%; touch-action: none; } </style> <!-- Include Babylon.js from CDN --> <script src="https://cdn.babylonjs.com/babylon.js"></script> <!-- Optional: Include Babylon.js loaders if you plan to load external models --> <script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script> </head> <body> <!-- Canvas element where the scene will be rendered --> <canvas id="renderCanvas"></canvas> <script> // Get the canvas element const canvas = document.getElementById("renderCanvas"); // Generate the Babylon 3D engine const engine = new BABYLON.Engine(canvas, true); // Create the scene const createScene = function () { const scene = new BABYLON.Scene(engine); // Set gravity for the scene (optional, useful if using physics) scene.gravity = new BABYLON.Vector3(0, -0.9, 0); scene.collisionsEnabled = true; // Create a Universal Camera (you can also use UniversalCamera for better controls) const camera = new BABYLON.UniversalCamera("UniversalCamera", new BABYLON.Vector3(0, 5, -10), scene); camera.attachControl(canvas, true); camera.speed = 0.5; camera.inertia = 0.1; // Enable camera collisions (optional) camera.checkCollisions = true; // Create a hemispheric light to light up the scene const light = new BABYLON.HemisphericLight("hemiLight", new BABYLON.Vector3(0, 1, 0), scene); light.intensity = 0.7; // Create a ground plane const ground = BABYLON.MeshBuilder.CreateGround("ground", {width: 50, height: 50}, scene); ground.position.y = 0; ground.checkCollisions = true; // Apply a simple material to the ground const groundMaterial = new BABYLON.StandardMaterial("groundMat", scene); groundMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5); ground.material = groundMaterial; // Create a simple character (a box) const character = BABYLON.MeshBuilder.CreateBox("character", {height: 2, width: 1, depth: 1}, scene); character.position = new BABYLON.Vector3(0, 1, 0.5); // Slightly above the ground character.checkCollisions = true; // Apply a material to the character const charMaterial = new BABYLON.StandardMaterial("charMat", scene); charMaterial.diffuseColor = new BABYLON.Color3(0, 0, 1); // Blue color character.material = charMaterial; // Enable physics (optional, requires Cannon.js or Oimo.js) // Uncomment the lines below if you want to use physics /* scene.enablePhysics(new BABYLON.Vector3(0, -9.81, 0), new BABYLON.CannonJSPlugin()); character.physicsImpostor = new BABYLON.PhysicsImpostor(character, BABYLON.PhysicsImpostor.BoxImpostor, { mass: 1 }, scene); ground.physicsImpostor = new BABYLON.PhysicsImpostor(ground, BABYLON.PhysicsImpostor.BoxImpostor, { mass: 0 }, scene); */ // Movement variables const inputMap = {}; scene.actionManager = new BABYLON.ActionManager(scene); // Listen for keyboard events scene.actionManager.registerAction(new BABYLON.ExecuteCodeAction(BABYLON.ActionManager.OnKeyDownTrigger, function (evt) { inputMap[evt.sourceEvent.key] = evt.sourceEvent.type == "keydown"; })); scene.actionManager.registerAction(new BABYLON.ExecuteCodeAction(BABYLON.ActionManager.OnKeyUpTrigger, function (evt) { inputMap[evt.sourceEvent.key] = evt.sourceEvent.type == "keydown"; })); // Register a before render function to handle continuous input scene.onBeforeRenderObservable.add(() => { // Define movement speed const speed = 0.1; if (inputMap["w"] || inputMap["ArrowUp"]) { // Move forward character.moveWithCollisions(new BABYLON.Vector3(0, 0, speed)); } if (inputMap["s"] || inputMap["ArrowDown"]) { // Move backward character.moveWithCollisions(new BABYLON.Vector3(0, 0, -speed)); } if (inputMap["a"] || inputMap["ArrowLeft"]) { // Move left character.moveWithCollisions(new BABYLON.Vector3(-speed, 0, 0)); } if (inputMap["d"] || inputMap["ArrowRight"]) { // Move right character.moveWithCollisions(new BABYLON.Vector3(speed, 0, 0)); } // Optional: Make the camera follow the character camera.position.x = character.position.x; camera.position.z = character.position.z - 10; camera.setTarget(character.position); }); return scene; }; const scene = createScene(); // Render the scene engine.runRenderLoop(function () { scene.render(); }); // Resize the engine on window resize window.addEventListener("resize", function () { engine.resize(); }); </script> </body> </html>Features and Explanation
-
Basic Setup:
- Canvas: The
<canvas>element withid="renderCanvas"is where the 3D scene is rendered. - Babylon.js: The library is included via CDN for easy access.
- Styling: The canvas is styled to take up the full browser window.
- Canvas: The
-
Scene Creation:
- Engine and Scene: Initializes the Babylon.js engine and creates a scene.
- Camera: A
UniversalCamerais used for better control. It's positioned initially at(0, 5, -10)and attached to the canvas for user interaction. - Lighting: A
HemisphericLightilluminates the scene with a soft light from above. - Ground: A large ground plane is created to serve as the floor. It has collision detection enabled to prevent the character from falling through.
- Character: Represented by a blue box (
MeshBuilder.CreateBox). It's positioned slightly above the ground to simulate being on the surface.
-
Movement Controls:
- Input Handling: Keyboard inputs are captured using Babylon's
ActionManagerand stored in theinputMapobject. - Continuous Movement: The
onBeforeRenderObservableis used to apply movement based on the keys pressed. This allows for smooth and continuous movement as keys are held down. - Directions:
- W / Arrow Up: Move forward.
- S / Arrow Down: Move backward.
- A / Arrow Left: Move left.
- D / Arrow Right: Move right.
- Collision Detection:
moveWithCollisionsensures the character does not pass through the ground or other collidable objects.
- Input Handling: Keyboard inputs are captured using Babylon's
-
Camera Follow (Optional):
- The camera's position is updated each frame to follow the character from behind, maintaining a consistent view.
-
Physics (Optional):
- Commented out physics integration using Cannon.js or Oimo.js is provided. If you wish to enable realistic physics (like gravity, jumping, etc.), you can integrate a physics engine and uncomment the related sections.
Running the Code
-
Save the Code:
- Save the above code into an HTML file, for example,
index.html.
- Save the above code into an HTML file, for example,
-
Open in Browser:
- Open the
index.htmlfile in a modern web browser (e.g., Chrome, Firefox).
- Open the
-
Interact:
- Use the W, A, S, and D keys or the arrow keys to move the character around the scene.
Customization Tips
-
Character Model:
- Replace the simple box with a more complex 3D model using Babylon.js loaders if desired.
-
Textures and Materials:
- Apply different materials or textures to the ground and character for a more visually appealing scene.
-
Additional Objects:
- Add more meshes (like trees, buildings, etc.) to enrich the environment.
-
Advanced Controls:
- Implement features like jumping, running, or even animations for the character for a more dynamic experience.
-
Lighting and Shadows:
- Enhance the scene with additional lights and shadows for depth and realism.
This example serves as a foundational starting point. Babylon.js is a powerful library with extensive capabilities, so feel free to explore its documentation and add more features to your 3D scenes!
-