Achieving object rotation in three.js by synchronizing with the camera

I'm currently working on making an object follow the camera to create a rifle viewfinder effect. I am using OrbitControl, but I've run into an issue with the camera rotation range. The camera.rotation.y property only goes from -PI/2 to PI/2, even though I can rotate the camera a full 360 degrees. I'm having trouble understanding this limitation and would appreciate some help!

Here's a snippet of my code:

pivot = new THREE.Object3D();
pivot.add(viewfinder);//adding viewfinder as a child of pivot
scene.add( pivot );

Later on in the code:

pivot.rotation.y = camera.rotation.y; 

Although this allows me to rotate my viewfinder, it is shifted by Pi/2 for some reason. To fix this, I adjusted the rotation as follows:

pivot.rotation.y = (camera.rotation.y - (Math.PI/2));

With this adjustment, I can now rotate the viewfinder with the camera within a range of 180 degrees. How can I achieve a full 360-degree rotation? Any assistance would be greatly appreciated. Thank You.

Answer №1

Do you need the mesh to constantly align with your camera's position? One way is to utilize the camera matrix to adjust mesh rotation, like this:

mesh.rotation.setRotationFromMatrix(camera.matrix)
. However, be cautious if your mesh has a parent entity. Alternatively, you can employ the lookAt() function by using mesh.lookAt(camera.position). Both methods should achieve the desired effect.

Answer №2

In my experience with THREE JS and testing it using "PointerLockControls," I discovered a way to make an object have the same Y rotation as the camera by following these steps:

const getCameraRotate = new THREE.Vector3();
        camera.getWorldDirection( getCameraRotate);
        getCameraRotate.y = 0;
        getCameraRotate.add( object.position );
        object.lookAt( getCameraRotate );

If you also want the object to have the same X, Y, and Z rotation as the camera, simply use:

object.rotation.copy(camera.rotation)

And if you wish for the object to have the same position as the camera, you can achieve it with this code:

object.position.copy (new THREE.Vector3 (camera.position.x, camera.position.y, camera.position.z));

However, keep in mind that placing the object at the exact same position as the camera may result in visibility issues since you would be inside the object. You can adjust the positioning by changing values like this:

new THREE.Vector3 (camera.position.x-5, camera.position .y -5, camera.position.z)

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

Ways to eliminate all attributes and their corresponding values within HTML tags

Hey there, I'm trying to strip away all the attribute values and styles from a tag in html Here's my Input: <div id="content"> <span id="span" data-span="a" aria-describedby="span">span</span> <p class="a b c" style=" ...

Is there a way to implement a watch on $validator.errors in Vue.js using the Vee Validation plugin?

My intention was to implement a watch on $validator.errors, so that any error that arises gets logged, To achieve this, I checked the length of errors and stored self.errors.all() in a variable, However, I'm curious if it's possible to directly ...

Presenting a trio of distinct tables each accompanied by its own unique button option

I am attempting to create a functionality where there are 3 buttons and when a user clicks on one of them, it shows the corresponding table while hiding the other two. I have experimented with using getElementById to manipulate the display property of the ...

Using Environment Variables in Mocha Test Suites

As I delve into integrating dotenv to manage environment variables for my integration tests, I am steering clear of specifying these variables through a mocha cli script. My goal is to designate them in a different location such as within the test.js files ...

What sets apart Selenium's mouseMove() function from the physical movement of a mouse?

Imagine I have element A and element B on a webpage. Using tools like Selenium or PhantomJS, I can manipulate the mouse via coordinates. By identifying the position of element A (a link) and element B (a submit button), I can create a bezier curve or mimi ...

The server mistakenly sent the resource as a Stylesheet even though it was interpreted differently

Dear Fellow Coders, Could anyone lend a hand? I encountered this issue on my website after uploading it to my FTP: "Resource interpreted as Stylesheet but transferred with MIME type text/plain" </head> <body> <div class= "navbar navbar ...

What is the best way to retrieve accurate error messages using AJAX and JSON?

Storing span values into a database has been successful. However, I am encountering an issue with the ajax return error message. For instance, in my save.php code, I mistakenly changed my table name from sample to simple (which does not exist in my databas ...

Is there a way to convert Firebase JSON into a JavaScript object? If so, what is the method to

I am currently working on using the kimono web scraper in conjunction with Firebase to obtain data stored as JSON. To convert the JSON to XML, I am utilizing a JavaScript library which allows me to create a variable from the JSON file (an example is shown ...

Issue encountered while generating a package using npm init in Node.js

I am currently in the learning process of NodeJs from tutorialspoint(TP). Following instructions provided in this link, I tried to create a package by running the following command: C:\Program Files (x86)\nodejs>npm init This utility will w ...

Creating a JSX syntax for a simulated component and ensuring it is fully typed with TypeScript

Looking for some innovative ideas on how to approach this challenge. I have a test helper utils with added types: import { jest } from '@jest/globals' import React from 'react' // https://learn.reactnativeschool.com/courses/781007/lect ...

JavaScript - task - collection of arrays

var x = new Array(); var y = new Array(); var z = [x,y]; var words = 'hello,world,nice,day'; for(var j = 0; j < z.length; j++){ z[j] = words.split(','); } Once executed, the desired outcome is: c = [x, y]; x = ['hello' ...

Arranging divs using inline-block display. How to adjust the heights consecutively?

After much searching and attempting, I am still unable to achieve a simple task. My goal is to apply display inline-block to some divs while aligning them in a row, similar to the image below: https://i.sstatic.net/iLhLS.png The issue arises when number ...

Align the pointerlockcontrols at the center of the mouse cursor

Addressing Cursor Locking Position Issue Currently, when the cursor is locked, it is positioned where it was clicked on the screen. However, I want the cursor to be centered on the screen. Due to security restrictions, directly centering the cursor is not ...

What can be done to prevent function from being treated as instance members within a controller's scope?

When using angularJS 1.3, the following code snippet showcases the functionality: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="http ...

An issue is encountered with the JavascriptExecutor while attempting to navigate to a different page using Selenium Webdriver

My goal is to capture user actions such as clicks, keypress, and other DOM events by adding JavaScript event listeners to the WebDriver instance. Everything works fine until I navigate to the next page, where I encounter an exception due to an undefined fu ...

PHP and JavaScript: Understanding Variables

I currently have a View containing an Associative Array filled with information on accidents. Users will have the ability to click on a Country. Once clicked, I want to display accident-related data for that specific country. This data is pulled from PHP ...

Floating above a surface to manipulate a title

Wondering if it's possible to achieve this without JavaScript, but that would be the ideal scenario. Here's a snapshot of how my page is structured: ____________________________ | TITLE | |This is a fixed header. I wa ...

Node.js command prompt claims that 'react is non-existent'

Hello everyone! I'm excited to ask my first question on this site. I am relatively new to coding and currently learning React. Yesterday, I started working on my first project. Today, when I tried to initialize live-server and babel compiler for my J ...

JavaScript pop-up purchase tooltips from MenuCool

I am relatively new to the world of web design and programming. I am putting in a lot of effort to learn as much as possible, but I am encountering difficulties with the tooltip JavaScript that I incorporated into my website Click here to visit my website ...

Decomposing a Vuex module into distinct files with Nuxt: A step-by-step guide

In the official Nuxt documentation (here), it is mentioned that 'You can choose to divide a module file into separate files: state.js, actions.js, mutations.js, and getters.js'. While there are examples of breaking down the Vuex store at the roo ...