Setting the OrbitControls Position in ThreeJS

Currently, I am saving the position of the OrbitControls by using .getAzimuthalAngle() and .getPolarAngle(). In the future, I would like to update these angles with slightly different values.

I chose to utilize getAzimuthalAngle and getPolarAngle because I need to calculate the rotation percentage. For example, if the angle is 180°, it represents 50% of the total rotation. This information is crucial as I am adjusting the position of a 2D map in sync with the OrbitControls location. While I have managed to achieve this synchronization in one direction, the inability to set the position of the OrbitControls has become a roadblock for me.

Answer №1

After some clever work, I found a way to solve the issue by duplicating the OrbitControl Update function and directly setting theta and phi values instead of using incremental updates.

this.setPhiTheta = function(t, p) {
    var position = this.object.position;

    offset.copy( position ).sub( this.target );

    // rotate offset to "y-axis-is-up" space
    offset.applyQuaternion( quat );

    // angle from z-axis around y-axis

    theta = Math.atan2( offset.x, offset.z );

    // angle from y-axis

    phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );

    if ( this.autoRotate && state === STATE.NONE ) {

        this.rotateLeft( getAutoRotationAngle() );

    }

    /*theta = 3.105;
    phi = 1.48;*/
    theta = t;
    phi = p
    //console.log("theta " + theta)
    // restrict theta to be between desired limits
    theta = Math.max( this.minAzimuthAngle, Math.min( this.maxAzimuthAngle, theta ) );

    // restrict phi to be between desired limits
    phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) );

    // restrict phi to be betwee EPS and PI-EPS
    phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );

    var radius = offset.length() * scale;

    // restrict radius to be between desired limits
    radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) );

    // move target to panned location
    this.target.add( pan );

    offset.x = radius * Math.sin( phi ) * Math.sin( theta );
    offset.y = radius * Math.cos( phi );
    offset.z = radius * Math.sin( phi ) * Math.cos( theta );

    // rotate offset back to "camera-up-vector-is-up" space
    offset.applyQuaternion( quatInverse );

    position.copy( this.target ).add( offset );

    this.object.lookAt( this.target );

    //thetaDelta /= 1.2;
    //phiDelta /= 1.2;
    scale = 1;
    pan.set( 0, 0, 0 );

    // update condition is:
    // min(camera displacement, camera rotation in radians)^2 > EPS
    // using small-angle approximation cos(x/2) = 1 - x^2 / 8

    if ( lastPosition.distanceToSquared( this.object.position ) > EPS
        || 8 * (1 - lastQuaternion.dot(this.object.quaternion)) > EPS ) {

        this.dispatchEvent( changeEvent );

        lastPosition.copy( this.object.position );
        lastQuaternion.copy (this.object.quaternion );

    }
}

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

JavaScript encountered an issue while parsing XML: the format is not well-formed

I keep seeing an error message saying "Error parsing XML: not well-formed" when I encounter this line in my javascript code: for (var i=1; i<=totalImgs; i++) If I remove the < character from the line, the parsing error goes away. However, the javas ...

Issue with firing the React-Redux action has been encountered

I am currently utilizing React along with react-redux, redux and redux-actions. Within my application, I have a specific action that is responsible for verifying the validity of the token stored in localStorage to ensure it is not expired. This action loo ...

Ways to manage your javascript variables

