Make a 3d visualiziation of solar system using babylon.js, provide complete code
- User
Make a 3d visualiziation of solar system using babylon.js, provide complete code
- Assistant
Creating a 3D visualization of the solar system using Babylon.js is a fun and educational project. Below is a complete, self-contained example that you can run in your browser. This example includes the Sun and the eight planets orbiting around it. For simplicity, the sizes and distances are scaled down to fit nicely within the scene.
Step 1: Set Up Your HTML File
Create an
index.htmlfile and include the following code:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>3D Solar System with Babylon.js</title> <!-- Include Babylon.js library from CDN --> <script src="https://cdn.babylonjs.com/babylon.js"></script> <!-- Optional: Include Babylon.js Loaders (if you plan to load external models or textures) --> <script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script> <style> /* Make the canvas full-screen */ html, body { overflow: hidden; width: 100%; height: 100%; margin: 0; padding: 0; } #renderCanvas { width: 100%; height: 100%; touch-action: none; } </style> </head> <body> <!-- Canvas for Babylon.js to render --> <canvas id="renderCanvas"></canvas> <script> // Wait until the DOM is fully loaded window.addEventListener('DOMContentLoaded', function() { // 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); // Add a camera to the scene and attach it to the canvas const camera = new BABYLON.ArcRotateCamera("Camera", BABYLON.Tools.ToRadians(45), BABYLON.Tools.ToRadians(60), 100, new BABYLON.Vector3(0, 0, 0), scene); camera.attachControl(canvas, true); // Add a hemispheric light to illuminate the scene const light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene); light.intensity = 0.7; // Create the Sun const sun = BABYLON.MeshBuilder.CreateSphere("sun", {diameter: 10}, scene); const sunMaterial = new BABYLON.StandardMaterial("sunMaterial", scene); sunMaterial.emissiveColor = new BABYLON.Color3(1, 0.8, 0.2); // Bright yellow sun.material = sunMaterial; // Planet data: name, size, distance from sun, color, orbital speed const planets = [ { name: "Mercury", size: 0.38, distance: 15, color: new BABYLON.Color3(0.5, 0.5, 0.5), speed: 0.04 }, { name: "Venus", size: 0.95, distance: 20, color: new BABYLON.Color3(1, 0.6, 0.2), speed: 0.015 }, { name: "Earth", size: 1, distance: 25, color: new BABYLON.Color3(0, 0.5, 1), speed: 0.01 }, { name: "Mars", size: 0.53, distance: 30, color: new BABYLON.Color3(1, 0.3, 0.2), speed: 0.008 }, { name: "Jupiter", size: 11.2, distance: 40, color: new BABYLON.Color3(1, 0.6, 0.3), speed: 0.002 }, { name: "Saturn", size: 9.45, distance: 50, color: new BABYLON.Color3(1, 0.8, 0.4), speed: 0.0015 }, { name: "Uranus", size: 4, distance: 60, color: new BABYLON.Color3(0.5, 1, 1), speed: 0.001 }, { name: "Neptune", size: 3.88, distance: 70, color: new BABYLON.Color3(0, 0, 1), speed: 0.0008 } ]; // Array to hold planet meshes and their orbital angles const planetMeshes = []; // Create planets planets.forEach(function(planet) { // Create planet mesh const mesh = BABYLON.MeshBuilder.CreateSphere(planet.name, {diameter: planet.size}, scene); // Create material const material = new BABYLON.StandardMaterial(planet.name + "Material", scene); material.diffuseColor = planet.color; mesh.material = material; // Position the planet at the initial distance along the X-axis mesh.position = new BABYLON.Vector3(planet.distance, 0, 0); // Add to the array with initial angle 0 planetMeshes.push({ mesh: mesh, distance: planet.distance, speed: planet.speed, angle: Math.random() * Math.PI * 2 }); // Optionally, add orbit lines const orbit = BABYLON.MeshBuilder.CreateTorus("orbit_" + planet.name, { diameter: planet.distance * 2, thickness: 0.05, tessellation: 64 }, scene); const orbitMaterial = new BABYLON.StandardMaterial("orbitMat_" + planet.name, scene); orbitMaterial.emissiveColor = new BABYLON.Color3(1, 1, 1); orbitMaterial.alpha = 0.3; orbit.material = orbitMaterial; }); // Create a simple animation loop scene.onBeforeRenderObservable.add(() => { planetMeshes.forEach(function(p) { // Update the angle based on speed p.angle += p.speed; // Update the position in XZ plane p.mesh.position.x = p.distance * Math.cos(p.angle); p.mesh.position.z = p.distance * Math.sin(p.angle); }); }); return scene; }; const scene = createScene(); // Register a render loop to repeatedly render the scene engine.runRenderLoop(function(){ scene.render(); }); // Watch for browser/canvas resize events window.addEventListener('resize', function(){ engine.resize(); }); }); </script> </body> </html>Step 2: Understanding the Code
Let's break down what this code does:
-
Including Babylon.js Library: The script includes Babylon.js from a CDN, which is necessary to use its functionalities.
-
Setting Up the Canvas: The
<canvas>element with the IDrenderCanvasis where Babylon.js will render the 3D scene. -
Creating the Engine and Scene:
- An engine is created to handle rendering.
- A scene is set up where all objects (Sun, planets, lights, camera) will reside.
-
Adding a Camera:
- An
ArcRotateCameraallows the user to rotate around the scene using mouse or touch inputs. - The camera is positioned at a distance that comfortably frames the entire solar system.
- An
-
Adding Light:
- A hemispheric light illuminates the scene, simulating ambient light from the sky.
-
Creating the Sun:
- A large sphere represents the Sun.
- The Sun has an emissive material to make it appear bright and self-illuminated.
-
Defining Planets:
- An array contains data for each planet, including name, size (radius), distance from the Sun, color, and orbital speed.
- Sizes and distances are scaled down for visualization purposes.
-
Creating Planet Meshes:
- For each planet, a sphere is created with the specified size and color.
- Each planet is initially positioned along the positive X-axis at its defined distance from the Sun.
- Optionally, orbit lines (toruses) are added to visualize the paths of the planets.
-
Animating the Orbits:
- Before each render, the position of each planet is updated based on its orbital speed.
- The planets move in circular orbits around the Sun by updating their X and Z positions using trigonometric functions.
-
Render Loop:
- The engine's render loop continuously renders the scene, updating planet positions to create the animation.
-
Responsive Design:
- The scene resizes automatically when the browser window size changes to maintain full-screen rendering.
Step 3: Running the Visualization
-
Save the File: Save the
index.htmlfile to a directory on your computer. -
Open in a Browser: Double-click the
index.htmlfile or open it in your preferred web browser (e.g., Chrome, Firefox). -
Interact with the Scene:
- Rotate: Click and drag the mouse to rotate the camera around the solar system.
- Zoom: Use the mouse scroll wheel or pinch gestures on a touchpad to zoom in and out.
- Pan: Right-click and drag to pan the camera.
Customizing the Visualization
Here are a few ideas to enhance and customize your solar system visualization:
-
Textures: Instead of solid colors, use textures to make the planets look more realistic. You can find free planet textures online. To apply a texture:
const material = new BABYLON.StandardMaterial(planet.name + "Material", scene); material.diffuseTexture = new BABYLON.Texture("path_to_texture.jpg", scene); mesh.material = material; -
Lighting Effects: Add a
PointLightat the Sun's position to simulate the light emitted by the Sun more realistically.const sunLight = new BABYLON.PointLight("sunLight", sun.position, scene); sunLight.intensity = 2; -
Planet Rotation: Make each planet rotate on its own axis to simulate day-night cycles.
scene.onBeforeRenderObservable.add(() => { planetMeshes.forEach(function(p) { // Existing orbital movement p.angle += p.speed; p.mesh.position.x = p.distance * Math.cos(p.angle); p.mesh.position.z = p.distance * Math.sin(p.angle); // Planet rotation p.mesh.rotation.y += 0.01; // Adjust rotation speed as needed }); }); -
Adding Moons: Similar to planets, you can add moons orbiting around their respective planets.
-
UI Elements: Add labels or information panels that display the name of the planet and other details when clicked or hovered.
Additional Resources
- Babylon.js Documentation: https://doc.babylonjs.com/
- Babylon.js Playground: https://playground.babylonjs.com/ – An online editor to experiment with Babylon.js code.
- 3D Models and Textures: Websites like NASA’s 3D Resources offer free models and textures.
Enjoy building and exploring your 3D solar system!
-