For the past couple of weeks, I've been engrossed in creating a solar system model using Three.js. After following tutorials and documentation, I successfully created a working model of the solar system. However, I encountered an issue when trying to zoom in on a specific planet upon clicking it. While the code works fine for the stationary sun, it fails to focus on the clicked planet correctly as it always zooms back to its initial empty position.
To simulate the orbiting or revolution of the planets around the sun, I created invisible parent objects positioned at the sun's location and rotated them accordingly in the animate() function. This approach made the planet revolution work smoothly, but the position of the planets remained unchanged. Even after attempting to use the update matrix function, the issue persists.
I devised a function that takes the initial position of the planet, the distance between the sun/parent object and the planet, the angular speed (rotation speed) of the respective parent object, and the number of times the rotatey function was called in the animate() function. There seems to be an issue with this function or perhaps my overall approach to solving the problem. Any help in rectifying this function or suggesting an alternative way to determine the object's position would be greatly appreciated.
function calculateCurrentPosition(initialPos, distance, angularSpeed, time) {
console.log(initialPos, distance, angularSpeed, time);
if (time === 0) {
return initialPos;
}
var currentAngle = angularSpeed * time;
var currentX = initialPos.x + distance * Math.cos(currentAngle);
var currentZ = initialPos.z + distance * Math.sin(currentAngle);
return { x: currentX, y: initialPos.y, z: currentZ };
}
The movement occurs along the x-z plane, therefore the y-coordinate remains constant.
The code snippet used to create the planet object is as follows:
function createPlanete(size, texture, position, ring) {
const geo = new THREE.SphereGeometry(size, 30, 30);
const mat = new THREE.MeshStandardMaterial({
map: textureLoader.load(texture)
});
const mesh = new THREE.Mesh(geo, mat);
const obj = new THREE.Object3D();
obj.add(mesh);
if(ring) {
const ringGeo = new THREE.RingGeometry(
ring.innerRadius,
ring.outerRadius,
32);
const ringMat = new THREE.MeshBasicMaterial({
map: textureLoader.load(ring.texture),
side: THREE.DoubleSide
});
const ringMesh = new THREE.Mesh(ringGeo, ringMat);
obj.add(ringMesh);
ringMesh.position.x = position;
ringMesh.rotation.x = -0.5*Math.PI;
}
scene.add(obj);
mesh.position.x = position;
return {mesh, obj}
}
If you require any additional information regarding the code or have further questions, feel free to ask.