The concept of tweening camera.lookat in Three.js

Struggling to smoothly tween the camera.lookAt method in Three.js using Tween.js. The current implementation rotates the camera directly to the object's position.

Here is the code snippet that sort of works:

    selectedHotspot = object;

    var tween = new TWEEN.Tween(camera.lookAt(object.position), 600).start();

However, the rotation isn't as smooth as desired. How can a smoother transition be achieved?

This function handles rendering:

function update() {

    lat = Math.max(-85, Math.min(85, lat));
    phi = THREE.Math.degToRad(90 - lat);
    theta = THREE.Math.degToRad(lon);

    target.x = 512 * Math.sin(phi) * Math.cos(theta);
    target.y = 512 * Math.cos(phi);
    target.z = 512 * Math.sin(phi) * Math.sin(theta);


    if (!selectedHotspot)
        camera.lookAt(target);


    renderer.render(scene, camera);

}

UPDATE

After further testing, it seems I am unable to properly tween the camera. There might be another issue lingering. Is there something missing from the render function?

Answer №1

To achieve the desired effect in your code, consider implementing it like this:

// Save original rotation
var initialRotation = new THREE.Euler().copy( camera.rotation );

// Set final rotation (using lookAt)
camera.lookAt( object.position );
var targetRotation = new THREE.Euler().copy( camera.rotation );

// Reset to initial rotation
camera.rotation.copy( initialRotation );

// Tween animation
new TWEEN.Tween( camera ).to( { rotation: targetRotation }, 600 ).start();

Answer №2

A modified version of mrdoob's solution using quaternions

// store initial rotation
var originalRotation = camera.quaternion.clone();

// calculate desired rotation (using lookAt)
camera.lookAt( target );
var finalRotation = camera.quaternion.clone();

// reset to initial rotation
camera.quaternion.copy( originalRotation );

// Apply Tween for smooth transition
var rotationTween = new TWEEN.Tween( camera.quaternion ).to( finalRotation, 600 ).start();

Answer №3

Using a positional tween in my code for smooth camera movement, I have implemented this function with a duration parameter:

function createSmoothTransition (currentPosition, targetPosition, duration)
{
    TWEEN.removeAll();    // clears previous tweens if any

    new TWEEN.Tween(currentPosition)
        .to(targetPosition, duration)
        .easing(TWEEN.Easing.Bounce.InOut)
        .onUpdate(function() {
            // update camera position during tween
            camera.position.copy(currentPosition);
        })
        .start();
}

This function is invoked like this:

createSmoothTransition(camera.position.clone(), new THREE.Vector3(x, y, z), 7500);

This results in a 7.5-second gradual transition.

Answer №4

Thank you everyone,

After struggling with tweening the camera, I decided to implement a different approach

if (target.y < selectedHotspot.position.y - 2)
        lat += 0.1;
    else if (target.y > selectedHotspot.position.y + 2)
            lat -= 0.1; 

    if (target.x < selectedHotspot.position.x - 5)
        lon += 0.5;
    else if (target.x > selectedHotspot.position.x + 5)
        lon -= 0.5;
    else {

        camera.lookAt(selectedHotspot.position);

        if (camera.fov > selectedHotspot.bubble.distance*0.05){
            camera.fov -= 0.1;

        }
        if(sceneReady)
            loadScene();
    }

    camera.updateProjectionMatrix();

This logic was integrated into a function called within the render loop, yielding successful results.

Answer №5

Utilizing controls.target for tweening the rotation of the camera has been highly effective in my project.

createjs.Tween.get(controls.target)
.to({
  x: tweenPos.x + 4,
  y: tweenPos.y - 9,
  z: tweenPos.z + 0.002
}, 900, createjs.Ease.linear);

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

Clicking on the initial link will in turn prompt clicks on the subsequent links

