Feat: added a sun and earth orbiting it in vanilla.

This commit is contained in:
anshk 2026-03-25 17:34:44 +05:30
parent 1e79754534
commit a4044c47a3
2 changed files with 46 additions and 18 deletions

View File

@ -3,10 +3,11 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>My first three.js app</title> <title>Solar System</title>
<style> <style>
body { body {
margin: 0; margin: 0;
background: white;
} }
</style> </style>
</head> </head>

View File

@ -1,25 +1,52 @@
import * as THREE from 'three'; import * as THREE from "three"
const scene = new THREE.Scene(); const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer(); const camera = new THREE.PerspectiveCamera(
renderer.setSize(window.innerWidth, window.innerHeight); 75,
renderer.setAnimationLoop(animate); window.innerWidth / window.innerHeight,
document.body.appendChild(renderer.domElement); 0.1,
1000
)
camera.position.z = 15
const geometry = new THREE.BoxGeometry(1, 1, 1); const renderer = new THREE.WebGLRenderer()
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); renderer.setSize(window.innerWidth, window.innerHeight)
const cube = new THREE.Mesh(geometry, material); renderer.setClearColor(0xffffff, 1)
scene.add(cube); document.body.appendChild(renderer.domElement)
camera.position.z = 5; const light = new THREE.PointLight(0xffffff, 2)
light.position.set(0, 0, 0)
scene.add(light)
function animate(time) { // Sun
const sunGeometry = new THREE.SphereGeometry(2, 32, 32)
const sunMaterial = new THREE.MeshBasicMaterial({ color: "yellow" })
const sunMesh = new THREE.Mesh(sunGeometry, sunMaterial)
scene.add(sunMesh)
cube.rotation.x = time / 2000; // Earth Orbit Group (pivot)
cube.rotation.y = time / 1000; const earthOrbit = new THREE.Group()
sunMesh.add(earthOrbit)
renderer.render(scene, camera); // Earth
const earthGeometry = new THREE.SphereGeometry(1, 32, 32)
const earthMaterial = new THREE.MeshStandardMaterial({ color: "blue" })
const earthMesh = new THREE.Mesh(earthGeometry, earthMaterial)
// distance from sun
earthMesh.position.x = 5
earthOrbit.add(earthMesh)
// Animation
function animate() {
requestAnimationFrame(animate)
earthOrbit.rotation.y += 0.01 // orbit
earthMesh.rotation.y += 0.05 // spin
renderer.render(scene, camera)
} }
animate()