Identify the visibility status of a mesh that may be obscured by an object

I am currently working on a project that involves a scene with an Object3D representing a globe and multiple mesh elements that represent points on the globe. To enable user interaction, I am using OrbitControls. In addition to this, I am attaching HTMLElements to these points on the globe. However, since a globe is essentially a sphere, there might be instances where the points are not visible to the camera due to being placed on the backside of the object.

I am looking for a way to determine whether a point is visible to the camera or hidden by the object. If a point is not visible, I want to hide the corresponding HTMLElement based on the visibility of the mesh. The position of the HTMLElement is updated during render, so I believe this check should also take place during rendering:

private render() {
   this.renderer.render(this.scene, this.camera);

   this.points.forEach(({ label, mesh }) => {
      const screen = this.toScreenPosition(mesh);
      label.style.transform = `translate3d(${screen.x - 15}px, ${screen.y}px, 0)`;
   });

   this.requestId = window.requestAnimationFrame(this.render.bind(this));
}

The following code snippet works within the render function:

this.points.forEach(({ label, mesh }) => {
    const screen = this.toScreenPosition(mesh);
    label.style.transform = `translate3d(${screen.x - 15}px, ${screen.y}px, 0)`;

    const direction = new Vector3();
    direction.copy(mesh.position).sub(this.camera.position).normalize();
    this.raycaster.set(this.camera.position, direction);
    const intersections = this.raycaster.intersectObject(this.scene, true);
    const intersected = intersections.length > 0 ? intersections[0].object.uuid === mesh.uuid : false;

    if (intersected && label.style.opacity === "0") {
        label.style.opacity = "1";
    } else if (!intersected && label.style.opacity === "1") {
        label.style.opacity = "0";
    }
});

Answer №1

Here is a foolproof algorithm consisting of two simple steps:

  • To begin with, ensure that the specified point falls within the view frustum. For step-by-step guidance on how to achieve this, refer to: three.js - check if object is still in view of the camera.
  • If the initial test yields positive results, proceed to determine whether the point is obstructed by any 3D objects. The standard practice for conducting this evaluation involves performing a line-of-sight assessment. This entails setting up a raycaster originating from the camera's location and pointing towards the designated point. Subsequently, assess whether any 3D entities intersect with this visual trajectory. If no intersections are detected, then the point remains unobstructed. Conversely, if there are intersections present, it indicates that the point is obscured, thereby allowing you to conceal the corresponding label.

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

Issue encountered with mouse handling on SVG elements that overlap is not functioning as anticipated

I am working with multiple SVG path elements, each contained within a parent SVG element, structured like this: <svg class="connector" style="position:absolute;left:277.5px;top:65px" position="absolute" pointer-events:"none" version="1.1" xmlns="http:/ ...

State dropdown in Angular dynamically updates based on the country selected

I am in search of a contextual state dropdown menu that is linked to the country, ensuring only relevant states are displayed. I have explored these two solutions for guidance in my project. Angularjs trigger country state dependency angularjs dependant ...

Tips for toggling the visibility of a custom video-js component when the user is inactive

I am currently utilizing VideoJS with React and I have created a custom title bar component using the videojs-overlay feature. My goal is to make the title bar fade out when the user is inactive (not moving the mouse) and fade back in as they move the mous ...

Adjust the default color for the icon in the v-text-field type=date using Vuetify

I need to filter records between two dates, displaying data retrieved from the backend. Instead of following the traditional method outlined in Vuetify's date pickers documentation or using the CodePen example: Vuetify v-text-field Date Picker on Cod ...

Divide the identical elements and distinct elements from a provided array into two separate arrays storing unique elements and recurring elements

Can anyone help me with this query? I have an array of objects that need to be separated into repeating and non-repeating objects based on the segments they belong to, each in a separate array. For example- [ {name:"abc",id:1,segments:[1,2]}, {n ...

Can a reducer be designed to accommodate varying states dynamically?

Welcome to my React Application for ages 16 and above, featuring Redux. Within my bookRoom.js file, I have a component called bookRoom which is responsible for rendering a single rectangle on the screen, symbolizing a room. You can see a sample render of ...

Looking to remove a task from an array of objects with the help of Sequelize?

I am facing an issue with updating my task array in the database using Sequelize. Despite finding the index of the task to be deleted and updating the tasks array, the changes are not reflected in the database. Below is my code snippet: var idx = 0; for ...

Unable to change placeholder in Material UI's Select Form

I'm having trouble modifying my SelectionForm. I need to update the color of the placeHolder image from red to a different color, but I can't find any properties or props on the material ui Docs to do so. Can someone assist me with this? https:/ ...

Angular/JS encountered a premature end of program unexpectedly

I am taking my first steps in the world of web development with Angular (and JavaScript in general). I have been trying to rewrite some basic and common examples using Angular. One thing I attempted was to display a simple message using data binding. This ...

"Extracting regular expressions between the penultimate and ultimate characters

I'm struggling with a simple regex question. I want to extract text between two specific characters: - and ~ Here's my string: Champions tour - To Win1 - To Win2 ~JIM FURYK Currently, when I use this regex pattern: \-([^)]+\~), it mat ...

Connecting Websockets in AngularJs for Message Binding

I've hit a roadblock with my mini project, and I have a hunch it's something simple... My challenge is binding websocket messages to an Angular datamodel, but I can't seem to make it work... Here is my controller and some HTML to display t ...

Show the advancement of a process as it runs in a pop-up window

Currently, I am working on revamping a webpage to give it a more modern look. However, I'm encountering some challenges when trying to add simple functionality to a modal window. On the webpage, users upload a file, and upon clicking submit, a shell ...

Dragging the mouse outside of an element after clicking inside

I've come across a common issue, but unfortunately haven't been able to find a solution yet. window.onload = function (e) { var foo = document.getElementById('foo'); foo.addEventListener('click', function(e) { ...

Is there a way to identify a location in close proximity to another location?

With a position at (9,-3), I am looking to display all positions surrounding it within a square red boundary. However, I am struggling to find the algorithm to accomplish this task. Any help or alternative solutions would be greatly appreciated. Thank you ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

Discover the secret to smoothly scrolling to an element in ReactJs

Currently, I am in the process of constructing a Single Page Application (SPA) using React and one key functionality I need to implement is navigation that scrolls to specific sections on the page when clicked. This behavior is similar to how anchor tags w ...

Encountering Undefined Object Error in Angular Framework

I just completed an upgrade to Angular and encountered an issue with the error message 'object is possibly undefined'. I have tried multiple solutions after doing some research online, including using 'if' statements, null coalescing, i ...

Unable to use NodeJS await/async within an object

I'm currently developing a validation module using nodeJs and I'm facing difficulties understanding why the async/await feature is not functioning correctly in my current module. Within this module, I need to have multiple exports for validation ...

Using Vue.js to share events and data across various components

I am currently working on an application that features a Google map with a places autocomplete controller, similar to the example provided by Google at this link. Whenever an address is searched or selected, or when the map bounds are changed, I trigger a ...

Strategies for resolving duplicate jQuery code in my project

Trying to simplify my jQuery code that handles video selection and playback functionality. Users can click on a thumbnail or button to play a specific video, with the title of the video changing accordingly. Despite achieving the desired outcome, the cur ...