Tips on how to rewind a glTF animation in Three.js if it does not intersect with an object

I have been experimenting with incorporating a gltf model into a three js project and I'm wondering if there's a way to reverse a gltf animation when the mouse moves away from the model. Currently, I've managed to trigger the animation as the mouse hovers over the model, but now I'd like to play it in reverse when the mouse leaves the area. If anyone has any suggestions on how I can achieve this, I would greatly appreciate your input. Thank you.

import * as THREE from 'three'; 
import { GLTFLoader } from 'GLTFLoader';
import { OrbitControls } from 'OrbitControls';

// Setting up the 3D Scene
var scene = new THREE.Scene();
scene.background = new THREE.Color('black');
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();

// Defining Camera Perspective
var camera = new THREE.PerspectiveCamera( 25, window.innerWidth / 
window.innerHeight );
camera.position.set( 10, 1, 25 );

// Creating Renderer
var renderer = new THREE.WebGLRenderer({ alpha: false });
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// Initializing Orbitcontroller
var controls = new OrbitControls( camera, renderer.domElement );

// Adding Ambient Light
var ambientLight = new THREE.AmbientLight( 0xFFFFFF );
scene.add( ambientLight );

// Loading gltf model and initiating animation
var mixer;
var mouse = new THREE.Vector2(1, 1);
var loader = new GLTFLoader();
loader.load( './assets/itc.glb', function ( gltf ) {
var object = gltf.scene;
scene.add( object );
mixer = new THREE.AnimationMixer( object );
var action;
gltf.animations.forEach((clip) => {
    action = mixer.clipAction(clip);
    action.setLoop(THREE.LoopOnce);
    action.clampWhenFinished = true;
    action.play();
});


object.scale.set( 2, 2, 2 );
object.rotation.y = 37.0;
object.position.x = -10;                  
object.position.y = -5;                 
object.position.z = -15;                  

});


// Animation Function
const clock = new THREE.Clock();
function animate() {
    requestAnimationFrame( animate );

    raycaster.setFromCamera( pointer, camera );

    const intersects = raycaster.intersectObjects( scene.children );
    if (intersects.length){
      mixer.update(clock.getDelta());
    }
    else{
      // code for reversing animation upon mouse leaving the gltf model
    }
    renderer.render( scene, camera );
}

// Render Function
function render() {
 requestAnimationFrame(render);
 renderer.render( scene, camera );
}

// Handling Window Resize
var tanFOV = Math.tan( ( ( Math.PI / 180 ) * camera.fov / 2 ) );
var windowHeight = window.innerHeight;
window.addEventListener( 'resize', onWindowResize, false );
function onWindowResize( event ) {
camera.aspect = window.innerWidth / window.innerHeight;

camera.fov = ( 360 / Math.PI ) * Math.atan( tanFOV * ( 
window.innerHeight / windowHeight ) );
camera.updateProjectionMatrix();
camera.lookAt( scene.position );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.render( scene, camera );
}

function onPointerMove( event ) {
    pointer.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    pointer.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}


window.addEventListener( 'pointermove', onPointerMove );

render();
animate();

Answer №1

If you want to reverse an animation easily, simply change the timeScale property to -1. For example:

action.timeScale = -1;

Feel free to modify the timeScale property at any point in your code.

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

Ways to retrieve several parameters from a controller using Ajax Jquery in Codeigniter

I need to retrieve a list of images from a folder based on a specific ID. Currently, I am able to get the file names but I also require the upload path. Is there a way to obtain both sets of data using a single function? Javascript Code: listFilesOnServ ...

The combination of Next.JS and React Objects is not acceptable as a React child

Summary: Encountering the error Error: Objects are not valid as a React child (found: [object Promise]) while making a fetch request in a Typescript project. Interestingly, the same code snippet works without errors in a Javascript project. Recently, I ...

Troubles with deploying on Heroku

Every time I try to run my application on Heroku, all I see is: Heroku | Welcome to your new app! Refer to the documentation if you need help deploying. Because of this, I attempted to deploy my app to Heroku using this command: git push heroku master Ho ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

