Finding the exact x and y coordinates of an object within the camera's frame

I'm currently working on figuring out the exact location (x, y, z coordinates) of an object (a BoxGeometry) in the world in reference to the screen (frustum) rather than the world itself. While the frustum.intersectsObject(…) method provides a Boolean result, I am interested in determining the quadrant ([-x,y],[x,y],[x,-y],[-x,-y]) where a box is situated relative to the camera (the red lines in the provided screenshot follow the camera, not the scene). The current setup functions well as long as the camera remains unrotated (room.children[i].position.x), but fails when the camera undergoes rotation.

It seems that elements are being detected in

if (frustum.intersectsObject(room.children[i])) {
that shouldn't be. (Refer to the image below for clarification)

Since I'm relatively new to three.js, it's likely there's a straightforward method to achieve this which I haven't discovered yet. If such a solution doesn't exist, what would be the simplest approach to implement this functionality? Thanks for your help!

    function onDocumentKeyDown(event) {
        event.preventDefault();
        var frustum = new THREE.Frustum();
        frustum.setFromMatrix(new THREE.Matrix4().multiply(camera.projectionMatrix));
        for (var i = 0; i < room.children.length; i++) {
            if (frustum.intersectsObject(room.children[i])) {
                var XYZ=new THREE.Vector4();
                XYZ.copy(room.children[i].position).applyMatrix4(camera.matrixWorldInverse);
                console.log(i, 'left', frustum.intersectsObject(room.children[i]), XYZ.x,XYZ.y,XYZ.z,XYZ.w, room.children[i].material.emissive.getHex());
                    if (XYZ.x < 0 && XYZ.y > 0 && (event.keyCode === 103 || event.keyCode === 13) ) {
                        if (room.children[i].material.emissive.getHex() !== 255) {
                            $('#score').text(score++);
                            room.children[i].material.emissive.setHex(0x00ff00);
                            console.log(frustum);
                            console.log(i, 'WHAT ARE THE BOUNDING BOX COORDINATES OF THIS BOX????');
                        }
                }
            }
        }
    }

https://i.sstatic.net/oI8FI.png

Answer №1

Have you checked out the `Vector3.project( camera )` method? It seems like it could be the solution you are searching for. By using this method, you can obtain the object's position in normalized device coordinates, where the values range from -1 to 1 in both the x and y directions.

vector.set( x, y, z ) // or vector.copy( ...)
vector.project( camera )
if ( vector.x <= 0 ) {
    ...
}

It is speculated that the condition should evaluate to true if the object is located in the left half of the view, although further testing is necessary.

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

Parse a string and generate an array using regular expressions in JavaScript/Node.js

I'm currently working on coding in JavaScript to extract an array of elements after splitting using a regular expression. var data = "ABCXYZ88"; var regexp = "([A-Z]{3})([A-Z]{3}d{2})"; console.log(data.split(regexp)); The current output is [ &a ...

What is the best way to incorporate child nodes when selecting dynamically generated elements through JavaScript?

Currently, I have buttons being dynamically generated on the page using plain JavaScript. For example: <button class="c-config__option c-config__option--button c-config__option--pack" data-index="0"> Item 1 <span>Subtext</span> ...

Using jQuery functions on inputs within a Bootstrap Modal

I've encountered an issue with my jQuery functions that validate input fields based on a regex pattern. Everything works smoothly when the form is displayed on a regular page, but as soon as I try to implement it within a Bootstrap Modal, the validati ...

Masonry ajax loading is not functioning properly

My images are supposed to load via ajax, but I am experiencing some issues. Sometimes it works perfectly fine, but most of the time they overlap each other like in this example. Where did I go wrong? Once I figure this out, I'll be able to refactor my ...

Tips for creating a responsive layout to ensure that H2 achieves its optimal font size in a one-line DIV

Is there a way to ensure that an H2 headline fits within the width of a DIV element? I am looking for a solution where the font size of the H2 automatically adjusts to display its full text without overflowing or breaking into a second line inside the DIV ...

Combine going to an anchor, performing an AJAX request, and opening a jQuery-UI accordion tab all within a

My goal is to have the user click on the hyperlink below, which will (1) anchor to #suggestions, (2) navigate to the url suggestions.php?appid=70&commentid=25961, and (3) open the jquery-ui accordion #suggestions. However, I am facing an issue where c ...

Problem with deploying a Nextjs project on cPanel

I've been struggling to deploy a nextjs project on cPanel. The project consists of only one SSG page. I set the basePath in next.config.js to deploy the project, but I keep getting a 404 page not found error and the page keeps getting called in the ne ...

Verify the dimensions of the file being uploaded

I have a file uploader component that requires a dimensions validator to be added. Below is the code for the validator: export const filesDimensionValidator = (maxWidth: number, maxHeight: number): ValidatorFn => (control: AbstractControl): Vali ...

Exploring the setTimeout function in JavaScript

As I understand it, the setTimeout function creates a new thread that waits for x milliseconds before executing the JavaScript function. setTimeout(functionName, timeInms); My question is: Is there a way to instruct it to run after all other JS on the pa ...

Adding an image to a React component in your project

I am currently working on an app that utilizes React and Typescript. To retrieve data, I am integrating a free API. My goal is to incorporate a default image for objects that lack images. Here is the project structure: https://i.stack.imgur.com/xfIYD.pn ...

When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading). Here is the scenario: There is an action button called View Report that re ...

Trouble fetching asynchronous data in Next.js Higher Order Component

Currently, I am in the process of creating a Higher Order Component (HOC) that will fetch user data from my API and then provide props to the wrapped component. This will allow the component to redirect the user based on their role. Although the HOC appea ...

Rendering components asynchronously in ReactJS

After completing my ajax request, I need to render my component. Here is a snippet of the code: var CategoriesSetup = React.createClass({ render: function(){ var rows = []; $.get('http://foobar.io/api/v1/listings/categories/&apo ...

No data, response or issue received from the Internet API

In my web api project, I have created the following controller: public IEnumerable<Speciality> GetAllSpecialities() { List<Speciality> specialities = null; try { specialities = (new Datatable(Proper ...

Using images stored locally in Three.js leads to undefined mapping and attributes

Currently, I am developing a WebGL application using Three.js that involves textures. To enhance my understanding, I have been referring to the tutorials available at . However, when attempting to run the application locally, I encountered several errors. ...

Simply drag and drop the image from your browser window into the file input

Is there a way to drag an image from a browser window into a file input that I developed? Looking for assistance in creating an event that allows me to get the image when dragging it to an input. While I have successfully created an event to obtain the i ...

How can you locate and emphasize specific text within various elements using JavaScript?

Created a script to highlight linked text in another HTML page. <p>Click <span class="f1"><a href="#myModal" data-reveal-id="myModal">here</a>/span></p> <div class="leftspread"> <p class="table-caption"& ...

Ways to widen the header to fit the entire page?

I'm having trouble stretching my header to fill the entire page. I've tried using margin-left and right, but it's not working as expected. My Header CSS: background: green; height: 70px; width: 100%; display: flex; just ...

What are the best ways to prioritize custom events over ng-click events?

Recently, I developed a web application using AngularJS. One of the features I included was an input text box with a custom ng-on-blur event handler. Due to some issues with ng-blur, I decided to create my own custom directive called ngOnBlur. Here's ...

There seems to be a complete absence of rendering in this particular vue

Upon initializing a fresh Vue project using Vue CLI 3 and removing all default views and components, I proceeded to add two new views. To my surprise, these views did not render when changing the URL; instead, I was met with a blank page and no error messa ...