Here is the code snippet I am working with: var json = jQuery.parseJSON(data); console.log(json) When I run this code, the output looks like this: Object {sql: "SELECT venta.cliente_tipodoc,count(*) AS cantidad FROM venta venta", results: Array[1], ...

Looking to subtly transition from the current webpage to the next one with a fading effect?

I'm looking to create a smooth transition between web pages on my site by slowly fading out the current page and fading in the next one when a link is clicked. $(document).ready(function() { $('body').css("display","none"); $(&a ...

Unable to establish API connection in node.js

As a novice, I recently delved into the world of APIs using node.js. My goal was to fetch data from a simple API for practice. This venture is just an experiment and any assistance or guidance on connecting to APIs, especially those requiring an API key, ...

The XMLHttpRequest only retrieves up to 32 descendant objects from the JSON file, not all of them

I've encountered a peculiar issue with my XMLHttpRequest and JSON file. While I can successfully access the data, it seems to only iterate through 32 child objects within each parent object. Take, for example, this snippet from the routes.json file: ...

When comparing TypeScript class functions with regular functions and variables, which one yields better performance?

When it comes to defining functions, is it better to use variables or functions directly? Also, how does this affect tree-shaking? I am dealing with a lot of calculation-intensive helper classes and I am unsure about the optimal approach in terms of memor ...

Enhancing 2D video viewing with Threejs interactivity

I want to create an interactive 2D video using three.js and maintain the aspect ratio of the video when resizing the browser window. Here is the code I am currently using: var camera, scene, renderer; var texture_placeholder, distance = 500; init() ...

Sending information to ajax request upon successful completion

I needed to transfer the output of the json_encode() function to jQuery. Once successful, I intended to refresh a specific division. Action: <a id="js-delete-file" href="#" data-url="<?php echo site_url('document_items/remove/'. $value[&a ...

HashRouter on Github pages is not rendering components as expected

Encountering issues with my React app deployed on GitHub Pages where components do not render using HashRouter. The "/" path displays a blank page and the "/about" path results in a 404 error. Here is a snippet from my app.js: function App() { return ( ...

Automatically Refreshing on Vue.js: Embracing the Passage of Time

I want to display this clock on Vue. The clock should automatically update the time, but how can I make this code work in Vue? Is there a simple way to implement this in Vue without using (document.getElementBy...) function updateTime () { document.ge ...

`Next.js project experiencing issues with scroll trigger functionality`

I've been working on a gsap animation with a scroll trigger, and while the animation itself functions fine, it's not triggering as expected. The AnimationEffect code involves using gsap and scrolltrigger to create the animation. The Hero section ...

Load the template.html file using pure JavaScript without relying on jQuery

At the moment, I am implementing a template load process in the following way: $('#mydiv').load("template1.html") While I am currently relying on jQuery for this functionality, I am curious to know how I can achieve the same outcome using pure ...

Adding wrapAll in jQuery or PHP after tags with identical IDs can be achieved by selecting all the target elements

web development <?php foreach ($forlop as $value) : ?> <?php $stringTitle = substr($value->getTitle(), 0, 1); ?> <?php if(is_numeric($stringTitle)){ echo "<h3 id ...

Listen for a click event on an Unordered List using addEventListener

Struggling to transform a for loop that iterates through an unordered list of hyperlinks and adds an 'onclick' function to each into one using an event listener instead. Unfortunately, I have not been able to create a functional solution. Below ...

How to leverage async/await within loops in Node.js for optimized performance and efficiency

Hey there, I'm working on my nodejs api where I need to fetch data inside a loop and then perform another loop to save data in a different table. Can anyone guide me on how to achieve this? Below is a snippet of what I have attempted so far without su ...

Enabling hover effects to scroll divs only when interacted with

I am aiming to achieve two separate scrolling divs and I'm uncertain about the exact approach. Experimenting with various overflow properties has only resulted in one scrolling independently. .profile { width: 100%; display: flex; ...

Static response is the way to go! Asynchronous responses just don't cut it

Currently in the process of developing an angular directive for displaying real-time charts. Below is the code snippet that encompasses everything, including link: function() { }, within the directive. Here's the code for a static directive that func ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

What are the steps to use the vue-text-highlight feature?

I am attempting to implement an example from the basic usage section of https://github.com/AlbertLucianto/vue-text-highlight. However, upon opening index.html in Firefox, I am only greeted with a blank page. You can find the code I am using at https://git ...