Obtaining the Camera's Position Relative to the Origin in Three.js

The wording of this question might be unclear, but I'm struggling to phrase it concisely.

Here's the scenario: there is a perspective camera in the scene along with a mesh. The mesh is positioned away from the origin of the axis.

The camera is pointed directly at the center of this object, and its position (the "position" property of the Three.js camera object) is based on the object's center, not the origin; therefore, it operates within a different coordinate system.

My query is: how can I determine the camera's position relative to the origin of the "global" coordinate system rather than the object's center?

To illustrate, consider this image. It shows a hand mesh positioned far from the origin of the coordinate system. When I check the camera's position, I get these values: x: -53.46980763626004; y: -2.7201492246619283; z: -9.814480359970839 yet what I require are positions relative to the origin (which would yield different values).

UPDATE: I followed @leota's advice and used the localToWorld method like this:

var camera = scene.getCamera();
var viewPos = camera.position;
var newView = new THREE.Vector3();
newView.copy(viewPos);
camera.localToWorld(newView);

I tested this with this mesh. The mesh isn't centered on the origin either. The regular camera position results are: x: 0; y: 0; z: 15

After applying the code above, the positions change to: x: 0; y: 0; z: 30

This output is inaccurate, as the camera's x and y coordinates should not be zero based on the image shown.

If I adjust the camera so it's closer to the origin, such as in this image, where it's behind the origin with negative coordinates for x, y, z, the positional data when considering the object's center become:

x: -4.674180744175711; y: -4.8370441591630255; z: -4.877951155147168

Yet after using the code, they shift to: x: 3.6176076166961373; y: -4.98753160894295; z: -4.365141278155379

The positive x value indicates an error despite possibly accurate y and z values.

I'll keep exploring solutions, but this could be a step forward. Any more suggestions are welcome!

UPDATE 2:

A solution has been found. While @leota provided the correct approach to obtaining absolute camera coordinates, I discovered a hidden line of code in the project that scaled everything according to a specific rule. Thus, I had to adjust the camera position based on that rule.

Since @leota's answer solved the original issue, it's being accepted as the correct response.

Answer №1

Confused about your inquiry :) If I understand correctly, you're looking to switch between World and Local coordinate systems. The THREE.PerspectiveCamera is a subclass of THREE.Object3D, allowing you to utilize the following methods for setting your coordinate system:

.localToWorld ( vector )

vector - Represents a local vector. This method updates the vector from local space to world space.

.worldToLocal ( vector )

vector - Represents a world vector. This method updates the vector from world space to local space.

Referenced from Three.js Documentation

Update:

Begin by updating your camera Matrix:

camera.updateMatrixWorld();

Then proceed with:

var vector = camera.position.clone();

vector.applyMatrix( camera.matrixWorld );

The vector will now hold the position in world coordinates.

Answer №2

I found myself grappling with the same question, trying to provide an answer. I was initially perplexed, but after some thought, here is my best guess:

var plot = camera.position.x - mesh.position.x;
var plotb = camera.position.y - mesh.position.y;
var plotc = camera.position.z - mesh.position.z;
mesh.position.x = (camera.position.x + plot) - mesh.position.x;
mesh.position.y = (camera.position.y + plotb) - mesh.position.y;
mesh.position.z = (camera.position.z + plotc) - mesh.position.z;

or

var plot = (camera.position.x *  mesh.position.x) / 1000;
var plotb = (camera.position.y *  mesh.position.y) / 1000;
var plotc = (camera.position.z *  mesh.position.z) / 1000;
mesh.position.x = mesh.position.x + plot;
mesh.position.y = mesh.position.y + plotb;
mesh.position.z = mesh.position.z + plotc;

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

typescript in conjunction with nested destructuring

ES6 has definitely made coding more efficient by reducing the number of lines, but relying solely on typescript for everything may not be the best approach. If I were to implement type checking for arguments that have been destructed multiple levels deep, ...

What strategies are typically employed to prevent falling into the callback hell trap when working with error-back asynchronous functions in Node.JS?

As a new Node user, I've been practicing pure Node scripting without relying on third-party npm packages. However, I quickly ran into the issue of my code becoming nested with callbacks inside callbacks, making it difficult to follow. This can lead to ...

Displaying data from a table in a modal window using getSelected in Bootstrap-table

