Switch between TrackBall and FlyControls in threejs to change the type of controls being used

My goal is to implement two different control modes in my project: a free "flying" mode and an object-centered (trackball) mode. I want to seamlessly switch between them with the press of a button.

Initially, I experimented with TrackBallControls and FlyControls. The issue I encountered was that TrackballControls relies on Euler angles, while FlyControls is based on Quaternions. In an attempt to make them compatible, I tried converting the camera's rotation vector to a quaternion using:

quaternion.setFromEuler( target ); //where 'target' is a Vector3 containing degrees

Although this approach seemed promising at first, problems arose when rotating the camera slightly and switching controls. This led to incorrect results, and extracting Euler angles from the quaternion (setEulerFromQuaternion) also yielded inaccurate data.

While I could successfully toggle between the two control modes, I struggled to synchronize their rotation coordinates. Upon switching, the camera's position would be correct but its rotation would be off.

Further testing revealed some success with FirstPersonControls, which also use Euler angles. However, the method it uses for screen latitude and longitude calculation proved error-prone and failed completely when there was Z-axis rotation involved.

Answer №1

How about trying out this code snippet?

function onClick() {

    var prevCamera = camera;

    camera = new THREE.PerspectiveCamera(...);
    camera.position.copy( prevCamera.position );
    camera.rotation.copy( prevCamera.rotation );

    var MODE = { TRACKBALL: 0, FLY: 1 };

    switch( mode ) {

        case MODE.FLY:

            controls = new THREE.TrackballControls( camera );

            mode = MODE.TRACKBALL;

            break;

        case MODE.TRACKBALL:

            controls = new THREE.FlyControls( camera );

            mode = MODE.FLY;

            break;

    }

}

Answer №2

Creating a fresh camera provides a simple solution to release all the keyboard and mouse events that were configured with the previous controls. Failure to do so may result in orbitcontrols events triggering while in fly mode.

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

Enhance Website Speed by Storing PHP Array on Server?

Is there a way to optimize the page load time by storing a PHP array on the server instead of parsing it from a CSV file every time the page is reloaded? The CSV file only updates once an hour, so constantly processing 100k+ elements for each user seems un ...

Incorporating library files (css/js) into your app built on the angular-fullstack framework

After using a Yo Angular-Fullstack generator (https://github.com/DaftMonk/generator-angular-fullstack) to start an app, I attempted to install Toastr from bower with the command: bower install angular-toastr Now, I need to add the toastr css and js files ...

In JavaScript, when using the fetch function with JSON, it is possible to skip the

Here's an example of fetching review data from within a 'for loop': fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline') In this case, some products may not have reviews and will return a 404 response. Th ...

Adjust the styling of selected elements when their values are changed

I am attempting to modify the background color based on the selected value that is returned. However, my current code doesn't seem to be working as expected: <script> $(document).ready(function() { $('#assessments').change(functi ...

What is the best way to loop through an array inside an object stored within another array using *ngFor in Angular 2?

Overview: My game data is structured as an array called 'game' with seven objects representing each round. Each round object contains details like 'roundNumber', 'title', 'players', and 'winner'. The &apos ...

Rails 4 - Functional JS errors are absent yet JavaScript functionality is not operational

Currently, I am delving into the world of Ruby on Rails and making an effort to grasp the concept of the asset pipeline. As a means to learn more effectively, I decided to construct my website using Rails and learn along the way. However, after integrating ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

Unusual blue outline spotted on Firefox

Could you please review the following code snippet: http://www.jsfiddle.net/tt13/5CxPr/21 In Firefox, there is a strange blue border that appears when selecting multiple rows by pressing the ctrl button. However, this issue does not occur in Chrome. Thi ...

Creating a simulated loading screen

I have created a preloader page for my website following tutorials, such as the one found here: https://codepen.io/bommell/pen/OPaMmj. However, I am facing a challenge in making this preloader appear fake without using heavy content like images or videos. ...

Leveraging the power of Discord.js to verify the image URL within an embed

The concept My goal is to create a bot that can detect embedded images in messages and send a predetermined response if the image URL matches a specific URL provided. I am looking for a way to trigger this check whenever a message is sent with an embed. ...

gulp build task fails to execute properly due to Callback (cb) issue

My gulp build task is not functioning properly even though I have created three tasks for the final build directory: bulid:cleanfolder build:copy build:remove Gulp Build Task /****************************************** bulid task *********** ...

Learn how to utilize interpolation within an *ngIf statement in Angular 2 in order to access local template

Consider the following scenario; <div *ngFor="item of items; let i = index;"> <div *ngIf="variable{{i}}">show if variable{{i}} is true</div> </div> Suppose I have variables named "variable0", "variable1",... Is there a way to ac ...

Utilizing AJAX requests in PHP's MVC framework

I am currently working on a game site using a combination of php and javascript. All my classes and data are stored in php and then encoded into json format. The view calls a javascript file which, through an ajax request, retrieves the php data encoded in ...

Enhance the jQueryUI progress bar by dynamically updating it with inner HTML data

I am working on implementing a jQueryUI progress bar and facing some challenges. Here is the basic code for the progress bar: <script> $(function() { $("#progressbar").progressbar({ value: 50, }); }); </script& ...

Why isn't Material UI Data Grid onCellEditCommit working? Wondering if anyone has insight

Having trouble retrieving the data after editing using onCellEditCommit, but it's not functioning properly. This callback is triggered when changes to a cell are committed. Signature: function(params: GridCellEditCommitParams, event: MuiEvent, deta ...

Using ESLint to enforce snake_case naming conventions within TypeScript Type properties

When working with TypeScript, I prefer to use snake_case for properties within my Interfaces or Types. To enforce this rule, I have configured the ESLint rule camelcase as follows: 'camelcase': ["error", {properties: "never"}], Even though the E ...

Obtain information through ajax using an asynchronous function

When fetching data in the first example using ajax with XMLHttpRequest, everything works smoothly. example 1 let req = new XMLHttpRequest(); req.open( "GET", "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-tempe ...

The symbol in my Google Maps path is off-center and not aligned correctly

Hey everyone, I'm currently working on a project that involves a plane moving along a polyline, but I'm facing an issue where the path symbol is not centered as demonstrated in this image This is what I have: Here, I define the path symbol as t ...

Issue with variable not being refreshed within requestJS's data event

I have been attempting to store the response from a URL in a variable for caching purposes and then send it upon subsequent requests. I am currently writing to the variable during the data event of the request. The variable does get updated, but I am encou ...

Creating object pairings in JavaScript

function convertToPairs(object) { var keys = Object.keys(object); var values = Object.values(object); var finalResult = ""; for (var i = 0; i < keys.length; i++) { for (var j = 0; j < values.length; j++) { finalResult += keys[i] + ...