Can you please provide instructions on how to correctly simulate a click on the remaining links if a click is made on the first link? jQuery('a.one_num').click(function() { jQuery('a.two_num').click(); jQuery('a.three_num&ap ...

What is the best way to access a DOM node within a withStyle component?

Currently, I am involved in a react project where my team and I are utilizing Material UI. I encountered a situation where I needed to access the DOM node of another component that was wrapped by a HOC. To achieve this, I attempted using ref in React but o ...

.npmignore failing to exclude certain files from npm package

I'm facing an issue with a private module on Github that I am adding to my project using npm. Despite having a .npmignore file in the module, the files specified are not being ignored when I install or update it. Here is what my project's packag ...

Attempting to utilize Vue js to connect to an API

I'm currently facing difficulties while trying to access an API in order to retrieve data. As a novice in the world of vue.js and javascript, I encountered an error message saying Uncaught SyntaxError: Invalid shorthand property initializer. Unfortuna ...

jquery survey quiz

Currently, I am attempting to develop a jQuery questionnaire, but my limited knowledge in the area is proving to be quite inadequate. So far, here is what I have: Upon clicking on "Questions," a pop-up window will appear with two questions. My goal is t ...

Footer div is being covered by the page

I am currently working on a website built with "WordPress", and I have implemented a mobile footer plugin that is designed to only appear on mobile devices. However, I am encountering an issue where the page content overlaps the footer on phones. I attemp ...

View the gathered HTML content in a fresh browser tab

I'm looking to enhance the reporting system on my website by sending an AJAX request with a progress bar. The server will collect the necessary data, convert it into HTML, and then send it back to me. Upon successful completion of the AJAX request, I ...

Not all divs are triggering the hover event as expected

I am facing an issue while creating a webpage with overlapping background and content divs. The hover event works properly on the div with the class "content," but not on the div with the class "background." There is no interference with the event in the J ...

Obtain the dimensions of the outermost layer in a JSON file

Could you please help me extract the dimensions (600*600) of the outermost layer from the JSON below dynamically? { "path" : "shape\/", "info" : { "author" : "" }, "name" : "shape", "layers" : [ { ...

Alter the navigation but keep the URL intact without modifying the view

I have an Angular project that includes a login component. The login component is located in the directory app/main/login. I am trying to navigate to the login component from app.component.html using a button. Below is the code snippet from my app-routi ...

Unable to execute any actions on object in JavaScript

I currently have two functions in my code: getRawData() and getBTRawData(). The purpose of getBTRawData() function is to retrieve data from Bluetooth connected to a mobile device. On the other hand, getRawData() function takes the return value from getB ...

challenges surrounding the use of getElementByTagName

Within my webpage, I have implemented two select elements, both containing multiple options. However, I am facing an issue where I can only access the options from the first select box using getElementByTagName("options"), and unable to retrieve the option ...

I can't seem to get anything to show up on my React

After starting to work with routing on react.JS, I encountered a challenge where the simple products.jsx file is supposed to display a simple message upon clicking, but it's not showing anything. Here is the code from Index.JS import React from &apos ...

Jest - experiencing intermittent test failures on initial run, yet succeeding on subsequent runs

Writing tests with jest and supertest npm on a node server has been a challenge for me. When I try to run all the tests together, some of them fail inexplicably: https://i.sstatic.net/TWDVp.png However, if I selectively run only the failed tests in the t ...

Discovering the specific DOM element that has been clicked using only JavaScript

Looking to enhance my HTML document with interactivity, I wanted to achieve a feature where clicking on a div element would display its respective id. I attempted the following approach: window.onload = function() { associateIds(); clicked(); } fu ...

The use of HTML5 required attribute is ineffective when submitting forms via AJAX

Seeking advice on implementing basic validation for a newsletter form that only requires an email address. The current page layout doesn't allow space for jQuery error messages, so I attempted to use the HTML 5 required attribute. However, the form st ...

The content section sits discreetly behind the sidebar

Upon loading my Bootstrap 5 webpage, the toggle button successfully moves the navbar and body section to show or hide the full sidebar. However, an issue arises where the body section goes behind the sidebar when using the toggle button. Below is a portio ...

Is there a jQuery function that can produce repeated output and append content with each successive click?

Attempting to implement a dynamic searchbar with various parameters has led me to explore using jQuery to load and clone the searchbar file in order to append it to the body dynamically. I have made several attempts to modify selectors without achieving t ...

Update the useState function individually for every object within an array

After clicking the MultipleComponent button, all logs in the function return null. However, when clicked a second time, it returns the previous values. Is there a way to retrieve the current status in each log within the map function? Concerning the useEf ...