Undo the impacts caused by a Tween.js animation

I'm attempting to create a three.js block animation that reverts back to its original position once the animation is complete, utilizing tween.js.

Is it possible to achieve this using only one tween with tween.js?

I have managed to make it work with the following code snippet:

var initialPosition = {x: -200, y: 150, width: 1, height: 1, depth: 1, rotx: -0.5, roty: 0.7, rotz: 0.9};
var finalPosition = {x: 200, y: -100, width: 0.4, height: 3, depth: 8, rotx: 0.3, roty: -0.4, rotz: -0.6};
var resetPosition = {x: -200, y: 150, width: 1, height: 1, depth: 1, rotx: -0.5, roty: 0.7, rotz: 0.9};

var meshObject = new THREE.Mesh(
  new THREE.CubeGeometry(190, 45, 30),
  new THREE.MeshBasicMaterial({color: 0x444444}),
  0
);
meshObject.position.set(initialPosition.x, initialPosition.y, 0);
meshObject.rotation.set(initialPosition.rotx, initialPosition.roty, initialPosition.rotz);
scene.add(meshObject);

var firstTween = new TWEEN.Tween(initialPosition).to(finalPosition, 2000);
firstTween.onUpdate(function() {
  meshObject.position.set(initialPosition.x, initialPosition.y, 0);
  meshObject.scale.set(initialPosition.width, initialPosition.height, initialPosition.depth);
  meshObject.rotation.set(initialPosition.rotx, initialPosition.roty, initialPosition.rotz);
});
firstTween.easing(TWEEN.Easing.Quadratic.Out);
firstTween.onComplete(function() {secondTween.start();});

var secondTween = new TWEEN.Tween(finalPosition).to(resetPosition, 2000);
secondTween.onUpdate(function() {
  meshObject.position.set(finalPosition.x, finalPosition.y, 0);
  meshObject.scale.set(finalPosition.width, finalPosition.height, finalPosition.depth);
  meshObject.rotation.set(finalPosition.rotx, finalPosition.roty, finalPosition.rotz);
});
secondTween.easing(TWEEN.Easing.Quadratic.In);

firstTween.start();

The tweens are updated within my animation function:

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
  meshObject.__dirtyPosition = true;
  meshObject.__dirtyRotation = true;
  TWEEN.update();
}
animate();

Although the current setup works as expected, it feels inefficient and cumbersome to manage.

Any assistance or guidance would be greatly appreciated.

Answer №1

Don't complicate things by renaming properties like x, y, z to width, height, depth or rotx, roty, rotz. This just means you'll have to manually translate these properties onUpdate when you set scale.x = position.width and rotation.x = position.rotx. It's better to stick with the original x, y, z to avoid extra work.

// Use THREE.js "x, y, z" convention for start and target pos
var startPos = {x: -200, y: 150, z: 0};
var targetPos = {x: 200, y: -100, z: 0};

// Scale and rotation are also in "x, y, z"
var startScale = {x: 1, y: 1, z: 1};
var targetScale = {x: 0.4, y: 3, z: 8};

var startRot = {x: -0.5, y: 0.7, z: 0.9};
var targetRot = {x: 0.3, y: -0.4, z: -0.6};

// Set up mesh
var mesh = new THREE.Mesh(
  new THREE.CubeGeometry(190, 45, 30),
  new THREE.MeshBasicMaterial({color: 0x444444})
);
mesh.position.copy(startPos);
mesh.rotation.copy(startRot);
scene.add(mesh);

// Define easing shortcuts
var QuadOut = TWEEN.Easing.Quadratic.Out;
var QuadIn = TWEEN.Easing.Quadratic.In;

// Tween animations for position, rotation, and scale
var t1 = new TWEEN.Tween(mesh.position)
    .to(targetPos, 2000, QuadOut)
    .to(startPos, 2000, QuadIn);

var t2 = new TWEEN.Tween(mesh.rotation)
    .to(targetRot, 2000, QuadOut)
    .to(startRot, 2000, QuadIn);

var t3 = new TWEEN.Tween(mesh.scale)
    .to(targetScale, 2000, QuadOut)
    .to(startScale, 2000, QuadIn);

t1.start();
t2.start();
t3.start();

No need to modify __dirtyPosition during animate() as the tween updates the mesh properties directly.

function animate() {
    requestAnimationFrame(animate);
    TWEEN.update();
    renderer.render(scene, camera);
}
animate();

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

Eliminate all elements marked with a particular class when the user clicks outside of a

I am currently building upon a project that I previously started here. Essentially, what I'm doing is dynamically generating tooltip popups that appear next to a link when it is clicked. However, I now need these tooltips to close when any click even ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

