Iavra

Iavra Animate Everything

Oct 23rd, 2015 (edited)
1,917
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*:
  2.  * =============================================================================
  3.  * Iavra Animate Everything.js
  4.  * =============================================================================
  5.  *
  6.  * @plugindesc Provides a generic way to animate every float property on every object.
  7.  * <Iavra Animate Everything>
  8.  * @author Iavra
  9.  *
  10.  * @param Enable Persistence
  11.  * @desc If set to true, running animations will be stored in the savefile and continued after loading.
  12.  * @default false
  13.  *
  14.  * @help
  15.  * To animate an object a new Tween has to be created and started like this:
  16.  * var myTween = new IAVRA.ANIMATE.Tween(object, {_x : 100}).duration(50).start();
  17.  *
  18.  * This will cause the property "_x" of "object" to change from its current value to 100 over the next
  19.  * 50 frames, using linear easing (default).
  20.  *
  21.  * The IAVRA.ANIMATE.Tween class contains the following functions:
  22.  *
  23.  * start()              Starts the animation.
  24.  * stop()               Stops the animation. It can be restarted, but the current progress isn't saved.
  25.  * pause()              Pauses the animation. It can be resumed at any time by calling resume().
  26.  * resume()             Resumes the animation that has previously been pause()-d.
  27.  * easing(easing)       Specified the easing function to be used by the tween. By default, linear (no)
  28.  *                      easing is used. An easing function takes a single parameter k, which is defined as
  29.  *                      t/d, meaning "current animation step" / "total duration" and can range from 0.0 to
  30.  *                      1.0. It must return a value of X, which will be used to calculate the current
  31.  *                      value as: start + (end - start) * X.
  32.  * duration(duration)   Sets the animation duration. The default value is 1 and causes the animation to
  33.  *                      complete instantly. Values lower than 1 will throw an error.
  34.  * delay(delay)         Causes the animation to pause for a given number of steps and can either be used
  35.  *                      to delay the start of the animation or to pause it during its execution. Values
  36.  *                      lower than 1 have no effect.
  37.  * onStart(callback)    Registers a callback, which will be invoked when the animation starts.
  38.  *                      The callback receives the animated object as a parameter.
  39.  * onUpdate(callback)   Registers a callback, which will be invoked when the animation proceeds
  40.  *                      by one step. The callback receives the animated object as a parameter.
  41.  * onComplete(callback) Registers a callback, which will be invoked when the animation completes.
  42.  *                      The callback receives the animated object as a parameter.
  43.  * onStop(callback)     Registers a callback, which will be invoked when the tween's stop() function is
  44.  *                      called. The callback receives the animated object as a parameter.
  45.  * chain(...)           Takes any number of IAVRA.ANIMATE.TWEEN objects, that will be started once this
  46.  *                      animation completes. Please ensure not to call start() on the chained objects, as
  47.  *                      this would cause them to be started twice.
  48.  * access(get, set)     Takes 2 callback functions, that will be used to read and write properties on the
  49.  *                      object being animated. The get callback takes 2 parameters, the object and name
  50.  *                      of the property being read. The set callback takes 3 parameters, the object, the
  51.  *                      name of the property to write and the value it should be set to.
  52.  *
  53.  * All functions return the Tween object itself and can be used for chaining.
  54.  *
  55.  * The IAVRA.ANIMATE module contains the following functions:
  56.  *
  57.  * clear()              Forcefully stops all currently running animations without triggering callbacks or
  58.  *                      starting chained tweens.
  59.  *
  60.  * By default, animations are saved locally and get lost after saving and loading the game. The parameter
  61.  * "Enable Persistence" changes this and stores all animations in the savefile. Note that JSON.stringify()
  62.  * (which MV uses as its save mechanism) discards functions, which means that registered callbacks are lost
  63.  * after loading a game.
  64.  */
  65.  
  66. var Imported = Imported || {};
  67. Imported["iavra_animate"] = true;
  68.  
  69. //=============================================================================
  70. // namespace IAVRA
  71. //=============================================================================
  72.  
  73. var IAVRA = IAVRA || {};
  74.  
  75. (function() {
  76.     "use strict";
  77.  
  78.     /**
  79.      * Loads plugin parameters. We are using our own solutions which bypasses the
  80.      * PluginManager, but is independent from the actual filename.
  81.      *
  82.      */
  83.     var params = (function($) {
  84.         return {
  85.             enablePersistence: $['Enable Persistence'].toLowerCase() === 'true'
  86.         };
  87.     })($plugins.filter(function(plugin) {
  88.         return plugin.description.indexOf('<Iavra Animate Everything>') != -1;
  89.     })[0].parameters);
  90.  
  91.     /**
  92.      * Depending on the "Enable Persistence" parameter, we either store tweens locally
  93.      * or in $gameSystem.
  94.      */
  95.     var getTweens;
  96.     if(params.enablePersistence) {
  97.         getTweens = function() {
  98.             return $gameSystem.iavra_animate_tweens;
  99.         };
  100.     } else {
  101.         var _tweens = [];
  102.         getTweens = function() {
  103.             return _tweens;
  104.         }
  105.     }
  106.    
  107.     /**
  108.      * Adds a new tween.
  109.      */
  110.     var addTween = function(tween) {
  111.         getTweens().push(tween);
  112.     };
  113.    
  114.     /**
  115.      * Removes a tween.
  116.      */
  117.     var removeTween = function(tween) {
  118.         var index = getTweens().indexOf(tween);
  119.         if(index !== -1) {
  120.             getTweens().splice(index, 1);
  121.         }
  122.     };
  123.    
  124.     //=============================================================================
  125.     // namespace IAVRA.ANIMATE
  126.     //=============================================================================
  127.    
  128.     IAVRA.ANIMATE = {
  129.        
  130.         /**
  131.         * Deletes all tweens, effectively stopping them (but without triggering any
  132.         * existing callbacks).
  133.         */
  134.         clear: function() {
  135.             getTweens().splice(0, getTweens().length);
  136.         },
  137.        
  138.         /**
  139.         * Updates all registered tweens, deleting those from the array whose update()-
  140.         * function return false.
  141.         */
  142.         update: function() {
  143.             for(var index = getTweens().length - 1; index >= 0; index--) {
  144.                 if (!getTweens()[index].update()) {
  145.                     getTweens().splice(index, 1);
  146.                 }
  147.             }
  148.         },
  149.        
  150.         /**
  151.         * Default callbacks to be used for accessing properties on objects. Can be
  152.         * overridden to alter the default behaviour. For single tweens, the function
  153.         * access(getCallback, setCallback) can be used to provide custom functions.
  154.         */
  155.         defaultCallbacks: {
  156.             propertyGet: function(object, property) {
  157.                 return object[property] || 0;
  158.             },
  159.             propertySet: function(object, property, value) {
  160.                 object[property] = value;
  161.             }
  162.         }        
  163.     };
  164.    
  165.     //=============================================================================
  166.     // class IAVRA.ANIMATE.Tween
  167.     //=============================================================================
  168.    
  169.     IAVRA.ANIMATE.Tween = (function($) {
  170.        
  171.         /**
  172.          * Initializes a new tween, which holds the animated object and handles the
  173.          * actual animation process.
  174.          */
  175.         $.prototype.initialize = function(object, properties) {
  176.             this._object = object;
  177.             this._time = 0;
  178.             this._duration = 1;
  179.             this._delay = 0;
  180.             this._easing = IAVRA.EASING.linear;
  181.            
  182.             this._running = false;
  183.            
  184.             this._valueGetCallback = IAVRA.ANIMATE.defaultCallbacks.propertyGet;
  185.             this._valueSetCallback = IAVRA.ANIMATE.defaultCallbacks.propertySet;
  186.            
  187.             this._valuesStart = {};
  188.             this._valuesEnd = properties || {};
  189.            
  190.             this._chainedTweens = [];
  191.         };
  192.        
  193.         /**
  194.          * Initializes all start values, calls the onStartCallback, if any, and adds
  195.          * this tween to the module.
  196.          */
  197.         $.prototype.start = function() {
  198.             this._running = true;
  199.             this._time = 0;
  200.             for(var prop in this._valuesEnd) {
  201.                 this._valuesStart[prop] = parseFloat(this._valueGetCallback(this._object, prop));
  202.             }
  203.             if(this._onStartCallback !== undefined) {
  204.                 this._onStartCallback(this._object);
  205.             }
  206.             addTween(this);
  207.             return this;
  208.         };
  209.        
  210.         /**
  211.          * Removes this tween and all chained tweens from the module and calls the
  212.          * onStopCallback, if any.
  213.          */
  214.         $.prototype.stop = function() {
  215.             removeTween(this);
  216.             this._running = false;
  217.             if(this._onStopCallback !== undefined) {
  218.                 this._onStopCallback(this._object);
  219.             }
  220.             this._chainedTweens.forEach(function(tween) {
  221.                 tween.stop();
  222.             });
  223.             return this;
  224.         };
  225.        
  226.         /**
  227.          * Pauses execution of this tween until resume() is called.
  228.          */
  229.         $.prototype.pause = function() {
  230.             this._running = false;
  231.             return this;
  232.         };
  233.        
  234.         /**
  235.          * Resumes execution of a tween, that has been pause()-d.
  236.          */
  237.         $.prototype.resume = function() {
  238.             this._running = true;
  239.             return this;
  240.         };
  241.        
  242.         /**
  243.          * Specifies the easing function to be used by this tween. By default, every
  244.          * tween uses linear (no) easing.
  245.          */
  246.         $.prototype.easing = function(easing) {
  247.             this._easing = easing;
  248.             return this;
  249.         };
  250.        
  251.         /**
  252.          * Sets the duration to be used for this tween. If this method is not called,
  253.          * the default value of 1 is used instead (which means, the animation finishes
  254.          * instantly).
  255.          */
  256.         $.prototype.duration = function(value) {
  257.             if((this._duration = parseInt(value)) < 1) {
  258.                 throw new Error('Duration has to be higher than 0.');
  259.             }
  260.             return this;
  261.         };
  262.        
  263.         /**
  264.          * Delays execution of this tween for a certain number of steps. Values lower
  265.          * or equal 0 have no effect.
  266.          */
  267.         $.prototype.delay = function(value) {
  268.             this._delay = parseInt(value);
  269.             return this;
  270.         };
  271.        
  272.         /**
  273.          * Registers a callback to be executed when the tween is started by calling the
  274.          * start()-function. The callback receives the animated object as a parameter.
  275.          */
  276.         $.prototype.onStart = function(callback) {
  277.             this._onStartCallback = callback;
  278.             return this;
  279.         };
  280.        
  281.         /**
  282.          * Registers a callback to be executed when the update()-method of this tween
  283.          * is called. The callback receives the animated object as a parameter.
  284.          */
  285.         $.prototype.onUpdate = function(callback) {
  286.             this._onUpdateCallback = callback;
  287.             return this;
  288.         };
  289.        
  290.         /**
  291.          * Registers a callback to be executed when the tween completes. The callback
  292.          * receives the animated object as a parameter.
  293.          */
  294.         $.prototype.onComplete = function(callback) {
  295.             this._onCompleteCallback = callback;
  296.             return this;
  297.         };
  298.        
  299.         /**
  300.          * Registers a callback to be executed when the tween is stopped by calling the
  301.          * stop()-function. The callback receives the animated object as a parameter.
  302.          */
  303.         $.prototype.onStop = function(callback) {
  304.             this._onStopCallback = callback;
  305.             return this;
  306.         }
  307.        
  308.         /**
  309.          * Adds the given tweens as chained tweens, which will be executed after this
  310.          * tween has been completed. Note that stopping a tween will also stop all
  311.          * chained tweens.
  312.          */
  313.         $.prototype.chain = function() {
  314.             this._chainedTweens = Array.prototype.slice.call(arguments);
  315.             return this;
  316.         }
  317.        
  318.         /**
  319.          * By default the script will read and write properties directly on the object.
  320.          * This might not always be desirable, as there could exist setters that contain
  321.          * properties in a specific value range or similar. In this case, the method can
  322.          * be called to provide callbacks for getting and setting properties.
  323.          */
  324.         $.prototype.access = function(getCallback, setCallback) {
  325.             this._valueGetCallback = getCallback;
  326.             this._valueSetCallback = setCallback;
  327.             return this;
  328.         }
  329.        
  330.         /**
  331.          * Progress the tween by incrementing the _time variable and calculating the
  332.          * new values of all given properties. Callbacks (onStart/onComplete) are called,
  333.          * if given. If the animation completes, all chained tweens (if any) are started.
  334.          * Returns false, when this tween has finished its execution.
  335.          */
  336.         $.prototype.update = function() {
  337.             if(!this._running || --this._delay >= 0) {
  338.                 return true;
  339.             }
  340.             var complete = (++this._time >= this._duration);
  341.             var progress = complete ? 1.0 : parseFloat(this._easing(this._time / this._duration));
  342.             for(var property in this._valuesEnd) {
  343.                 var start = this._valuesStart[property];
  344.                 var end = this._valuesEnd[property];
  345.                 this._valueSetCallback(this._object, property, start + (end - start) * progress);
  346.             }
  347.             if(this._onUpdateCallback !== undefined) {
  348.                 this._onUpdateCallback(this._object);
  349.             }
  350.             if(complete) {
  351.                 if(this._onCompleteCallback !== undefined) {
  352.                     this._onCompleteCallback(this._object);
  353.                 }
  354.                 this._chainedTweens.forEach(function(tween) {
  355.                     tween.start();
  356.                 });
  357.             }
  358.             return !complete;
  359.         }
  360.        
  361.         return $;
  362.     })(function() { this.initialize.apply(this, arguments); });
  363.    
  364.     //=============================================================================
  365.     // module IAVRA.EASING
  366.     //=============================================================================
  367.    
  368.     IAVRA.EASING = (function($) {
  369.        
  370.         /**
  371.         * Linear (no) easing. Other functions can be provided, but the script only ships
  372.         * with this one to not bloat it with functions.
  373.         */
  374.         $.linear = function(k) {
  375.             return k;
  376.         }
  377.        
  378.         return $;
  379.     })(IAVRA.EASING || {});
  380.    
  381.     //=============================================================================
  382.     // class Game_System
  383.     //=============================================================================
  384.    
  385.     /**
  386.      * Defining a new property that will be used to store currently executing tweens.
  387.      */
  388.     Object.defineProperty(Game_System.prototype, 'iavra_animate_tweens', {
  389.         get: function() {
  390.             this._iavra_animate_tweens || (this._iavra_animate_tweens = []);
  391.             return this._iavra_animate_tweens;
  392.         }
  393.     });
  394.    
  395.     //=============================================================================
  396.     // class Scene_Base
  397.     //=============================================================================
  398.    
  399.     /**
  400.      * Hooking our own update()-function into every scene, to be as generic as possible.
  401.      */
  402.     var _scene_base_update = Scene_Base.prototype.update;
  403.     Scene_Base.prototype.update = function() {
  404.         IAVRA.ANIMATE.update();
  405.         _scene_base_update.call(this, arguments);
  406.     };
  407.    
  408. })();
Add Comment
Please, Sign In to add comment