Orbit around a moving object in Three.js

I am working with a camera that needs to rotate around a specific target position within the scene. Despite attempts to implement a pivot concept, as suggested in this discussion: https://github.com/mrdoob/three.js/issues/1830, I have come up with my own solution using the code below:

var rotationY = new THREE.Matrix4();
var rotationX = new THREE.Matrix4();
var translation = new THREE.Matrix4();
var translationInverse = new THREE.Matrix4();
var matrix = new THREE.Matrix4();
function rotateCameraAroundObject(dx, dy, target) {  
    // defining up and right vectors based on camera perspective
    camComponents.up = rotateVectorForObject(new THREE.Vector3(0,1,0), camera.matrixWorld);
    camComponents.right = rotateVectorForObject(new THREE.Vector3(1,0,0), camera.matrixWorld);

    matrix.identity();

    rotationX.makeRotationAxis(camComponents.right, -dx);
    rotationY.makeRotationAxis(camComponents.up, -dy);
    translation.makeTranslation(
        target.position.x - camera.position.x,
        target.position.y - camera.position.y,
        target.position.z - camera.position.z);
    translationInverse.getInverse(translation);

    matrix.multiply(translation).multiply(rotationY).multiply(rotationX).multiply(translationInverse);
    camera.applyMatrix(matrix);
    camera.lookAt(target.position); 
}

The challenge lies in not wanting to utilize lookAt due to its reorientation effect. The goal is to achieve the rotation without relying on this function.

When the code above is executed without lookAt, the camera rotates around the point but does not maintain focus on it. Ideally, the camera's perspective should align with its physical rotations, yet this does not happen. I would appreciate any insights into what could be causing this discrepancy.

EDIT: Revising the original post and code for better clarity regarding my query.

The approach involves translating to the origin (the target position), rotating to the desired degree, and then returning to the initial position. This process is expected to result in a new orientation towards the origin due to the rotation applied.

Currently, I am conducting tests without incorporating the translation matrices, which simplifies the matrix multiplication line to:

matrix.multiply(rotationY).multiply(rotationX);

Yet, the behavior remains consistent. Many thanks for all the previous assistance!

ONE MORE THING! An additional complexity arises when the camera encounters issues near the poles, specifically the north and south points of the scene. To achieve a more versatile and unrestricted movement, I am seeking recommendations for enhancing the camera control system.

Answer №1

Include the code below in your rendering loop:

camera.position.x = target.position.x + radius * Math.cos( constant * elapsedTime );         
camera.position.z = target.position.z + radius * Math.sin( constant * elapsedTime );
camera.lookAt( target.position );

renderer.render( scene, camera );

Alternatively, you have the option to utilize THREE.OrbitControls or THREE.TrackballControls. Refer to the various examples provided by three.js.

Answer №2

The issue with Gimbal lock, which occurs during reorientation, is caused by the reliance on Euler angles in the standard camera lookat function. To avoid this problem, you can enable quaternions by setting

camera.useQuaternion = true;

prior to invoking the lookat method. Have you tried implementing this solution?

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

incorporating a timer into a JavaScript game

I am currently working on a memory card game where I want to include a stopwatch feature. I'm looking to display the time elapsed from when the user selects the first card until they win. However, I am struggling with keeping the stopwatch running smo ...

Maintain text while transitioning to another page

On my webpage (refer to image for details), users need to select options through a series of steps. The process involves clicking on a link in the top box, then entering a search term in the searchbox to display relevant links in div1. Clicking on a link ...

The React application is experiencing difficulties in receiving the response data (JSON) from the Express server, despite the fact that

When making POST or GET requests to our Express server, served through PM2 on EC2, Postman receives the complete response with JSON data. However, our front end React app (both locally and deployed via CF) only gets the response status code and message. Th ...

Encountering a fresh issue after updating to TS version 4.4.3 while accessing properties of the top "Object may be 'null'."

After upgrading my project to TypeScript 4.4.3 from 3.9.9, I encountered a change in the type declarations for the top property. My project utilizes "strictNullChecks": true, in its configuration file tsconfig.json, and is browser-based rather t ...

Is there a way to display multiple images in a JSON message object?

