0% found this document useful (0 votes)
18 views3 pages

Three.js Solar System Simulation Code

This document is an HTML file that sets up a solar system simulation using Three.js. It creates a scene with a sun and two planets, Earth and Mars, which orbit around the sun while rotating on their axes. The simulation includes interactive camera controls and adjusts to window resizing.

Uploaded by

Abuzar Ali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views3 pages

Three.js Solar System Simulation Code

This document is an HTML file that sets up a solar system simulation using Three.js. It creates a scene with a sun and two planets, Earth and Mars, which orbit around the sun while rotating on their axes. The simulation includes interactive camera controls and adjusts to window resizing.

Uploaded by

Abuzar Ali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

<!

DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Solar System Simulation</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<!-- Include [Link] and, optionally, OrbitControls from a CDN -->
<script src="[Link]
<script src="[Link]
[Link]"></script>
<script>
// Set up the scene, camera, and renderer
const scene = new [Link]();
[Link] = new [Link](0x000000); // black background for space

const camera = new [Link](


75,
[Link] / [Link],
0.1,
1000
);
[Link].z = 50; // back the camera off so that the scene is visible

const renderer = new [Link]({ antialias: true });


[Link]([Link], [Link]);
[Link]([Link]);

// OrbitControls allow you to interactively rotate and zoom the camera view.
const controls = new [Link](camera, [Link]);
[Link] = true; // smooth out camera movements

// Create the Sun


const sunGeometry = new [Link](5, 32, 32);
const sunMaterial = new [Link]({ color: 0xffff00 });
const sun = new [Link](sunGeometry, sunMaterial);
[Link](sun);

// Create a point light at the Sun's location to simulate sunlight for other objects
const sunLight = new [Link](0xffffff, 2, 500);
[Link](0, 0, 0);
[Link](sunLight);

// Function to create a planet that orbits the sun


function createPlanet(radius, orbitDistance, color) {
// Create a pivot so that the planet can orbit the sun
const orbitGroup = new THREE.Object3D();
[Link](orbitGroup);

// Create the planet geometry and material


const planetGeometry = new [Link](radius, 32, 32);
const planetMaterial = new [Link]({ color, roughness: 1 });
const planet = new [Link](planetGeometry, planetMaterial);

// Position the planet along the x-axis relative to its orbit pivot
[Link].x = orbitDistance;
[Link](planet);

return { orbitGroup, planet };


}

// Create Earth and Mars as examples:


const earthData = createPlanet(2, 15, 0x2233ff); // a blue Earth
const marsData = createPlanet(1.5, 25, 0xff4500); // a reddish Mars

// Animation loop to simulate rotations and orbits


const animate = function () {
requestAnimationFrame(animate);

// Rotate the sun slowly on its axis


[Link].y += 0.005;

// Simulate the Earth's orbit by rotating its pivot group


[Link].y += 0.01;
// (Optional) add Earth’s self-rotation for extra realism:
[Link].y += 0.02;

// Simulate Mars’ orbit:


[Link].y += 0.008;
[Link].y += 0.02;

// Update controls and render the scene


[Link]();
[Link](scene, camera);
};

animate();

// Adjust the camera and renderer when the window is resized


[Link]("resize", () => {
[Link] = [Link] / [Link];
[Link]();
[Link]([Link], [Link]);
});
</script>
</body>
</html>

Common questions

Powered by AI

Resizing the window affects the simulation by altering the aspect ratio of the view, which could distort the visual representation if not managed. The implementation addresses this by listening for 'resize' events and updating the camera's aspect ratio and projection matrix accordingly. The renderer's size is also adjusted to match the new window dimensions, ensuring that the visual experience remains consistent and undistorted regardless of screen size changes .

The simulation ensures realistic behavior by implementing orbital and rotational mechanics using Object3D groups and animations. The Sun rotates slowly to simulate its axis rotation. The Earth and Mars orbit the Sun by rotating their corresponding orbit groups. Additionally, self-rotation is added to Earth and Mars to enhance realism. The use of a PointLight at the Sun's position to simulate sunlight, combined with materials that reflect light realistically, contributes to a more lifelike visualization .

Lighting in the simulation contributes to realism by simulating the effects of sunlight on celestial bodies. A PointLight is placed at the Sun's location, casting illumination that affects the appearance of materials like those on the planets. This setup imitates how the Sun would light up planets in space, providing visual clues about their size, distance, and movement through the interplay of light and shadow .

The JavaScript structure begins by initializing the scene, camera, and renderer, setting a black backdrop to simulate space. model components such as celestial bodies are created using functions like createPlanet, encapsulating properties like size, color, and orbit specifics. The animation loop running requestAnimationFrame ensures continuous updating of celestial motions, with individual rotations applied to each body. The scene is constantly updated and rendered, maintaining a dynamic simulation environment that reacts to window resizing through event listeners .

OrbitControls enhance user interaction by allowing users to rotate and zoom the camera around the 3D scene smoothly. This is achieved by enabling damping on the camera movements, which smooths out transitions and provides an interactive experience where users can explore the solar system from different perspectives .

The simulation incorporates Three.js to create a virtual environment where celestial bodies such as the Sun, Earth, and Mars are represented using 3D geometries and materials. The scene is set up with a black background to mimic space, utilizing a perspective camera for a 3D view. The Sun is implemented as a SphereGeometry with a MeshBasicMaterial to simulate its glowing appearance, further enhanced with a PointLight at its location to provide illumination. The Earth and Mars are created using the createPlanet function, which assigns them different sizes, orbit distances, and colors. These planets are part of Object3D groups that rotate to simulate orbital motion around the Sun. Additionally, each planet has animations for self-rotation, enhancing the realism of the simulation .

Planetary orbits and rotations are simulated using Object3D groups that act as invisible pivots, around which planets orbit the Sun. The animate function triggers these pivots to rotate, mimicking the actual orbit paths. Planetary self-rotation is also applied within the same animation loop, matching realistic diurnal cycles. This dual representation of orbital and axial rotations provides an authentic depiction of real-world celestial dynamics .

The rendering loop maintains continuous simulation by repeatedly calling requestAnimationFrame to execute the animate function. Within this function, celestial bodies' rotations and orbits are updated, and the renderer updates the scene to reflect these changes. This loop runs indefinitely, allowing for a smooth, ongoing animation that simulates real-time changes in the solar system .

Parameters for planet size, orbit distance, and rotational speeds are selected to balance visual clarity with realism in the simulation. While not necessarily to scale, these parameters are chosen to effectively differentiate celestial bodies and depict unique orbital characteristics. The Earth is larger and more distant than Mars to match their relative sizes and distances from the Sun, while rotational speeds are adjusted to convey real-world dynamism within the constraints of a simulation timeline that remains visually engaging .

Geometries and materials work together by defining the physical structure and surface appearance of planets. SphereGeometry is used for its consistent, spherical shape, suitable for representing celestial bodies. Materials like MeshStandardMaterial and MeshBasicMaterial define how light interacts with the planets, affecting their color and reflective properties. This combination creates visual realism by reflecting light to mimic natural planetary surfaces as perceived in space .

You might also like