As a newcomer to JavaScript and Three.js, I managed to write some code that successfully renders a sphere representing Earth and a smaller sphere as a Satellite in orbit. However, a perplexing issue arises when the Satellite passes behind Earth – it remains visible on top of Earth.
// Set up Renderer
const renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor(0x000000, 1);
document.body.appendChild( renderer.domElement );
// Create Scene
const scene = new THREE.Scene();
// Establish Camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100.0 * R_earth);
camera.position.z = 4.0 * R_earth;
camera.position.y = 1.0 * R_earth;
camera.lookAt(0,0,0);
scene.add(camera);
// Earth Mesh
const earth_geom = new THREE.SphereGeometry(R_earth, 32, 32);
const earth_mat = new THREE.MeshPhongMaterial({color: 0x999999});
const earth_mesh = new THREE.Mesh(earth_geom, earth_mat);
scene.add(earth_mesh);
// Satellite Mesh
const sat = new Satellite(2.0 * R_earth, 0.0, Math.PI/2.0, 0.0, 0.0, 0.0);
const sat_geom = new THREE.SphereGeometry(0.1 * R_earth, 32, 32);
const sat_mat = new THREE.MeshLambertMaterial({ color: 0xff0000 });
const sat_mesh = new THREE.Mesh(sat_geom, sat_mat);
scene.add(sat_mesh);
// Ambient Light Source
const ambient_light = new THREE.AmbientLight(0xf1f1f1, 1);
scene.add(ambient_light);
// Spot Light Source
const spot_light = new THREE.DirectionalLight(0xffffff);
spot_light.position.set(100 * R_earth, 100 * R_earth, 100 * R_earth);
scene.add(spot_light);
// Rendering Loop
var t = 0.0;
function render() {
t += 100.0;
requestAnimationFrame(render);
const sat_pos = sat.position(t);
sat_mesh.position.x = sat_pos.get([0]);
sat_mesh.position.y = sat_pos.get([1]);
sat_mesh.position.z = sat_pos.get([2]);
renderer.render(scene, camera);
}
render();
The Satellite
class is stored in a separate file and handles the orbit mechanics equations to retrieve the Satellite's position vector at time t
. The positioning of the objects in space has been confirmed, ruling out any discrepancies there.
Research yielded the idea of render order, a concept I am now somewhat acquainted with despite lacking a background in computer graphics. However, the solutions I found focused on enforcing a specific render order to keep one object consistently on top of another. In this case, I require the Satellite to be concealed behind Earth, which unfortunately is not happening.