Using third-party libraries like jQuery, CSS, and JavaScript in your React project by directly importing them into the index.html file can be a more efficient approach compared

When working with React, is it advisable to import external JavaScript, jQuery, and CSS files into the index.html file in the public folder? Are there any potential performance implications associated with this practice? I have utilized some jQuery functi ...

What steps should I take to re-enable a setInterval function after I have previously called clearInterval?

Below is the javascript code snippet I am working with: <script type="text/javascript"> var timer; $(document).ready(function () { timer = setInterval(updatetimerdisplay, 1000); $('.countdown').change(function () { timer ...

The issue of `req.flash()` returning an empty object in the `app.js` file seems to be resolved when used

When setting my flash messages inside the controller method like this: req.flash('info', 'flash is working'), I then use console.log(req.flash()) in the controller to verify if it works. However, upon passing it on to res.locals in my a ...

Gather and transfer array - AngularJS and PHP

Currently experimenting with the combination of AngularJS and PHP for CRUD operations. This is the function I am currently using in Angular: $scope.initCart = function () { $http({ method: 'post', url: url, data: $.param({ 'res ...

Issue: The variable 'HelloWorld' has been declared but not utilized

Why am I encountering an error when using TypeScript, Composition API, and Pug templating together in Vue 3? How do I resolve this issue when importing a component with the Composition API and using it in a Pug template? ...

Developing an ASP.NET message box feature with options for both "OK" and "Cancel

I have implemented a JavaScript function in my website to display a message box to the user: Private Sub MessageBox(ByVal msg As String) Dim lbl As New Label lbl.Text = "<script language='javascript'>" & Environment.NewLine &a ...

using db.eval() to call db.collection.find()

On my Node.js platform, I have created a JavaScript function that is executed within db.eval() on MongoDB. Here is the original JS function: function(data){ var d = { vehicle_id:data.vehicle_id, timestamp:{ $gte:data.start ...

Having trouble fetching data using $http and promises in AngularJS

I'm having trouble connecting to my RESTful API within my AngularJS application. Despite my efforts, I'm not seeing any data being displayed on the screen. It seems like I might be misunderstanding the usage of $http with promises. Any suggestio ...

Increasing the height of list items

I'm currently working on creating a scale using list items, and I want the height of each item to increase incrementally. So far, I haven't been able to find a solution other than adding a class to each item. Here's a fiddle demonstrating t ...

How to access selection range styles using JavaScript

It is common knowledge that we can retrieve the selection of text in JavaScript using the following method: var range = window.getSelection (); However, how can we obtain the style of this selection? For example, when I select bolded text or italicized ...

Ways to resolve the issue of missing data display in Angular when working with the nz-table

Below is the code snippet: <nz-table #listTable nzSize="middle" [nzData]="data"> <thead> <tr> <th nzShowExpand></th> <th>Location</th> <th>Device</th> ...

An undocumented finished status in Node.js

Currently diving into the world of node.js with the guidance of Node Cookbook. However, I've hit a roadblock when it comes to URL routing. Let's take a look at the code snippet provided in the book: var http = require('http'); var pat ...

Include a function call within a ternary operator in JSX code

I am looking to call a function within a ternary operator condition. Here is what my code looks like: {snapshot.Bid[0].Price !== 'undefined' ? `(${initialOrderInfo.snapshot.Bid[0].Price}` {renderCurrencySymb ...

Send a Dictionary<String, List<String>> object to JavaScript

I am looking to send a Dictionary> from the server to the client using JavaScript. Although I came across this post, I am still unsure about the steps to follow. To clarify my objective, the dictionary comprises the 'name' key of all workshee ...

Unable to navigate using ui-sref or $state.go in initial directive execution

There seems to be an issue with my ng-repeat on a directive where I'm passing in 3 pieces of information. The directive includes a button that is supposed to pass that information on to another view using params like this: ui-sref='profiles.sho ...

Error: SVG variable not found in react-native-react-apexchart library for React Native

Error: The module "node_modules\react-apexcharts\dist\react-apexcharts.min.js" is causing an exception: ReferenceError: SVG variable not found I have researched this error, but I could not find a proper solution. Here is my package.json fil ...

What is the method for presenting an integer column from a specific table to a user on the front end as a series that automatically increments from 1?

I'm currently developing a comprehensive full-stack application designed to function as a task and project management tool. It features a table layout with a convenient drag and drop functionality that enables upper-management to easily re-prioritize ...

Sliding elements horizontally with jQuery from right to left

I recently purchased a WordPress theme and I'm looking to customize the JavaScript behavior when the page loads. Currently, my titles animate from top to bottom but I want to change this behavior dynamically. You can view it in action here: I have ...