Ensure that an object is within the frustum by utilizing THREE.js

I've been experimenting with Three.js and have a canvas that I want to use as a GUI. To achieve this, I need to check if an object is within the camera's frustum.

Here is my current code snippet:

camera.updateMatrix();
camera.updateMatrixWorld();

const frustum = new THREE.Frustum();
const projScreenMatrix = new THREE.Matrix4();
projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );

frustum.setFromProjectionMatrix( camera.projectionMatrix );

if(frustum.containsPoint( mesh.position )){
    // do something...
};

The issue I'm facing is that frustum.containsPoint() keeps returning false. Any suggestions on what might be going wrong here?

Answer №1

Take note of the code being utilized in your project:

frustum.setFromMatrix( camera.projectionMatrix );

However, this may not be the ideal matrix for your needs. It is recommended to use the following instead:

frustum.setFromMatrix( new THREE.Matrix4().multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ) );

This information was provided as a solution in How to determine if plane is in Three.js camera Frustum

Answer №2

Three.js utilizes internal view frustum culling to optimize rendering by only rendering objects that are within the camera's range. As long as your bounding volumes are accurately calculated, you can determine whether an Object3D is inside the camera's view frustum by monitoring the Object3D.onBeforeRender callback during each frame.

Answer №3

My approach to determining if a mesh is within the camera view and doing so in under 100 milliseconds:

mesh.onBeforeRender = function() {
    if (mesh.userData.inViewID) clearTimeout(mesh.userData.inViewID);
    mesh.userData.inViewID = setTimeout(()=>{
        mesh.userData.inView = false;
        console.log("out of view");
    }, 100);
    if (!mesh.userData.inView) { 
        mesh.userData.inView = true;
        console.log("in view");
    }
}

Answer №4

With the latest update to version r166, there have been slight changes to the code that I wanted to share.

const frustum = new THREE.Frustum();

camera.updateMatrix();
camera.updateMatrixWorld();
mesh.updateMatrix();
mesh.updateMatrixWorld();

frustum.setFromProjectionMatrix(
new THREE.Matrix4().multiplyMatrices(
        camera.projectionMatrix,
        camera.matrixWorldInverse
    )
);

const intersectedMesh = frustum.intersectsObject(mesh);

if(intersectedMesh){
//Perform some action
}

Best regards,

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

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

Vue.JS: The central layout element and navigation system

I have a primary layout component (consists of a fixed top header and a left side menu with multiple links created using the router-link component) as well as a "dynamic" layout component that serves as the heart of the page. My goal is to change the cen ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

Is it a common occurrence for AJAX applications utilizing POST requests to encounter issues in Internet Explorer?

After some investigation, I have come across a bug in Internet Explorer that is causing intermittent failures for users running my application. This bug exists within the HTTP stack of IE and impacts all applications utilizing POST requests from this brows ...

What is the method for generating three inputs simultaneously in a single line?

I'm facing a challenge in my code where I want each line to contain only three input fields. Whenever I try to add a fourth input field, the first one remains on the previous line while the other three move to the next line. Oddly enough, this issue o ...

Change background according to URL query

My goal is to dynamically change background images based on a URL parameter, specifically the destination code. With numerous background images available, it's crucial to display the correct one depending on the URL string. For instance, if the URL re ...

When attempting to run npm run build for a Next.js application on an EC2 instance, it unexpectedly terminates on its own

While attempting to deploy my Next.js app on EC2, I encountered an issue where the npm run build command was being automatically killed. Suspecting it may be due to insufficient RAM, I switched to an instance type with 4GB of RAM (t3.medium), but the probl ...

Tips for dynamically adjusting an iframe's content size as the browser window is resized

Currently, I am in the process of building a website that will showcase a location on a map (not Google Maps). To achieve this, I have utilized an iframe to contain the map and my goal is for the map to adjust its width based on the width of the browser wi ...

Trying to access the label attribute of a select option in Vue.js?

Looking to retrieve the name attribute of a selected option in Vuejs. After experimenting with the value attribute, I found that it worked successfully. Below is the code I used: Tested code: <select id="countryselect" name="country" @change="onChange ...

Issue TS2349 occurs when attempting to use a combination of boolean and function types within union typing

In my class, there is a property called "isVisible" which can be either a boolean value or a function that returns a boolean. The code snippet below demonstrates what I am currently using. It works fine and achieves the desired result, but during compilat ...

What is the process for creating a new subdocument if it doesn't already exist, and then appending another subdocument below it?

On my mongoose schema, I have a user schema with a property named lastExams defined as follows: lastExams: [{ lecture: { type: String, required: true }, exams: [{ examID: {type: [mongoose.Schema.Types.Obj ...

Learn how to showcase the current date by utilizing JavaScript arrays and the getDate method!

I have been struggling to format the date as follows: "Today is Sunday, the 31st day of March in the year 2019." I am working with JavaScript in an HTML5 document. Below is the code I have so far, and I would appreciate any help. I prefer not to rely on ...

Compatibility with IE9: Using jQuery to send an AJAX POST request

I'm currently facing an issue with making a POST request from my website to a server that is not on the same domain. The functionality is working seamlessly on Chrome, Firefox, and IE10+, but I need to ensure it works on IE9 as well. Below is the cod ...

Is it possible to assign a type conditionally depending on the value of a boolean?

While grappling with this issue, the title question arose in my mind: How can I handle the situation where the library function getResponse returns { a: number } for Android phones and { b: number } for iOS phones? The code snippet below initially led to ...

Leveraging PCDLoader in APS Viewer with version 71 of three.js

Attempting to load a .pcd file format with PCDLoader from three.js has been unsuccessful for me. It seems like there may be an issue related to version compatibility. I have added the necessary scripts in the HTML: <script type="importmap"&g ...

The issue arises when attempting to make an Ajax request after changing the value of a cascading dropdown

Hey there! I'm currently working on a cascading drop-down feature where, upon change, I need to populate another field with data from the database. Unfortunately, every time I try to populate the drop-down, my AJAX call returns an error 500. I can&ap ...

What is the best way to tidy up a function within a useEffect hook?

When updating state within a useEffect hook while using async/await syntax, I encountered an error regarding the cleanup function. I'm unsure how to properly utilize the cleanup function in this scenario. Error: Warning - A React state update was att ...

Guide on utilizing jQuery/AJAX data with PassportJS

When I submit a login request using the form fields action="/login", method="post", everything works smoothly. This is similar to the code examples found either here or here. However, when I attempt to send the same information using jquery/ajax, passport ...

Can express middleware be tailored for each individual handler within the same route path?

I am seeking to create distinct routes under an /api path with varying middleware handlers, each allowing for different authentication methods. My initial approach was to nest these API routes under separate instances of the Router object using Express: c ...

Tips for transforming a string into a date using Angular

What is the best way to transform a string into a date in Angular13? Here's an example: str = '2022-06-09T22:00:00Z'; needs to be converted to a datetime format of mm/dd/yyyy --:-- -- ...