I am currently utilizing bootstrap and bootstrap-table, and I have a requirement to display the data of the selected item in a modal window. When I retrieve the information of the selected item: Here is my JavaScript code: var $table = $('#tableprod ...

Is there a way to navigate to a specific div when clicking on it?

Need help with scrolling after running code function scrollFunction() { document.getElementById('insert').scrollIntoView(); } I have a button that triggers some code and I want the page to scroll afterwards. Currently, it scroll ...

Enhancing a Pie Chart Dynamically with Ajax using Highcharts

I need assistance with updating the data for the pie chart when a list item is clicked. The issue arises when using dynamic values from $cid in data.php. For example, user_student.cid = 1 works correctly, but if I use user_student.cid = $cid, it doesn&apos ...

Cookies store their values within the document.cookie framework

My cookie contains the following data: emailID=a1%40a.comSEPmaths=0SEPphysics=0SEPchemistry=0SEPbotany=0SEPzoology=0SEPta mil=0SEPenglish=0SEPpolity=0SEPgk=0SEPhistory=0 However, when I use document.cookie.split('; '), it returns the encoded ve ...

Retrieve key codes from inputs sharing the same class

My webpage contains multiple text inputs that all share the same class for various reasons. Currently, I am attempting to capture the ESC button press when an input is focused and alert whether the input has a value or not. However, this functionality on ...

Showing the result of a backend script on the current page using PHP

I currently have a PHP web application that involves submitting data to a backend pipeline, also written in PHP. This pipeline consists of an external script that my application accesses using the 'exec' PHP function. The pipeline follows a multi ...

Place the image either above or below the text in a relative position

I have a peculiar dilemma that has been on my mind lately. As I work on designing my website, I am nearing completion of the responsive/mobile view. Currently, everything looks fine, but only because I use display: none; to hide images when the viewport is ...

Using identical CSS styles across various classes in material UI

Three classes have been defined with identical CSS properties. const useStyles = makeStyles((theme) => ({ classA: { color: 'green' }, classB: { color: 'green' }, classC: { color: 'green' } }) Is there a way to combin ...

Tips for validating multiple forms on a single page without altering the JavaScript validation structure

My JSP page currently consists of two forms: <body> <form id="1"></form> <form id="2"></form> </body> Only one form is visible at a time when the page is viewed. A JavaScript validation file is used to check the ...

Enhancing Filtering Capabilities with Multiple ng-Model in AngularJS

I am facing an issue with filtering a form based on user input in a text box or selection from a dropdown list. The text box filter works fine individually, but when I try to combine it with the dropdown list selection, neither filter seems to work. Below ...

I'm stumped trying to identify the issue in the JavaScript code provided. I attempted to save a function within a variable with no success

After incorporating the suggestions I received, I have revised the entire code. However, there seems to be a missing element as I am still unable to utilize the var deducere in mathematical operations. I consistently receive NaN. Any advice or feedback o ...

Using an external call to trigger the revert method in jQuery UI

My draggable event setup looks like this: $(ids.label).draggable({ containment: ids.wrapper, revertDuration: 100, revert: function(event) { $(this).data("draggable").originalPosition = { top: $(this).data('origionalTo ...

Put identical objects into several arrays at the same time

This question is in relation to a previous query about arranging 3 arrays to correspond with each other. After creating my objects, I am now attempting to push values into their respective arrays based on JSON data received. let objName = ["object1", "obj ...

Generate a dynamic form that automatically populates different input fields based on JSON data

I am trying to dynamically auto populate a form with various input types such as select boxes and text areas. I have successfully implemented this for input boxes, see example below: function autofill(){ var data = [{visible_retail: "0", brand: ...

When reference variables are utilized before being parsed, what happens?

I'm a beginner learning Angular and have a question regarding the use of reference variables. Here is an example code snippet: <div class="bg-info text-white p-2"> Selected Product: {{product.value || '(None)'}} </div> <di ...

fetch promise not fulfilling as expected

There's a method I'm using to call an all-purpose fetch method defined in a separate JS file: export function detailedView(request,token) { let endpoint = 'api/v1/cbn/inventory/GetDetailRequest?RequestNo='+request['RequestNo&a ...

Unable to locate module within a subdirectory in typescript

The issue I'm facing involves the module arrayGenerator.ts which is located in a subfolder. It works perfectly fine with other modules like Array.ts in the parent folder. However, when I introduced a new module called Sorting.ts, it started giving me ...

The nested promise.all function is executing synchronously instead of asynchronously as anticipated

Within the nested Promise.all section of my NodeJs script, I believe there is an error. The script is designed to process multiple .csv files within a directory, creating a database record for each row. If a row fails processing, it is added to a list of f ...