In Three.js, objects are consistently displayed in a hierarchical manner, with each one appearing on top

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.

Answer №1

The root cause of the issue was traced back to the size of Earth's radius. Initially, I had set this value in meters as

const R_earth = 6.371009e6;

Since many calculations in the code are based on multiples of this figure, there was a potential for numerical instability. Switching to smaller units, like kilometers instead of meters, helped resolve the problem.

A big thank you to @Mugen87 for the assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop Scrolling in VueJS

I am currently facing a challenge in preventing scrolling only when the lightbox component is open. I prefer not to rely on any external libraries or plugins for this task. Within my App.vue file, I have included the "LightBox" component. Therefore, it se ...

What is the best way to locate this specific element?

<div class="ptp-item-container"> <div class="plan">New Text to Display!</div> <div class="price">200</div> <div class="bullet-item">some other text</div> <div class="cta"> <a class="button" ...

Is Your CanvasJS Chart Traveling in Reverse?

My charts are displaying dates in reverse order, can anyone help me figure out what's causing this issue? I've checked the documentation but couldn't find anything that would explain this problem. Link to documentation: Here is a screensh ...

Javascript navigation menu failing to accurately display all pages

As I continue to enhance my website at , I have encountered an issue with the menu functionality. The menu is dynamically generated through JavaScript, scanning a folder for pages and populating them into an array. While this system functions smoothly ove ...

Insert a JavaScript object into the rendered HTML using the componentDidMount lifecycle method

I'm trying to incorporate a JavaScript object into the template once the component has mounted for tracking purposes. Here is how I want the object to be rendered: var tracking = { pagename: 'page name', channel: 'lp&ap ...

After clicking on a specific href element with a designated class, trigger the display of a custom dialog styled using CSS

I recently added a unique class to certain links on my website. When these specific links are clicked, I want them to trigger a customized dialog box. My goal is to modify the CSS of this special dialog box. Only links with this particular class should ...

How to disable form submission using ENTER key in jQuery when alerts are present?

My form contains a text input field. To prevent the form from being submitted when ENTER key is pressed, I used this code snippet: jQuery("#inputTags").keydown(function(event) { if (event.keyCode == '13') { event.preventDefault() ...

Having trouble retrieving data from a remote URL with angucomplete-alt

Utilizing the angucomplete-alt directive for creating an autocomplete list through a get request. Successfully fetching results from the Github API: <div angucomplete-alt id="ex5" placeholder="Search projects" pause="500" selected-object="selectedProj ...

Deciding whether an item qualifies as a Map in JavaScript

I have been working on developing a function that will return true if the argument provided to it is an instance of a JavaScript Map. When we use typeof new Map(), the returned value is object and there isn't a built-in Map.isMap method available. H ...

Adding extra fields to an existing JSON response in a TypeScript REST API

I am in need of an additional column to be added to my response data. Currently, I am fetching data from multiple REST endpoints one by one and merging the results into a single JSON format to display them in an Angular Mat table. The columns that I want t ...

Ways to convert asynchronous operations of Node.js into synchronous operations in Node.js

Using node js, I am making multiple AWS API calls within a for loop. var prodAdvOptions = { host : "webservices.amazon.in", region : "IN", version : "2013-08-01", path : "/onca/xml" }; prodAdv = aws.createProdAdvCli ...

The proper method for redirecting the view after a successful AJAX request in a MVC application

Explanation of the Issue: I have added a search function to the header section of my MVC website. It includes an input text box and a 'Search' button. The Problem at Hand: Currently, I have incorporated an AJAX function in the shared master la ...

Transmitting an array through Socket.IO using the emit() method

I am currently developing an array in my socket io server and then transmitting it to the client. var roomList = io.sockets.manager.rooms; // creating a new Array to store the clients per room var clientsPerRoom = new Array(); //for (var i ...

Validation of VAT numbers using JavaScript instead of PHP

I came across an interesting function at this link that is used for checking VAT numbers in the EU. However, I am struggling to integrate it with my registration form. I would like to convert it into a JavaScript function so that I can validate the number ...

The initial dropdown menu in PHP coupled with Javascript fails to retain my chosen option

As a novice PHP programmer, I successfully created a double drop-down list from a MySQL database. The idea is to choose a claims hub in the first box and then select an attorney associated with that specific hub in the second box. However, I am facing an ...

Issue with my JavaScript code for customizing checkboxes: the else condition is not being triggered

I'm currently in the process of customizing my own version of "checkboxes" by styling label elements and moving the actual checkbox off-screen. This is the approach I decided to take based on the design and functionality requirements presented to me. ...

Whenever the ajax oncomplete event is triggered, Primefaces overrides the functionality of jquery, leading to

I have implemented a plugin for fixed table columns in my Primefaces project. The plugin is somewhat functional, but I am facing some issues. primefaces v6.1 jQuery v1.7.1 It works under the following conditions; p:dataTable with <p:ajax event="page ...

Animate the sliding of divs using the JavaScript animation function

I've designed some boxes that function similar to notifications, but now I want to smoothly slide them in from the left instead of just fading in. I know that I need to use .animate rather than .fadeIn to achieve this effect. The code snippet I&apos ...

Tips for Providing Real-Time Data for a Dynamic Chart in d3

I have a line chart sample from D3, and the issue I'm facing is that I need to continuously feed live data from a server at certain time intervals and use D3 to draw the chart based on this dynamic data. Despite my efforts to search for a solution, I ...

What methods can I use to design a splash screen using Vue.js?

I am interested in creating a splash screen that will be displayed for a minimum of X seconds or until the app finishes loading. My vision is to have the app logo prominently displayed in the center of the screen, fading in and out against a black, opaque ...