If you're looking for a fun way to generate random dog images, then check out my DogAPI image generator! Simply enter a number between 1-50 into the form text box, hit send, and watch as it displays that amount of random dog photos. I'm almost t ...

Utilizing Next.js with formidable for efficient parsing of multipart/form-data

I've been working on developing a next.js application that is supposed to handle multipart/form-data and then process it to extract the name, address, and file data from an endpoint. Although I attempted to use Formidable library for parsing the form ...

Cheerio - Ensure accurate text retrieval for selectors that produce multiple results

Visit this link for more information https://i.stack.imgur.com/FfYeg.png I am trying to extract specific market data from the given webpage. Specifically, I need to retrieve "Sábado, 14 de Abril de 2018" and "16:00". Here is how I did it using Kotlin an ...

Shadows persist despite light intensity being reduced to 0 during runtime

Struggling to figure out how to get rid of these persistent shadows... During runtime, I attempt: light.intensity = 0.0; This makes the scene darker (which is good), but the shadows created by the light remain visible. I've experimented with both ...

using vuejs, learn how to retrieve properties within the .then function

This is the code I am working on: methods: { async pay() { this.$notify(`working`); if (!this.$v.$invalid) { try { var data = { to: this.to, subject: this.subject, }; let resp ...

Using index value as parameter in append function within angular js

I attempted to develop a chat box in Angular, and although I was able to create it, something feels wrong. When I click on the members, it displays a different member than expected. Could someone please review my code? Here is the link to the Plunker: &l ...

"Troubleshooting: Why is my jQuery .load function returning an empty div when

Currently, I am developing a PHP control panel and I need a div in one of my PHP files to automatically refresh. After researching, I found a jQuery solution that can reload specific parts of a website automatically. However, the issue I am facing is that ...

Troubleshooting a mysterious anomaly with a jQuery UI button

Would like to achieve something similar to this: http://jqueryui.com/demos/button/#icons When trying to replicate it, http://jsfiddle.net/p5PzU/1/ Why is the height so small? I expected a square shape but am getting a rectangle instead. What could be c ...

When the window size is reduced, the navigation vanishes

Whenever I resize the window, the navigation bar disappears. Here is the image of the page before resizing the window https://i.sstatic.net/UiRB9.png Below is the image after resizing the window https://i.sstatic.net/X00d2.png Displayed below is the cod ...

Retrieve data from the api

Can someone provide the JavaScript code to loop through an API, extract the coordinates/address, and map it? Here is a simple demonstration of fetching the API data: const fetch = require("node-fetch"); fetch('url').then(function (resp ...

Sending basic HTML from Express.jsSending simple HTML content from an Express.js

Within my index.html document, I have the following: <input name='qwe'> {{qwe}} I am looking to send {{qwe}} in its literal form, without it being replaced by server-populated variables. How can I achieve this? My initial thought was to ...

Add a CSS class to the text that is selected within a Content Editable div

Hey there, I'm having an issue where the class is being applied to the button when pressed instead of the selected text. Here's my current code: The button needs to be a div, but it might be causing the problem. I just want the highlighted text ...

Gulp Watch fails to identify changes in the SASS SCSS directory

After setting up Gulp to compile SCSS into CSS using NanoCSS and gulp-css for the first time, I encountered an issue. While my do-sass command successfully compiles SCSS and minifies CSS files, it does not run when placed within a watch task. Any changes ...

Is there a way to populate an array with Twilio fax results and then successfully send them via Express?

Currently, I am working on integrating the Twilio API into our secured backend system before sending the data to our client app. This is being done to protect our API keys and for security purposes. We have successfully implemented fax sending and checkin ...

Implementing CKEditor instances within AngularJS Controller scopes

Greetings everyone, Recently, I have been exploring Angular JS. Everything is going smoothly - my controllers, services, and so on. However, when attempting to make a Div editable that is within the ng-controller, the ckeditor toolbar fails to appear. On ...

Ensure that a specific value is maintained for a property of an element throughout its animation

There are two distinct types of components that I am working with, which I will refer to as .a and .b. It is possible that these components have been assigned certain CSS animations. I do not have the ability to control these keyframes, whether they are a ...