js实现宇宙


JavaScript 实现宇宙模拟
使用 JavaScript 可以创建简单的宇宙模拟,包括粒子系统、引力效应和星系运动。以下是几种实现方式:
使用 Canvas 绘制粒子系统
const canvas = document.getElementById('universe');
const ctx = canvas.getContext('2d');
const particles = [];
class Particle {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.size = Math.random() * 3 + 1;
this.speedX = Math.random() * 2 - 1;
this.speedY = Math.random() * 2 - 1;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x < 0 || this.x > canvas.width) this.speedX *= -1;
if (this.y < 0 || this.y > canvas.height) this.speedY *= -1;
}
draw() {
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
function init() {
for (let i = 0; i < 100; i++) {
particles.push(new Particle());
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(particle => {
particle.update();
particle.draw();
});
requestAnimationFrame(animate);
}
init();
animate();
使用 Three.js 创建 3D 宇宙
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.SphereGeometry(0.5, 32, 32);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
const starsGeometry = new THREE.BufferGeometry();
const starsMaterial = new THREE.PointsMaterial({ color: 0xffffff });
const starsVertices = [];
for (let i = 0; i < 10000; i++) {
const x = (Math.random() - 0.5) * 2000;
const y = (Math.random() - 0.5) * 2000;
const z = (Math.random() - 0.5) * 2000;
starsVertices.push(x, y, z);
}
starsGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starsVertices, 3));
const stars = new THREE.Points(starsGeometry, starsMaterial);
scene.add(stars);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
sphere.rotation.x += 0.01;
sphere.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
实现引力物理效果
class Body {
constructor(x, y, mass) {
this.x = x;
this.y = y;
this.mass = mass;
this.vx = 0;
this.vy = 0;
this.ax = 0;
this.ay = 0;
}
applyForce(other) {
const dx = other.x - this.x;
const dy = other.y - this.y;
const distSq = dx * dx + dy * dy;
const dist = Math.sqrt(distSq);
const force = (this.mass * other.mass) / distSq;
const fx = (dx / dist) * force;
const fy = (dy / dist) * force;
this.ax += fx / this.mass;
this.ay += fy / this.mass;
}
update() {
this.vx += this.ax;
this.vy += this.ay;
this.x += this.vx;
this.y += this.vy;
this.ax = 0;
this.ay = 0;
}
}
使用现有库简化开发
- matter.js:2D 物理引擎
- cannon.js:3D 物理引擎
- p5.js:简化创意编码
- Babylon.js:高级 3D 引擎
这些方法展示了从简单到复杂的宇宙模拟实现方式,可以根据需求选择适合的技术方案。






