3D Object Anchored in Environment - Three.js

In my current scene, I have two objects at play. Utilizing the LeapTrackballControls library for camera movement creates a dynamic where one object appears to rotate based on hand movements.

However, an issue arises as the second object also moves along with the camera motion. My goal is to keep this second object stationary in front of me, regardless of camera movement within the canvas/explorer.

Your understanding and assistance with this matter would be greatly appreciated.

EDIT:

var controls = new THREE.LeapTrackballControls( camera , controller );

The setup involves a central sphere that users interact with using LeapTrackball library, giving the perception of rotation around their center.

model = new THREE.Mesh(modelGeo, modelMat);
model.geometry.dynamic = true;
model.position.set(0, 0, 0);
scene.add(model);

The challenge lies with another shape:

myMesh = new THREE.Mesh(circleGeometry, material);
myMesh.position.set(0, 0, 10);
scene.add(myMesh);

This additional object seems to mimic the camera's rotation. The objective is to maintain the spherical rotation effect while keeping the other mesh fixed in the center of the screen (coordinates: 0,0,10).

Details regarding my camera object:

var camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 5000);

Below is the render function responsible for updating camera control/movement:

   function render() {
        controls.update();
        renderer.render(scene, camera);
        doMouse();
        if(useOrbitControls){
            orbitControls.update();
        }
    }

With the integration of a Leap controller, here is the function building it up:

