javascript, Utilizing three.js: A Guide to Animating the Camera's Field of View

I'm currently working through a tutorial on that focuses on tweening a camera's field of view in three.js. However, I've encountered an issue where the value doesn't seem to update as expected. Can anyone offer insight into what might be going wrong? Here is the relevant portion of my code:

    var fov = 70;
    var zoomFov = 100;

    function onDocumentMouseUp( event ) {
        castRay(); 
    }

    function castRay(){
        var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
        projector.unprojectVector( vector, camera );
        var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
        var intersects = ray.intersectObjects( objects );
        if ( intersects.length > 0 ) {
            var camObj = intersects[0].object;
            camTween = new TWEEN.Tween( fov ).to( zoomFov,500 ).easing( camEase );
            camTween.start();
            camTween.onUpdate(function(){
                updateCam(fov);
            });
        }
    }

    function updateCam(fov){
       console.log(fov); //MH - outputs 70 every time
    }

function animate() {

    requestAnimationFrame( animate );
    render();
    TWEEN.update();

}

Answer №1

I was able to resolve this issue by implementing the code below. It appears that the tween class requires a property of an object to be present in order for updates to occur smoothly.

let fieldOfView = 70;
let zoomFieldOfView = 10;
let currentFOV;
let cameraTween;

function launchRay(){
    let vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
    projector.unprojectVector( vector, camera );
    let ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
    let intersects = ray.intersectObjects( objects );
    if ( intersects.length > 0 ) {
        initializeTween();
    }
}

function initializeTween(){
    let updateFunction = function(){=
        camera.projectionMatrix.makePerspective( currentFOV.fov, window.innerWidth / window.innerHeight, 1, 1100 );
        render();
    }

    currentFOV = { fov: 70};
    TWEEN.removeAll();
    cameraTween = new TWEEN.Tween( currentFOV ).to( {fov: zoomFieldOfView}, 500 ).easing( camEase ).onUpdate(updateFunction);
    cameraTween.start();
}

function runAnimation() {

    requestAnimationFrame( runAnimation );
    render();
    TWEEN.update();

}

Answer №2

It seems like the issue lies in forgetting to execute camTween.update(). To address this, consider incorporating a render loop within your code snippet. The following snippet could potentially resolve the problem:

setInterval(function(){ 
    camTween.update(); 
}, 50);

If not, ensure to include a call to camTween.update() within your render loop.

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

How can I extract the minimum price from this array list using Reactjs?

In my ReactJS project, I have an array list structured like this. I am trying to find the minimum price from this list. For example, if 'totalll' is 100, how can I achieve that? Please advise on how to navigate through the array to retrieve the i ...

Ways to change columns into rows with CSS

Hey there! I'm looking for a way to convert columns into rows and vice versa. In my table, I have both column headers and row headers on the left side. The row headers are simply bold text placed next to each row to describe its content. I want to op ...

Navigating the path for the script src dynamically with the help of Angular.js and Javascript

I could really use some assistance. I am trying to dynamically set the js/css path name using Angular.js/Javascript/Jquery. Let me explain my code below. <script src="/crm/controller/productController.js" type="text/javascript"></script> Let& ...

The file-loader is able to organize images into separate folders when saving them. For example, an image file named "example.jpg" located in Project/Module

Hey there! I'm currently in the process of setting up a Webpack configuration that will generate files for each folder within my project. Unfortunately, creating a separate webpack.config file for each folder is not an option. So far, I have successf ...

animation of leaping to a specific element

I am currently working on a sidebar with links that have a hover effect to add a bullet. However, I want the bullet to smoothly follow the cursor's movement along the y-axis within the sidebar instead of jumping between the links. How can I achieve th ...

Trigger click events based on specific coordinates x and y in Fabric.js

While working on my project, I utilized three.js and fabric.js to manipulate textures on a 3D model. I managed to synchronize coordinates on the model with coordinates on the canvas in fabric js. However, I encountered an issue with simulating click events ...

