Determine the distance between two objects and the camera using Three.js

I am working with two squares positioned in space, resembling the front and back walls of a cube with specific vertices:

x=-2 y=-1138 z=-2;
x=-2 y=-1134 z=-2;
x=2 y=-1138 z=-2;
x=2 y=-1134 z=-2

The second square is defined by the following vertices:

x=-2 y=1134 z=2;
x=-2 y=1138 z=2;
x=2 y=1134 z=2;
x=2 y=1138 z=2

When I calculate the distance from the camera using the following code snippet:

var point1 = this.camera.matrixWorld.getPosition().clone();
var point2 = this.mesh.cubePlane3.children[0].matrixWorld.getPosition().clone();
var distance = point1.distanceTo( point2 );  

I consistently get the same distance of 20.09 for both squares. These squares are rotated in space, so only the rotation changes. I am trying to determine which wall is closer to the camera in order to selectively display walls in the cube. However, I am struggling to understand the mathematics behind this. For instance, I am puzzled by the fact that adjacent walls have different y-coordinates (positive and negative) and why the distance remains the same even when one wall is closer along the z-axis than the other. Can someone please help me figure out how to identify the closer walls? Thank you.

Answer №1

Every shape comes equipped with a computeBoundingBox method. This means you can simply call: var bbox = geometry.computeBoundingBox(); for each shape you want to analyze, and then call bbox.center() to find the center of the shape. An even quicker method is to use computeBoundingSphere on your shape. From there, you can easily compare the positions of the centers relative to your camera.

Answer №2

I implemented the computeBoundingBox function using the following code snippet

    this.mesh[cubePlane[0]].children[0].geometry.computeBoundingBox();

    var position = new THREE.Vector3();
    position.sub( this.mesh[cubePlane[0]].children[0].geometry.boundingBox.max, this.mesh[cubePlane[0]].children[0].geometry.boundingBox.min );
    position.multiplyScalar( 0.5 );
    position.addSelf(this.mesh[cubePlane[0]].children[0].geometry.boundingBox.min );

    this.mesh[cubePlane[0]].children[0].matrixWorld.multiplyVector3( position );

    var point1 = this.camera.matrixWorld.getPosition().clone();
    var point2 = position;
    var distance = point1.distanceTo( point2 );

Thanks for the helpful suggestion, my implementation is now working perfectly :)

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

"Utilizing the 'await' keyword within a JavaScript 'for of'

Could there be an issue with my code? I am utilizing express and mongoose router.get('/c/:hashtoken', validateEmailToken, catchAsync(async(req,res)=>{ const hashtoken = req.params.hashtoken const hashtoken2 = createHash('sha256&ap ...

Having trouble accessing the information stored in the Firebase Database?

As a newcomer to Firebase and JS, I am attempting to showcase user information on a webpage that is stored within the Firebase database. The data format resembles the image linked here I have written this Javascript code based on various tutorials. Howev ...

Is there a way to create a duplicate form without any pre-filled text when clicking the "next" button using JavaScript?

This form contains the details that I would like to display on the page again when clicking the "Add Another Module" button. <div> <form class="in-line" id="module_info"></form> <div style="display: flex;"> < ...

When I set the width of my script to 100% in CSS, it causes the width to become distorted

I encountered an issue with my Div Slider that swaps out Divs on click. When I modified the CSS to include the following: .hslide-item {width: 100%}; The script started ignoring the entire div width. I am looking for a solution where the .hslide-item ca ...

How can I trigger the execution of textarea HTML code with an onClick event using JavaScript?

When my fingers are lifted from the keyboard, some code will be automatically executed. I want to trigger this function when I click a button (onclick) instead of using onkeyup. <div id="result"></div> <textarea ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

Integrating AngularJS code into dynamically generated HTML using JavaScript

I am currently utilizing an outdated version of AngularJS (1.3). I have a page where I need to dynamically display different content based on database values. If the user interacts with the page and changes the database value, I want the displayed content ...

Using Angular $resource to store an object with arrays

Consider a scenario where we have a User $resource structured as follows: $scope.user = { name: 'John', hobbies: [1, 2, 3] } If we were to save User.save($scope.user) to the server, it would send the following parameters: name: 'John& ...

Is there a way to display a date that is two days before the current date in a React date picker using only vanilla JavaScript

Greetings, I am currently immersed in working with a Shopify app that utilizes React. Unfortunately, I do not have access to their code base or API. The challenge at hand is sending the correct delivery date to the Shopify system. The app currently allows ...

Having trouble passing parameters in a Node.js express POST request?

Here is the code snippet I am currently working with: const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })); app.post('/rasp&apos ...

Keep elements in position when their bottom edge becomes visible while scrolling

This task may appear intricate, but I will do my best to explain it! I want to create a continuous scrolling article display similar to Bloomberg Politics (), but with a slight twist. My idea is to have the current article's bottom edge stick to the ...

The dropdown menu is dynamically populated based on the selection from another dropdown menu, with options retrieved from

Apologies if this has been addressed previously, but the existing solutions do not seem to work for me. I have 5 dropdowns: Brand, Model, Color, Engine No., and Chassis No. My query pertains to how I can link the dropdown options for Model based on the sel ...

Is it possible for a user to modify the JavaScript code on a website?

As I develop a website that heavily relies on JavaScript, I am curious about the possibility of users being able to edit the JS code themselves. For instance, if I have an ajax function that calls a.php, could a user modify the function using Firebug or a ...

Having difficulty accessing the value of a table td element in HTML using a jQuery selector

When creating a table, I utilize ng-repeat to generate table rows. Whenever the dropdown changes, a function is triggered which applies certain conditions. Based on these conditions, an object is added to an array that is bound to a scope variable. Here i ...

Why is the value not being assigned by the Angular component from the observable service getter?

I am currently working on developing a filter set, and I am facing an issue with the salesChannels array content in my view. The array only gets populated after clicking a button that triggers the test() function. Interestingly, the first time I log the ar ...

The functionality of Bootstrap tooltips becomes disabled as soon as any element on the page is clicked

When initializing Bootstrap tooltips on my page, I follow this approach <script> $(document).ready(function () { $(function () { $('[data-toggle="tooltip"]').tooltip(); }); }); </script> A questio ...

Adjust the text size for groupBy and option labels in Material UI Autocomplete without altering the size of the input field

Currently, I am utilizing Material-UI and ReactJS to implement grouped autocomplete functionality. See the code snippet below: import * as React from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from &q ...

React Hook is failing to trigger an update

Learning React and JavaScript has been quite a challenge for me, especially when it comes to understanding React Hooks and the issue of them not updating sometimes. I have tried searching online but either end up with solutions for class-based components o ...

Having trouble with the functionality of the AngularJS Custom Service?

I have developed a straightforward service as shown below: var app = angular.module('myApp', ['ngRoute']); app.service('UserService', function() { this.user = {firstName:"",middleName:"",lastName:"",email:"",dob:""}; this.ad ...

Challenges with Dual Y-Axis in a Horizontal Stacked Bar Graph

My charts are presenting me with several issues and questions: Is there a way to avoid the right y-axis tick values from either being partially erased or overlapping with the chart? When I set yValuesTripId as the domain for both the left and right y ...