What is the best approach for implementing a getworldposition functionality with Three.js?

Looking for a way to create a getWorldPosition function in Three.js that will return a vector?

This is the code I have to obtain the World Position of an object (obj) and store it in the vector vec.

obj.updateMatrixWorld();
var vec = new THREE.Vector3();
vec.setFromMatrixPosition(obj.matrixWorld);

Now, I would like to turn these three lines into a function so it can be used like this:

var vector = getWorldPosition(obj);

Does this approach seem correct to you?

function getWorldPosition(obj)
{
    obj.updateMatrixWorld();
    var vec = new THREE.Vector3();
    vec.setFromMatrixPosition(obj.matrixWorld);
    return {vec.x, vec.y, vec.z}; // Is this how you would write it?
}

Answer №1

With the use of Object3D().getWorldPosition (target), you can now easily retrieve the world position information.

The target parameter is where the result will be stored as a Vector3, giving you the object's position in global coordinates.

For instance:

const newObject = new THREE.Mesh(geometry, material)
let positionVector = new THREE.Vector3()
newObject.getWorldPosition(positionVector)

This means that positionVector now holds the world position data of newObject.

For more detailed information, refer to the documentation:

Answer №2

To gain some insight, take a look at how Jerome Etienne implemented his ObjCoord library:

https://github.com/jeromeetienne/threex.objcoord

Although it may be slightly outdated:

/**
 * Obtain the world position
 * @return {THREE.Vector3}  the world position
 */
THREEx.ObjCoord.worldPosition = function(object3d){
  object3d.updateMatrixWorld();
  var worldMatrix = object3d.matrixWorld;
  var worldPos  = new THREE.Vector3().getPositionFromMatrix(worldMatrix);
  return worldPos;
}

Your approach of directly utilizing the vector aligns with the current best practices in the latest version of THREE.js.

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

Simple code styling tool

Seeking guidance to create a basic syntax highlighter using JavaScript or ClojureScript. While aware of existing projects like Codemirror and rainbow.js, I'm interested in understanding how they are constructed and looking for a simple example. Do th ...

Is there a way to update a useState in TabPanel without causing a re-render?

For the past few months, I've been immersing myself in React and MUI. Recently, I encountered a problem that has me stumped. The Goal: I receive data from a backend and need to display it for users to edit before sending the changes back to the serv ...

When rotating transparent objects with TrackballControls in Three.js, their transparency does not function as expected

When I introduce two objects into the scene and make them transparent with some opacity while using TrackballControls to rotate the scene with the mouse, I notice that the object that was originally farther from the camera loses its transparency. I have l ...

Incorporating a new textfield in Codeigniter through a button/link activation

Currently, I am working on designing a request form for my website. I am facing an issue with creating a button that can dynamically add new input fields when clicked. Unfortunately, I am unsure of how to resolve this problem. Picture this: [ button ] A ...

The YouTube video continues to play even after the container is closed

I recently worked on implementing a lightbox feature using jQuery, where a window opens upon clicking an element. Everything was working fine with images, but when I tried to open a YouTube video and play it, the video kept playing in the background even a ...

Class component proceeding without waiting for function completion

My function, getactivity(), pulls and sorts data from an API and returns the sorted data in answer1 format. However, I am facing a problem where whenever I run the function to retrieve the data, it keeps returning nothing. Here is the full code: import Re ...

Determine the data type of a property within a JavaScript object

I am currently working with a javascript object that looks like this: venue = { id: 0, name: '', venueimage_set: [ { imageurl: '', }, ]... At a later point in my code, I need to modify the object ...

Adding additional validations to your Marketo form is a great way to ensure the accuracy

I'm having trouble adding a new validation rule to the Marketo form since I'm not well-versed in JS and jQuery. I need this rule to display an error message if the form is submitted with any field left empty. Additionally, I want to validate the ...

Issues with Javascript causing MongoDB batch insert to fail

I need assistance with optimizing my Javascript code. I have created a script to insert multiple records into a collection at once using "insertMany()". However, the code I wrote is not functioning correctly: var batch = []; for (i=0; i<10; i++) { ...

Linking a variable in typescript to a translation service

I am attempting to bind a TypeScript variable to the translate service in a similar way as binding in HTML markup, which is functioning correctly. Here's what I have attempted so far: ngOnInit() { this.customTranslateService.get("mainLayout.user ...

The Vue feature responsible for displaying information on the webpage is currently not working as expected

I'm in the process of developing a settings page for a project. This particular page is based on HTML and utilizes JSON to store data, with Vue 3 being used to display the information on the page. However, I've encountered an issue where the data ...

Adjusting Classes in JavaScript with jQuery

I need to create a feature that changes the state of a button from active to inactive based on user input, using Bootstrap. Ultimately, I am working towards finding an intuitive way to validate form input so that the submit button can be pressed for PHP pr ...

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...

Facing compatibility problems with JavaScript and Cascading Style Sheets in Google Chrome?

Welcome to the site . Let's address a couple of issues with JavaScript and CSS: Firstly, the JS code seems to be malfunctioning only in Chrome, throwing an error that reads: 'Uncaught TypeError: Object [object Object] has no method 'on prij ...

Plot a Highchart heatmap with the x-axis representing time values and the y-axis representing strings

I've been working on creating a heatmap to display the time taken for each task to execute. The x-axis will show time in datetime format, the y-axis will contain the task names, and each point will represent the time taken for the task execution. [{d ...

What is the expected return type in TypeScript of a function that returns a void function?

I recently received feedback during a code review suggesting that I add return type values to my functions. However, I am unsure of what return type to assign to this particular function: function mysteryTypeFunction(): mysteryType { return function() ...

Issue encountered while attempting to load a JSON file into an ExtJS JSONPStore due to a

After validating a json file with json.bloople.net, the file begins as follows: { "sepString": "--", When attempting to load this json file into an ExtJS JsonPStore, Chrome displays the error: Uncaught SyntaxError: Unexpected token : in line 2 What ...

React failing to display changes in child components even after using setState

When I delete an "infraction" on the child component, I try to update the state in the parent component. However, the changes do not reflect visually in the child component even though the state is updated. It seems like it's related to shallow update ...

Angular - Highlight a section of a string variable

Is there a way to apply bold formatting to part of a string assigned to a variable? I attempted the following: boldTxt = 'bold' message = 'this text should be ' + this.boldTxt.toUpperCase().bold() ; However, the HTML output is: thi ...

Angular 6 animation moving forward (utilizing animation-fill-mode in Angular)

My CSS animated property is functioning properly with the code snippet below: animation: collapse1 0.3s forwards; However, I now need to transition to Angular animations. Everything is working correctly, except for one issue: once the animation completes ...