Tween. js User Guide-animation library used with Three. js

Source: Internet
Author: User

Tween. js User Guide-animation library used with Three. js

Tween. js User Guide-animation library used with Three. js

Beautiful Life of the sun and fire god (http://blog.csdn.net/opengl_es)

This article follows the "signature-non-commercial use-consistency" creation public agreement

Reprinted please keep this sentence: Sun huoshen's beautiful life-this blog focuses on Agile development and mobile and IOT device research: iOS, Android, Html5, Arduino, pcDuino, otherwise, this blog post is rejected or reprinted. Thank you for your cooperation.


Learning Three. js-Tween. js for Smooth Animation

Tween. js User Guide
Tween. js user guide

Note: This is a ongoing task. Please forgive me for the shortcomings. Whenever you see the content marked as TODO, it indicates that it is not done yet. If you have something unclear or lack details, submit a question to help make this guide better. Or if you think you can help, you can submit your own instructions or improvements at will.
NOTE this is a work in progress, please excuse the gaps. wherever you see something marked as TODO, it's not done yet. if you something is unclear or missing details, please file an issue and help make this guide better. or feel free to submit clarifications or improvements of your own if you feel you can help too!

What is a complementary animation? How do they work? Why do you want to use them?
What is a tween? How do they work? Why do you want to use them?

A tween (from in-between) is a concept that allows you to change the values of the properties of an object in a smooth way. you just tell it which properties you want to change, which final values shoshould they have when the tween finishes running, and how long shoshould this take, and the tweening engine will take care of finding the intermediate values from the starting to the ending point. for example, suppose you havepositionObjectxAndyCoordinates:

var position = { x: 100, y: 0 }

If you wanted to changexValue from100To200, You 'd do this:

// Create a tween for position firstvar tween = new TWEEN.Tween(position);// Then tell the tween we want to animate the x property over 1000 millisecondstween.to({ x: 200 }, 1000);

Actually this won't do anything yet. The tween has been created but it's not active. You need to start it:

// And set it to starttween.start();

Finally in order to run as smoothly as possible you shoshould callTWEEN.updateFunction in the same main loop you're using for animating. This generally looks like this:

animate();function animate() {    requestAnimationFrame(animate);    // [...]    TWEEN.update();    // [...]}

This will take care of updating all active tweens; after 1 second (I. e. 1000 milliseconds)position.xWill be200.

But unless you print the valuexTo the console, you can't see its value changing. You might want to useonUpdateCallback:

tween.onUpdate(function() {    console.log(this.x);});

This function will be called each time the tween is updated; how often this happens depends on each factors -- how fast (and how busy !) Your computer or device is, for example.

So far we 've only used tweens to print values to the console, but you can use it for things such as animating positions of three. js objects:

var tween = new TWEEN.Tween(cube.position);        .to({ x: 100, y: 100, z: 100 }, 10000)        .start();animate();function animate() {    requestAnimationFrame(animate);    TWEEN.update();    threeRenderer.render(scene, camera);}

In this case, because the three. js renderer will look at the object's position before rendering, you don't need to use an explicitonUpdateCallback.

You might have noticed something different here too: we're chaining the tween function CILS! Each tween function returns the tween instance, so you can rewrite the following code:

var tween = new TWEEN.Tween(position);tween.to({ x: 200 }, 1000);tween.start();

Into this

var tween = new TWEEN.Tween(position)    .to({ x: 200 }, 1000)    .start();

You'll see this a lot in the examples, so it's good to be familiar with it! Check 04-simplest for a working example.


Use tween. js Animation
Animating with tween. js

Tween. js doesn' t run by itself. You need to tell it when to run, by explicitly callingupdateMethod. The recommended method is to do this inside your main animation loop, which shoshould be calledrequestAnimationFrameFor getting the best graphics performance:

We 've seen this example before:

animate();function animate() {    requestAnimationFrame(animate);    // [...]    TWEEN.update();    // [...]}

If called without parameters,updateWill determine the current time in order to find out how long has it been since the last time it ran.

However you can also pass an explicit time parameterupdate. Thus,

TWEEN.update(100);

Means "update with time = 100 milliseconds ". you can use this to make sure that all the time-dependent functions in your code are using the very same time value. for example suppose you 've got a player and want to run tweens in sync. youranimateCode cocould look like this:

var currentTime = player.currentTime;TWEEN.update(currentTime);

We use explicit time values for the unit tests. You can have a look at TestTweens to see how we call TWEEN. update () with different values in order to simulate time passing.


Controls a compensation Animation
Controlling a tween Start and Stop
Start
And stop

So far we 've learned aboutTween.startMethod, but there are more methods that control individual tweens. Probably the most important one isstartCounterpart:stop. If you want to cancel a tween, just call this method over an individual tween:

tween.stop();

Stopping a tween that was never started or that has already been stopped has no effect. No errors are thrown either.

ThestartMethod also acceptstimeParameter. If you use it, the tween won't start until that particle moment in time; otherwise it will start as soon as possible (I. e. on the next callTWEEN.update).

Update
Update

Individual tweens also haveupdateMethod --- this is in fact calledTWEEN.update. You generally don't need to call this directly, but might be useful if you're doing crazy hacks.


Link
chain

Things get more interesting when you sequence different tweens in order, I. e. setup one tween to start once a previous one has finished. we call this chaining tweens, and it's done withchainMethod. Thus, to maketweenBStart aftertweenAFinishes:

tweenA.chain(tweenB);

Or, for an infinite chain, settweenATo start oncetweenBFinishes:

tweenA.chain(tweenB);tweenB.chain(tweenA);

Check Hello world to see an example of these infinite chains.


Repeated
repeat

If you wanted a tween to repeat forever you cocould chain it to itself, but a better way is to userepeatMethod. It accepts a parameter that describes how many repetitions you want:

tween.repeat(10); // repeats 10 times and stopstween.repeat(Infinity); // repeats forever

Check the Repeat example.


Jiule
yoyo

This function only has effect if used alongrepeat. When active, the behaviour of the tween will be like a yoyo, I. e. it will bounce to and from the start and end values, instead of just repeating the same sequence from the beginning.

Latency
Delay

More complex arrangements might require delaying a tween before it actually starts running. You can do that usingdelayMethod:

tween.delay(1000);tween.start();

Will start executing 1 second afterstartMethod has been called.

Controls all the supplementary animations
Controlling all the tweens

The following methods are found in the TWEEN global object, and you generally won't need to use most of them, should tupdate.

TWEEN.update(time)

We 've already talked about this method. It is used to update all the active tweens.

IftimeIs not specified, it will use the current time.

TWEEN.getAllAnd TWEEN.removeAll

Used to get a reference to the activetweensArray and to remove all of them from the array with just one call, respectively.

TWEEN.add(tween)And TWEEN.remove(tween)

Used to add a tween to the list of active tweens, or to remove an specific one from the list, respectively.

These methods are usually used internally only, but are exposed just in case you want to do something funny.


Modify the easing function (AKA make it councy)
Changing the easing function (AKA make it bouncy)

Tween. js will perform the interpolation between values (I. e. the easing) in a linear manner, so the change will be directly proportional to the elapsed time. this is predictable but also quite uninteresting ally wise. worry not -- this behaviour can be easily changed usingeasingMethod. For example:

tween.easing(TWEEN.Easing.Quadratic.In);

This will result in the tween slowly starting to change towards the final value, accelerating towards the middle, and then quickly reaching its final value. In contrast,TWEEN.Easing.Quadratic.OutWocould start changing quickly towards the value, but then slow down as it approaches the final value.


Available easing Functions
Available easing functions: TWEEN.Easing

There are a few existing easing functions provided with tween. js. they are grouped by the type of equation they represent: Linear, Quadratic, Cubic, Quartic, Quintic, Sinusoidal, Exponential, Circular, Elastic, Back and Bounce, and then by the easing type: in, Out and InOut.

Probably the names won't be saying anything to you unless you're familiar with these concepts already, so it is probably the time to check the Graphs example, which graphs all the curves in one page so you can compare how they look at a glance.

Credit where credit is due: these functions are derived from the original set of equations that Robert Penner graciously made available as free software a few years ago, but have been optimised to play nicely with JavaScript.

Use the custom easing Function
Using a custom easing function

Not only can you use any of the existing functions, but you can also provide your own, as long as it follows a couple of conventions:

  • It must accept one parameter:
    • k: The easing progress, or how far along the duration of the tween we are. Allowed values are in the range [0, 1].
    • It must return a value based on the input parameters.

      The easing function is only called once per tween on each update, no matter how many properties are to be changed. the result is then used with the initial value and the difference (the deltas) between this and the final values, as in this pseudo code:

      easedElapsed = easing(k);for each property:    newPropertyValue = initialPropertyValue + propertyDelta * easedElapsed;

      For the performance obsessed people out there: the deltas are calculated only whenstart()Is called on a tween.

      So let's suppose you wanted to use a custom easing function that eased the values but appplied a Math. floor to the output, so only the integer part wocould be returned, resulting in a sort of step-ladder output:

      function tenStepEasing(k) {    return Math.floor(k * 10) / 10;}

      And you cocould use it in a tween by simply calling its easing method, as we 've seen before:

      tween.easing(tenStepEasing);

      Check the graphs for easm easing functions example to see this in action (and also some metaprogramming for generating step functions ).


      Callback
      Callbacks

      Another powerful feature is to be able to run your own functions at specific times in each tween's life cycle. This is usually required when changing properties is not enough.

      For example, suppose you're trying to animate some object whose properties can't be accessed directly but require you to call a setter instead. You can useupdateCallback to read the new updated values and then manually call the setters:

      var trickyObjTween = new TWEEN.Tween({    propertyA: trickyObj.getPropertyA(),    propertyB: trickyObj.getPropertyB()})    .to({ propertyA: 100, propertyB: 200 })    .onUpdate(function() {        this.setA( this.propertyA );        this.setB( this.propertyB );    });

      Or imagine you want to ensure the values of an object are in an specific state each time the tween is started. You'll assignstartCallback:

      var tween = new TWEEN.Tween(obj)    .to({ x: 100 })    .onStart(function() {        this.x = 0;    });

      The scope for each callback is the tweened object.

      Callback at startup
      OnStart

      Executed right before the tween starts-i.e. before the deltas are calculated. This is the place to reset values in order to have the tween always start from the same point, for example.

      Callback upon stopping
      OnStop

      Executed when a tween is explicitly stopped (not when it is completed normally), and before stopping any possible chained tween.

      Callback during update
      OnUpdate

      Executed each time the tween is updated, after the values have been actually updated.

      Callback upon completion
      OnComplete

      Executed when a tween is finished normally (I. e. not stopped ).

      Advanced Animation
      Advanced tweening Relative Value
      Relative values

      You can also use relative values when usingtoMethod. when the tween is started, Tween. js will read the current property values and apply the relative values to find out the new final values. but you need to use quotes or the values will be taken as absolute. let's see this with an example:

      // This will make the `x` property be 100, alwaysvar absoluteTween = new TWEEN.Tween(absoluteObj).to({ x: 100 });// Suppose absoluteObj.x is 0 nowabsoluteTween.start(); // Makes x go to 100// Suppose absoluteObj.x is -100 nowabsoluteTween.start(); // Makes x go to 100// In contrast...// This will make the `x` property be 100 units more,// relative to the actual value when it startsvar relativeTween = new TWEEN.Tween(relativeObj).to({ x: "+100" });// Suppose relativeObj.x is 0 nowrelativeTween.start(); // Makes x go to 0 +100 = 100// Suppose relativeObj.x is -100 nowrelativeTween.start(); // Makes x go to -100 +100 = 0

      Check 09_relative_values for an example.

      Population to array value
      Tweening to arrays of values

      In addition to tweening to an absolute or a relative value, you can also have Tween. js change properties each ss a series of values. to do this, you just need to specify an array of values instead of a single value for a property. for example:

      var tween = new TWEEN.Tween(relativeObj).to({ x: [0, -100, 100] });

      Will makexGo from its initial value to 0,-100 and 100.

      The way these values are calculated is as follows:

      • First the tween progress is calculated as usual
      • The progress (from 0 to 1) is used as input for the interpolation function
      • Based on the progress and the array of values, an interpolated value is generated

        For example, when the tween has just started (progress is 0), the interpolation function will return the first value in the array. when the tween is halfway, the interpolation function will return a value approximately in the middle of the array, and when the tween is at the end, the interpolation function will return the last value.

        You can change the interpolation function withinterpolationMethod. For example:

        tween.interpolation( TWEEN.Interpolation.Bezier );

        The following values are available:

        • TWEEN. Interpolation. Linear
        • TWEEN. Interpolation. bezr
        • TWEEN. Interpolation. CatmullRom

          The default isLinear.

          Note that the interpolation function is global to all properties that are tweened with arrays in the same tween. you can't make property A change with an array and a Linear function, and property B with an array too and a bezr function using the same tween; you shoshould use two tween objects running over the same object but modifying different properties and using different interpolation functions.

          Check 06_array_interpolation for an example.


          Optimal Performance
          Getting the best performance

          While Tween. js tries to be used t on its own, nothing prevents you from using it in a way that is counter=t. here are some of the ways you can avoid slowing down your projects when using Tween. js (or when animating in the web, in general ).

          Use high-performance CSS
          Use counter t CSS

          When you try to animate the position of an element in the page, the easiest solution is to animatetopAndleftStyle properties, like this:

          var element = document.getElementById('myElement');var tween = new TWEEN.Tween({ top: 0, left: 0 })    .to({ top: 100, left: 100 }, 1000)    .onUpdate(function() {        element.style.top = this.top + 'px';        element.style.left = this.left + 'px';    });

          But this is really inefficient because altering these properties forces the browser to recalculate the layout on each update, and this is a very costly operation. Instead of using these, you should usetransform, Which doesn' t invalidate the layout and will also be hardware accelerated when possible, like this:

          var element = document.getElementById('myElement');var tween = new TWEEN.Tween({ top: 0, left: 0 })    .to({ top: 100, left: 100 }, 1000)    .onUpdate(function() {        element.style.transform = 'translate(' + this.left + 'px, ' + this.top + 'px);';    });

          If you want to read more about this, have a look at this article.

          However, if your animation needs are that simple, it might be better to just use CSS animations or transitions, where applicable, so that the browser can optimise as much as possible. tween. js is most useful when your animation needs involve complex arrangements, I. e. you need to sync several tweens together, have some start after one has finished, loop them a number of times, etc.

          Garbage Collection (alias GC)
          Be good to the Garbage collector (alias the GC)

          If you useonUpdateCallback, you need to be very careful with what you put on it. this function will be called when times per second, so if you're doing costly operations on each update, you might block the main thread and cause horrible jank, or --- if your operations involve memory allocations, you'll end up getting the garbage collector to run too often, and cause jank too. so just don't do either of those things. keep youronUpdateCallbacks very lightweight, and be sure to also use a memory profiler while you're developing.

          Super compensation Animation
          Crazy tweening

          This is something you might not use often, but you can use the tweening equations outside of Tween. js. they're just functions, after all. so you cocould use them to calculate smooth curves as input data. for example, they're used to generate audio data in this experiment.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.