function leapMotion() {
                var controllerOptions = {
                    enableGestures: true
                    , background: true
            , frameEventName: 'animationFrame'
                , };

[...]

    controller.on('frame', onFrame);

Essentially, the 'onFrame' function executes with each received frame (approximately 60 times per second).

    function onFrame(frame){
[...]
        }

The functionality largely stems from the library accessible at:

Answer №1

To keep an object, such as crosshairs, stationary in front of the camera, you can achieve this by making the object a child of the camera. Here is an example code snippet:

scene.add( camera ); // Make sure to include this line when the camera has a child
camera.add( object );
object.position.set( 0, 0, - 100 ); // Adjust the distance as needed

This method is applicable in three.js version r.71

Answer №2

To easily achieve this, you can have your object follow the camera's movement.

By making sure that both the camera and the object move together at every update, while maintaining a constant distance between them, tracking is achieved.

In order for this method to be effective, you must establish a set position from which your object will always be seen, in this case it would be (0, 0, 10).

var fixedPosition = new THREE.Vector3(0, 0, 10);

Next, within your render() function you need to adjust the object's position after the camera has been repositioned but before rendering everything.

function render() {
        controls.update();

        // Let's now update the object's position!
        myMesh.position.sub(camera.position, fixedPosition);
        // The camera and mesh are now equidistant
        renderer.render(scene, camera);
        //...
    }

In this scenario, a vector subtraction does the job efficiently, effectively placing your object constantly 10 units away from the camera on the Z-axis by deducting the fixed amount of 10.

Most of the operations involved will deal with 3D vectors and numerical calculations, so grasping how these operations (basic addition, subtraction, multiplication, etc.) impact what appears on the screen can be beneficial.

If you find yourself uncertain about anything, delving into some knowledge regarding vector mathematics could prove insightful. It doesn't require memorizing formulas as Three.js already incorporates all necessary math functions, but comprehending the effects of these operations can be exceedingly advantageous.

Answer №3

For those utilizing @react-three/fiber, this solution may be beneficial.

import {useFrame, useThree} from "@react-three/fiber";

const { gl } = useThree();

const [ vrEnabled, setVREnabled ] = useState(false);

useFrame(({camera}) => {
    setVREnabled(gl.xr.isPresenting);

    if (vrEnabled) {
        camera.add(ref.current);
        ref.current.position.set( 18, 0, 0 );
    }
});

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

Enhancing live query functionality and providing a substitute for DOMNodeInserted specifically tailored for

I have searched multiple times on various platforms for a solution to my specific issue, but have not found one that fits my unique circumstances. My goal is to replace outdated code such as livequery and DOMNodeInserted. See examples below. I am current ...

change the return value to NaN instead of a number

Hey there, I have something similar to this: var abc1 = 1846; var abc2 = 1649; var abc3 = 174; var abc4 = 27; if(message.toLowerCase() == ('!xyz')) { client.say(channel, `abc1` +`(${+ abc1.toLocaleString()})` +` | abc2 `+`(${+ abc2.toLocaleStri ...

Conceal a div once the content in a separate div has finished loading

After loading an image in slices inside a div, I want to ensure that the entire content is loaded before displaying the div. To achieve this, I am using another div as a mask while the content loads: <div id="prepage" style="position:absolute; left:0px ...

use jquery to dynamically switch CSS class on navigation with animated arrows

Looking to update arrows to display a right arrow when the parent list item has the .active class. Here is the jQuery code: jQuery(function(){ initAccordion(); }); function initAccordion() { jQuery('.accordion').slideAccordion({ opener ...

Angular is the best method for properly loading a webpage

Struggling to solve this issue. I have a webpage where I need to load another webpage, specifically a page from a different site, into a div. Essentially, it's like a news ticker that I want to showcase. The problem is that the URL is stored in a Mon ...

Having trouble getting the onPress event to function properly on a custom button component in my React Native application

As a React Native beginner, I am currently working on a project where I am trying to create a custom button named "RoundedButton" using TouchableOpacity. However, when I attempt to trigger an event using onPress like , it does not seem to work for me. Here ...

ExpressJS: How to resolve the undefined error in Express session

After using express-generator to create my project, I installed the express-session package. Below is how express-session is ordered in my app: app.js var expressSession = require('express-session'); app.use(logger('dev')); app.use( ...

Is it possible to programmatically hide the Textarea and submit button for each row in a PHP-generated database table?

After spending a considerable amount of time on this project, I'm looking to incorporate a JavaScript effect (hide/unhide) into a basic submit form. Although the functionality is successful, it seems to be limited to only one row in the database tabl ...

Changing properties of JavaScript arrays

Currently using Express and dealing with an array of objects that I need to adjust the created property for better presentation, utilizing the dateFormat package. The array originates from a mongo query and is stored in a variable called stories. A sample ...

What could be causing angularjs to malfunction in this specific scenario?

Recently, I followed a tutorial and implemented the code provided. Inside the angular folder in my libs directory, I have the minified version of Angular JS obtained from https://angularjs.org/. However, the output I am seeing is: {{author.name}} {{autho ...

What is the best way to upload an object in React using fetch and form-data?

Currently, I am facing an issue where I need to send a file to my express app as the backend. The problem lies in the fact that my body is being sent as type application/json, but I actually want to send it as form-data so that I can later upload this file ...

Utilizing Windows Azure and restify for node.js Development

I have an azure website with a URL like: . In my server.js file, I have the following code: var restify = require('restify'); function respond(req, res, next) { res.send('hello ' + req.params.name); next(); } var server = restify ...

Is it necessary for the scope to be separated?

In the document object model (DOM), I have two straightforward directives that are responsible for creating similar elements. Both directives have an isolated scope. Each directive has an ng-click attribute that calls a method to display a message. One d ...

Hide the popup menu when the user clicks outside of it

I am presenting the following code <!DOCTYPE html> <html> <head> <title>GalacticCraft</title> <link rel="stylesheet" type="text/css" href="style.css" /> <link rel="shortcut icon" type="image/png" href="fa ...

ajaxStop and ajaxStart not functioning as expected

Currently working on a project to create a Wikipedia viewer, and running into an issue with the following code snippet: $(document).ready(function() { $(document).on('click', '#search_button', function() { ...

Listening for Events from Child Components in Vue.js

I am struggling to figure out how to send an event from a child component to its parent in order to change the view. Although I have been able to create and emit the event, my template does not seem to be properly registering it. I am working with Single ...

Iterating through a series of Axios requests nested within each other to handle pagination in an

I need help iterating through the API response that includes pagination. Below is a snippet of the API response: { count: 165, next: "http://example.com/name?offset=30&per_page=30", previous: null } Here is my useEffect hook: const [datas, se ...

Searching patterns in Javascript code using regular expressions

I am dealing with two strings that contain image URLs: http://dfdkdlkdkldkldkldl.jpg (it is image src which starts with http and ends with an image) http://fflffllkfl Now I want to replace the "http://" with some text only on those URLs that are images. ...

What could be causing my Material UI Divider to appear invisible within a Material UI Container or Paper component?

Hey there! I am absolutely smitten with Material UI - it's incredibly versatile. However, I'm facing a bit of trouble with the Material UI Divider not displaying when nested within either a Container or Paper component. I've looked into it ...

What is the best way to give stacked bar charts a rounded top and bottom edge?

Looking for recommendations on integrating c3.js chart library into an Angular 6 project. Any advice or suggestions would be greatly appreciated! https://i.sstatic.net/iiT9e.png ...