What is the best way to mark a specific photo as a favorite in an array of Photo objects?

I am working with a basic array of photo categories that follows this structure: [ { category: 1001, photos: [ { id: 100101, url: 'url.com/100101', favorite: false}, { id: 100102, url: 'url.com/100102', favorite: ...

Typescript error: The 'datepicker' property is not found on the type 'IAugmentedJQuery'

Currently, I am working with AngularJS and Typescript. I encountered an error stating "Property 'datepicker' does not exist on type 'IAugmentedJQuery'.". Can someone please provide guidance on how to fix this issue? angular.element(&a ...

Presenting search results of images in the database without showing file extensions

I am encountering an issue with my autocomplete search box that displays image thumbnails from a database. The problem is that the .jpg extension appears each time the image name is shown in the autocomplete suggestions. Is there a way for me to modify the ...

Invoking a greasemonkey script when a user interacts with a button

For a script I wrote, I added an extra column and link in each row. However, the issue is that I want the links to trigger a function in my greasemonkey script and pass a variable to it. I have learned that because greasemonkey operates in a sandbox, achi ...

Issue with Highcharts: Overlapping yAxis labels when displaying multiple series data

I am facing an issue with a highchart that I have rendered for multiple series data. The y-axis labels are overlapping. Is there a way to resolve this problem? You can view the chart here: https://jsfiddle.net/sharadkalya/mhg52js4/ https://i.sstatic.net/ ...

Creating a CSS animation to mimic the fading in and out effect of the Mac scrollbar when scrolling begins

My journey begins with this: *::-webkit-scrollbar { } *::-webkit-scrollbar-button { } *::-webkit-scrollbar-track { } *::-webkit-scrollbar-track-piece { } *::-webkit-scrollbar-thumb:active { width: 6px; background-color: red; } *::-webkit-scr ...

Issue with the date picker UI in react-datetime not displaying correctly?

<Datetime dateFormat={false} className="form-control" onChange={this.handleChange.bind(this)}/> I am currently utilizing the react-datetime library for time selection handleChange(newtime){ this.setState({MTtime: moment(newtime).format ...

Is there a way to customize the animation for a button in material UI?

Trying to implement material UI in React and looking for a button that does not have the standard wave animation effect upon clicking, which you can see demonstrated here. Instead, I am searching for an animation that instantly fills the entire button wit ...

NextJS function utilizes its own references within React and automatically fetches data without the need for an import

I recently purchased this template and I'm trying to figure out which page the code snippet "{getLayout(<Component {...pageProps} />)}" is directed to during the initial load. It seems like it might be a global variable hidden somewher ...

choose multiple elements from an array simultaneously

Looking for help with a basic Array question and seeking the most effective solution. The scenario involves having an array: var pathArr = [element1, element2, element3, element4, element5, element6] If I want to select multiple elements from this array ...

Step-by-step guide on leveraging PubNub for facilitating group chat creation by users

I am currently working on developing a chat application utilizing PubNub. A key feature I am seeking to implement is the ability for individual users to create group chats, where they can add or remove members and designate admins. While I have come across ...

For JavaScript to run, it must be included in the HTML document and invoked externally using the <script src=...> tag

When it comes to my JavaScript code, I've encountered an interesting scenario where it only seems to run properly when it is both included in the HTML file and called externally like so: <script type="text/javascript" src="{{ url_fo ...

An issue occurred while attempting to access the Stripe checkout page

While working on my e-commerce website using next.js and stripe checkout, I encountered an error during the checkout process. I am utilizing the use-shopping-cart package, but suspect it may be causing the following response error from stripe-checkout: & ...

The height of the image is equal to the height of the phone/tablet - functioning correctly only in Chrome

, I'm currently fine-tuning my portfolio website with the help of responsive and adaptive design using mobile_detect.php. The challenge lies in getting the codes to align perfectly for desktop and handheld devices. To simplify testing on desktop befo ...