Can the ThreeJS element be seen?

I am facing a challenge in my ThreeJS application where the view automatically centers on an object if it is close to the center of the view and closer than a specified distance. While I have information about the latitude and longitude of all objects and the viewer (camera), I am unsure if there are obstacles like walls blocking the view.

Is there a way for ThreeJS to indicate if an object is visible from the camera?

I came across a potential solution in an older version of ThreeJS that referenced a webglObjects array, but I am unable to locate its equivalent in newer versions: https://github.com/mrdoob/three.js/issues/3627#issuecomment-20763458

While ThreeJS Frustum culling is available, it only confirms if the camera is correctly aligned and does not address potential obstructions in the view of the object.

Raycaster solutions are not suitable as the target object has dimensions, unlike a point.

Developing my own occlusion culling system seems daunting without any sample resources to guide me.

Are there any recommendations or suggestions to overcome this issue?

Answer №1

Hey there, I've come up with a solution that takes into account the possibility of an object being blocked from view if it's not directly in the camera's line of sight. Any feedback or suggestions are more than welcome! Hopefully, this code will be useful for someone down the road.

// This function determines whether a specific object obstructs the view of another object's origin point
// The variables threeScene and threeCamera are assumed to be initialized elsewhere in the script:
// threeScene = new THREE.Scene();
// threeScene.add(mesh);
// ...
// threeCamera = new THREE.PerspectiveCamera(...
// ...
var checkIfObjectBlocksView = function(objectName) {
  if (threeScene) {
    var obj = threeScene.getObjectByName(objectName);
    if (obj) {
      var dirVector = new THREE.Vector3();
      dirVector.subVectors(obj.position, threeCamera.position); 
      dirVector.normalize();                                      
      var raycaster = new THREE.Raycaster(threeCamera.position, dirVector);
      var intersections = raycaster.intersectObjects(threeScene.children, false); 

      if (intersections.length > 0) {
        for (var k=0; k<intersections.length; k++) {
          if ((intersections[k].object !== undefined) && (intersections[k].object['name'] !== objectName) &&
              (intersections[k].object['name'] !== '')) {
            // Object blocks the view of the target object
            return true;
          }
        }
      }

      // No obstructions found between the target object and the camera's view
      return false;
    }
  }

  // Scene is empty or specified object cannot be located
  return true;
};

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

Converting a JavaScript function to CoffeeScript, accepting jQuery's .map function and Selectors as parameters

I'm in the process of converting some JavaScript code into CoffeeScript and encountering an issue with a particular function. Here is the original functioning JS: $(".comformt_QA").change(function(){ var array = $(".comformt_QA").map(function() { ...

Maximizing Efficiency: Using a Single Prototype-Instance Across Multiple HTML Pages

I have defined some Javascript "Classes" in separate files using the Prototype function as shown below: function Playlist(id, name){ this.id = id; this.name = name; } Playlist.prototype.getid = function(){return this.id;} Playlist.prototype.getn ...

Steps to restrict input in a text area to only backspace and cursor movements

I'm in search of a jQuery function that restricts movements to only arrow keys and backspace within a textarea. However, there seems to be an issue with the arrow key movements not functioning correctly. function moveArrow(e){ if(e.which >= 3 ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

The server is unable to process the .get() request for the file rendering

Struggling with basic Express routing here. I want the server to render 'layout2.hbs' when accessing '/1', but all I'm getting is a 304 in the console. Here's the error message: GET / 304 30.902 ms - - GET /style.css 304 3.3 ...

Passing an array through ajax from PHP to JavaScript using a properly formatted JSON structure

I began with an array generated by PHP and retrieved via ajax, which had the following structure: Array ( [0] => {id:"12",from:"09:00:00",to:"15:00:00"} [1] => {id:"13",from:"08:00:00",to:"10:00:00"} [2] => {id:"12",from:"15:00:00",to ...

Start up a server using Angular along with Node.js and Express framework

I am encountering an issue with configuring Express as a server in my Angular application. The app loads without any issues when accessing the HOME route, but when trying to access another route, I receive an error message: Cannot GET / This is how I hav ...

Having issues with AJAX and .change() function not functioning correctly?

I am working on two drop-down menus. The first menu displays the provinces in the country, and when a province is selected, the second menu should show the districts within that province. The following code is for displaying the provinces: $(document).re ...

Obtain the refined information from a UiGrid table

Is there a way to loop through the filtered rows in an uigrid? I am aware that we can get the filtered rows using the following code: var filteredData = $scope.gridApi.core.getVisibleRows($scope.gridApi.grid); However, I need to iterate through it and cr ...

What is the best way to ensure the initial item in an accordion group remains open by default when using NextJS?

I've successfully developed an accordion feature in NextJS from scratch and it's functioning flawlessly. However, I am looking to have the first item of the accordion open automatically when the page loads. Can anyone guide me on how to make this ...

Gathering information in a non-blocking manner with $.ajax() in rails version 3.2.2

Currently, I am delving into the realm of asynchronous data retrieval in my Rails 3.2.2 project. As a newcomer to both JavaScript and jQuery, I've stumbled upon an issue where JavaScript is unable to fetch data from a different domain server. To overc ...

What steps do I need to take to successfully implement a $.fn. function that runs automatically when it is called?

I'm struggling with the following piece of code: function init() { var $contentButtonPanel: JQuery = $('#content-button-panel') $contentButtonPanel .find('.arbo .toggle, .collapsible-list li:has(ul) > ...

What is the process of transforming this jQuery script into AngularJS code?

Currently I am facing a situation where I am utilizing Angular1.x for a project. On a specific subpage, there are small clickable images along with some additional content below these images. The requirement is that only the images should be visible init ...

How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneousl ...

Showing Div content from AngularJS response

Query -- I am currently using a Controller in AngularJs that performs an $http.get request and receives data as a response. The data includes an HTML DivID and corresponding classes. How can I extract this DivID from the response and transfer it to the vi ...

Align elements on the left side with some space between them

Having trouble displaying a list of images inline within a div. When I float them left, they leave a lot of space and do not display properly. Can anyone help me with this issue? See screenshot below: Here is my html code: <div class="col75"> & ...

Typescript having issues compiling to commonjs/es2015 accurately

I currently have Node v14.5.0 installed and I'm using ts-node-dev in my development environment However, I am encountering an error every time I try to compile to JS. Initially, I attempted with the following tsconfig: "target": "es5& ...

What is the best way to maintain the toggleClass event state once an ajax call has been made?

If I have the HTML code below <div class="row"> <div class="link grey"> <a href="#">Link</a> </div> </div> <div class="row"> <div class="link"> <a href="#">Link</a> </div> & ...

"An issue has arisen in MongoDB when attempting to save data, resulting in an error message

Having trouble inserting data into MongoDB with Node.js. Encountering an error in the final line of code. Here are the execution logs: { _id: 56e90c1292e69900190954f5, nfs: [ 'ebdp1', 'ebdp2', 'ebdp3', 'ebdp4' ], s ...

Chrome is throwing a syntax error with an unexpected token in jQuery replaceWith

jQuery('div#top').replaceWith('<div id="top"> </div>') When I try to replace the entire content of the top div using jQuery, Chrome gives me an error: "Uncaught SyntaxError: Unexpected token" on the first line. I'm no ...