What is the best way to set a fixed width for my HTML elements?

I am facing an issue with my user registration form where error messages are causing all elements to become wider when they fail validation. I need help in preventing this widening effect. How can I achieve that? The expansion seems to be triggered by the ...

React application experiencing continuous SpeechRecognition API without stopping

I need assistance with integrating speech recognition into my web application using Web API's speech recognition feature. Below is the React code I am currently working with: import logo from './logo.svg'; import './App.css'; impor ...

Everlasting Dropdown in AngularJS Always Open Mode

I am currently working on my first AngularJS App and I am facing some issues with creating a Dropdown menu. Here is the HTML code I have: <div class="btn-group" dropdown> <button type="button" class="btn btn-danger">Action</button> & ...

Retrieving a boolean value from a function that includes an asynchronous AJAX request

In my calendar application, I am working with an array of dates: <div v-for="date in dates">{{ date }}</div> I want to apply a conditional class based on the outcome of an isWeekend() method that involves making an API call: <div v-for="d ...

Aurelia: Understanding the Integration of a View/ViewModel from an npm Package

We've decided to implement Aurelia for the frontend of our application. With multiple projects in the pipeline, we are looking to streamline the process by packaging our custom code into npm packages that can be easily integrated by developers. This w ...

Updating input value using React state

Hey there, I'm currently using a color picker to update my this.state.colorPicked value, which is working well. Now, I want to create a function that will concatenate the state's colorPicked value with the input field when called. If the input fi ...

What is the best way to refine the results from an AJAX request in Datatables?

I have successfully configured a Datatables plugin, set up a new table, and populated it with content using an AJAX call: var table= $("#mytable").DataTable({ ajax: "list.json", columns: [ {"data": "name"}, {"data": "location"}, ...

My jQuery code is encountering issues with the .each loop functionality

I have encountered an issue with the code snippet below, which is intended to hide the "IN STOCK" phrase on specific vendors' product pages. Upon testing, I noticed that the loop doesn't seem to be executing as expected when using console.log. Ca ...

How can you handle events on DOM elements that haven't been created yet in JavaScript?

In my JavaScript module, I have the following code: EntryController = function$entry(args) { MainView(); $('#target').click(function() { alert('Handler called!'); }); } The MainView() function includes a callback ...

Is there a way to dynamically hide specific ID elements in Javascript based on the size of the browser window?

I have spent countless hours searching for a solution to this issue without any success. The problem I am facing involves making certain elements on a webpage invisible when the browser window width is less than a specified size. The issue arises due to f ...

Verify whether a specific value exists in my React array; if it does, display a specific component

I need to display different components based on the following criteria: Whether the items contain a specific value And if all 10 items have that value const DisplayComponents = ({ data }: Props) => { const filteredItems = data.items?.filter( ( ...

What is the method for obtaining a unique id that changes dynamically?

Having trouble accessing the dynamically generated ID in jQuery? It seems to work fine in JavaScript but not in jQuery. Here's an example of the issue: My jQuery code: var img = $("#MAP"+current_img_height); $("#map").css({'height': img.h ...

Node.js, PHP, and the Express framework

I have a project where I need to develop a to-do list and a form that allows users to upload png files using Node.js. Currently, I am using the following packages: { "name": "todo", "version": "0.0.1", "private": true, "dependencies": { "ejs": ...

AngularJS - Issue with retrieving the most recent entry during $routeChangeStart event

I am utilizing the $routeChangeStart function to redirect authorized users to specific URLs and prevent unauthorized access to special pages. In addition, I have dynamically generated pages that can be accessed via their unique page slugs. To achieve this ...

Prevent inheriting styles with jQuery Else / If conditions

I'm seeking advice on how to prevent elements from retaining the same inline styles in different breakpoints. My goal is to adjust styling based on window width, similar to CSS media queries, but with the additional need to increment a numeric value ...

Mastering the art of chaining promises in Mongoose

I need help figuring out how to properly chain promises for a "find or create" functionality using mongodb/mongoose. So far, I've attempted the following: userSchema.statics.findByFacebookIdOrCreate = function(facebookId, name, email) { var self = ...