pexi
Version:
A collection of useful libraries for Pixi.js based on Hexi by kittykatattack.
1,506 lines (1,243 loc) • 245 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["pexi"] = factory();
else
root["pexi"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.easingFormulas = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _tween = __webpack_require__(3);
var _tween2 = _interopRequireDefault(_tween);
var _pathTween = __webpack_require__(8);
var _pathTween2 = _interopRequireDefault(_pathTween);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var easingFormulas = exports.easingFormulas = {
// Linear
linear: function linear(x) {
return x;
},
// Smoothstep
smoothstep: function smoothstep(x) {
return x * x * (3 - 2 * x);
},
smoothstepSquared: function smoothstepSquared(x) {
return Math.pow(x * x * (3 - 2 * x), 2);
},
smoothstepCubed: function smoothstepCubed(x) {
return Math.pow(x * x * (3 - 2 * x), 3);
},
// Acceleration
acceleration: function acceleration(x) {
return x * x;
},
accelerationCubed: function accelerationCubed(x) {
return Math.pow(x * x, 3);
},
// Deceleration
deceleration: function deceleration(x) {
return 1 - Math.pow(1 - x, 2);
},
decelerationCubed: function decelerationCubed(x) {
return 1 - Math.pow(1 - x, 3);
},
// Sine
sine: function sine(x) {
return Math.sin(x * Math.PI / 2);
},
sineSquared: function sineSquared(x) {
return Math.pow(Math.sin(x * Math.PI / 2), 2);
},
sineCubed: function sineCubed(x) {
return Math.pow(Math.sin(x * Math.PI / 2), 2);
},
inverseSine: function inverseSine(x) {
return 1 - Math.sin((1 - x) * Math.PI / 2);
},
inverseSineSquared: function inverseSineSquared(x) {
return 1 - Math.pow(Math.sin((1 - x) * Math.PI / 2), 2);
},
inverseSineCubed: function inverseSineCubed(x) {
return 1 - Math.pow(Math.sin((1 - x) * Math.PI / 2), 3);
},
// Spline
spline: function spline(t, p0, p1, p2, p3) {
return 0.5 * (2 * p1 + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t + (-p0 + 3 * p1 - 3 * p2 + p3) * t * t * t);
},
// Bezier curve
cubicBezier: function cubicBezier(t, a, b, c, d) {
var t2 = t * t;
var t3 = t2 * t;
return a + (-a * 3 + t * (3 * a - a * t)) * t + (3 * b + t * (-6 * b + b * 3 * t)) * t + (c * 3 - c * 3 * t) * t2 + d * t3;
}
};
/**
* Contains multiple tweens and has some convienence methods for interacting with all the tweens at once.
*
* @param {...Array} tweens the tween properties
*/
var MultiTween = function () {
function MultiTween() {
var _this = this;
_classCallCheck(this, MultiTween);
for (var _len = arguments.length, tweens = Array(_len), _key = 0; _key < _len; _key++) {
tweens[_key] = arguments[_key];
}
// Make a new tween for each array
this.tweens = tweens.map(function (tweenPropertyArguments) {
return new (Function.prototype.bind.apply(_tween2.default, [null].concat(_toConsumableArray(tweenPropertyArguments))))();
});
// Add a counter to keep track of the
// number of tweens that have completed their actions
this.completionCounter = 0;
// Add `onComplete` methods to all tweens
this.tweens.forEach(function (tween) {
tween.onComplete = _this.completed.bind(_this);
});
}
/**
* Updates each of the tweens.
*
* @param {number} deltaTime passed in from a ticker update
*/
_createClass(MultiTween, [{
key: 'update',
value: function update(deltaTime) {
this.tweens.forEach(function (tween) {
return tween.update(deltaTime);
});
}
/**
* Called each time one of the tweens finishes.
*/
}, {
key: 'completed',
value: function completed() {
// Add 1 to the `completionCounter`
this.completionCounter++;
// If all tweens have finished, call the user-defined `onComplete`
// method, if it's been assigned. Reset the `completionCounter`
if (this.completionCounter === this.tweens.length) {
if (this.onComplete) this.onComplete();
this.completionCounter = 0;
}
}
/**
* Plays all of the tweens.
*/
}, {
key: 'play',
value: function play() {
this.tweens.forEach(function (tween) {
return tween.play();
});
}
/**
* Pauses all of the tweens.
*/
}, {
key: 'pause',
value: function pause() {
this.tweens.forEach(function (tween) {
return tween.pause();
});
}
}]);
return MultiTween;
}();
/**
*
*/
var Charm = function () {
_createClass(Charm, null, [{
key: 'Tween',
get: function get() {
return _tween2.default;
}
}, {
key: 'MultiTween',
get: function get() {
return MultiTween;
}
}, {
key: 'PathTween',
get: function get() {
return _pathTween2.default;
}
}, {
key: 'easingFormulas',
get: function get() {
return easingFormulas;
}
}]);
function Charm() {
var renderingEngine = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : PIXI;
var ticker = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
_classCallCheck(this, Charm);
if (!renderingEngine) throw new Error('Please assign a rendering engine in the constructor before using charm.js');
// Find out which rendering engine is being used (the default is Pixi)
this.renderer = '';
// If the `renderingEngine` is Pixi, set up Pixi object aliases
if (renderingEngine.particles.ParticleContainer && renderingEngine.Sprite) {
this.renderer = 'pixi';
}
if (ticker) ticker.add(this.update, this, PIXI.UPDATE_PRIORITY.HIGH);
this._tweens = [];
}
_createClass(Charm, [{
key: '_addScaleProperties',
/**
* Add `scaleX` and `scaleY` properties to Pixi sprites.
*
* @param {PIXI.Sprite} sprite the sprite to add the properties to
*/
value: function _addScaleProperties(sprite) {
if (this.renderer === 'pixi') {
if (!('scaleX' in sprite) && 'scale' in sprite && 'x' in sprite.scale) {
Object.defineProperty(sprite, 'scaleX', {
get: function get() {
return sprite.scale.x;
},
set: function set(value) {
sprite.scale.x = value;
}
});
}
if (!('scaleY' in sprite) && 'scale' in sprite && 'y' in sprite.scale) {
Object.defineProperty(sprite, 'scaleY', {
get: function get() {
return sprite.scale.y;
},
set: function set(value) {
sprite.scale.y = value;
}
});
}
}
}
/**
* The low level `tweenProperty` function is used as the foundation for the the higher level tween methods.
*
* @param {PIXI.Sprite} sprite [description]
* @param {[type]} property [description]
* @param {[type]} startValue [description]
* @param {[type]} endValue [description]
* @param {[type]} totalFrames [description]
* @param {String} type [description]
* @param {Boolean} yoyo [description]
* @param {Number} delayBeforeRepeat [description]
* @return {[type]} [description]
*/
}, {
key: 'tweenProperty',
value: function tweenProperty(sprite, // Sprite object
property, // String property
startValue, // Tween start value
endValue, // Tween end value
totalFrames) // Delay in frames before repeating
{
var type = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 'smoothstep';
var yoyo = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false;
var delayBeforeRepeat = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0;
return this.addTween(new (Function.prototype.bind.apply(_tween2.default, [null].concat(Array.prototype.slice.call(arguments))))());
}
// `makeTween` is a general low-level method for making complex tweens
// out of multiple `tweenProperty` functions. Its one argument,
// `tweensToAdd` is an array containing multiple `tweenProperty` calls
}, {
key: 'makeTween',
value: function makeTween() {
for (var _len2 = arguments.length, tweensToAdd = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
tweensToAdd[_key2] = arguments[_key2];
}
return this.addTween(new (Function.prototype.bind.apply(MultiTween, [null].concat(tweensToAdd)))());
}
/* High level tween methods */
// 1. Simple tweens
// `fadeOut`
}, {
key: 'fadeOut',
value: function fadeOut(sprite) {
var frames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 60;
return this.tweenProperty(sprite, 'alpha', sprite.alpha, 0, frames, 'sine');
}
// `fadeIn`
}, {
key: 'fadeIn',
value: function fadeIn(sprite) {
var frames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 60;
return this.tweenProperty(sprite, 'alpha', sprite.alpha, 1, frames, 'sine');
}
// `pulse`
// Fades the sprite in and out at a steady rate.
// Set the `minAlpha` to something greater than 0 if you
// don't want the sprite to fade away completely
}, {
key: 'pulse',
value: function pulse(sprite) {
var frames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 60;
var minAlpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
return this.tweenProperty(sprite, 'alpha', sprite.alpha, minAlpha, frames, 'smoothstep', true);
}
// 2. Complex tweens
}, {
key: 'slide',
value: function slide(sprite, endX, endY) {
var frames = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 60;
var type = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'smoothstep';
var yoyo = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
var delayBeforeRepeat = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;
return this.makeTween(
// Create the x axis tween
[sprite, 'x', sprite.x, endX, frames, type, yoyo, delayBeforeRepeat],
// Create the y axis tween
[sprite, 'y', sprite.y, endY, frames, type, yoyo, delayBeforeRepeat]);
}
}, {
key: 'breathe',
value: function breathe(sprite) {
var endScaleX = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.8;
var endScaleY = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.8;
var frames = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 60;
var yoyo = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
var delayBeforeRepeat = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
// Add `scaleX` and `scaleY` properties to Pixi sprites
this._addScaleProperties(sprite);
return this.makeTween(
// Create the scaleX tween
[sprite, 'scaleX', sprite.scaleX, endScaleX, frames, 'smoothstepSquared', yoyo, delayBeforeRepeat],
// Create the scaleY tween
[sprite, 'scaleY', sprite.scaleY, endScaleY, frames, 'smoothstepSquared', yoyo, delayBeforeRepeat]);
}
}, {
key: 'scale',
value: function scale(sprite) {
var endScaleX = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.5;
var endScaleY = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.5;
var frames = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 60;
// Add `scaleX` and `scaleY` properties to Pixi sprites
this._addScaleProperties(sprite);
return this.makeTween(
// Create the scaleX tween
[sprite, 'scaleX', sprite.scaleX, endScaleX, frames, 'smoothstep', false],
// Create the scaleY tween
[sprite, 'scaleY', sprite.scaleY, endScaleY, frames, 'smoothstep', false]);
}
}, {
key: 'strobe',
value: function strobe(sprite) {
var scaleFactor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1.3;
var startMagnitude = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;
var endMagnitude = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 20;
var frames = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 10;
var yoyo = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
var delayBeforeRepeat = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;
var bounce = 'bounce ' + startMagnitude + ' ' + endMagnitude;
// Add `scaleX` and `scaleY` properties to Pixi sprites
this._addScaleProperties(sprite);
return this.makeTween(
// Create the scaleX tween
[sprite, 'scaleX', sprite.scaleX, scaleFactor, frames, bounce, yoyo, delayBeforeRepeat],
// Create the scaleY tween
[sprite, 'scaleY', sprite.scaleY, scaleFactor, frames, bounce, yoyo, delayBeforeRepeat]);
}
}, {
key: 'wobble',
value: function wobble(sprite) {
var scaleFactorX = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1.2;
var scaleFactorY = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1.2;
var frames = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10;
var xStartMagnitude = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 10;
var xEndMagnitude = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 10;
var yStartMagnitude = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : -10;
var yEndMagnitude = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : -10;
var friction = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0.98;
var _this2 = this;
var yoyo = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : true;
var delayBeforeRepeat = arguments.length > 10 && arguments[10] !== undefined ? arguments[10] : 0;
var bounceX = 'bounce ' + xStartMagnitude + ' ' + xEndMagnitude;
var bounceY = 'bounce ' + yStartMagnitude + ' ' + yEndMagnitude;
// Add `scaleX` and `scaleY` properties to Pixi sprites
this._addScaleProperties(sprite);
var o = this.makeTween(
// Create the scaleX tween
[sprite, 'scaleX', sprite.scaleX, scaleFactorX, frames, bounceX, yoyo, delayBeforeRepeat],
// Create the scaleY tween
[sprite, 'scaleY', sprite.scaleY, scaleFactorY, frames, bounceY, yoyo, delayBeforeRepeat]);
// Add some friction to the `endValue` at the end of each tween
o.tweens.forEach(function (tween) {
tween.onComplete = function () {
// Add friction if the `endValue` is greater than 1
if (tween.endValue > 1) {
tween.endValue *= friction;
// Set the `endValue` to 1 when the effect is finished and
// remove the tween from the global `tweens` array
if (tween.endValue <= 1) {
tween.endValue = 1;
_this2.removeTween(tween);
}
}
};
});
return o;
}
// 3. Motion path tweens
}, {
key: 'followCurve',
value: function followCurve(sprite, pointsArray, totalFrames) {
var type = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'smoothstep';
var yoyo = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var delayBeforeRepeat = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
return this.addTween(new (Function.prototype.bind.apply(_pathTween2.default, [null].concat(Array.prototype.slice.call(arguments))))());
}
}, {
key: 'walkPath',
value: function walkPath(sprite, // The sprite
originalPathArray) // Delay, in milliseconds, between sections
{
var totalFrames = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 300;
var type = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'smoothstep';
var loop = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var _this3 = this;
var yoyo = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
var delayBetweenSections = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;
// Clone the path array so that any possible references to sprite
// properties are converted into ordinary numbers
var pathArray = cloneDeep(originalPathArray);
// Figure out the duration, in frames, of each path section by
// dividing the `totalFrames` by the length of the `pathArray`
var frames = totalFrames / pathArray.length;
// Set the current point to 0, which will be the first waypoint
var currentPoint = 0;
// The `makePath` function creates a single tween between two points and
// then schedules the next path to be made after it
var makePath = function makePath(currentPoint) {
// Use the `makeTween` function to tween the sprite's
// x and y position
var tween = _this3.makeTween(
// Create the x axis tween between the first x value in the
// current point and the x value in the following point
[sprite, 'x', pathArray[currentPoint][0], pathArray[currentPoint + 1][0], frames, type],
// Create the y axis tween in the same way
[sprite, 'y', pathArray[currentPoint][1], pathArray[currentPoint + 1][1], frames, type]);
// When the tween is complete, advance the `currentPoint` by one.
// Add an optional delay between path segments, and then make the
// next connecting path
tween.onComplete = function () {
// Advance to the next point
currentPoint += 1;
// If the sprite hasn't reached the end of the
// path, tween the sprite to the next point
if (currentPoint < pathArray.length - 1) {
_this3.wait(delayBetweenSections).then(function () {
tween = makePath(currentPoint);
});
}
// If we've reached the end of the path, optionally
// loop and yoyo it
else {
// Reverse the path if `loop` is `true`
if (loop) {
// Reverse the array if `yoyo` is `true`
if (yoyo) pathArray.reverse();
// Optionally wait before restarting
_this3.wait(delayBetweenSections).then(function () {
// Reset the `currentPoint` to 0 so that we can
// restart at the first point
currentPoint = 0;
// Set the sprite to the first point
sprite.x = pathArray[0][0];
sprite.y = pathArray[0][1];
// Make the first new path
tween = makePath(currentPoint);
// ... and so it continues!
});
}
}
};
// Return the path tween to the main function
return tween;
};
// Make the first path using the internal `makePath` function (below)
var tween = makePath(currentPoint);
// Pass the tween back to the main program
return tween;
}
}, {
key: 'walkCurve',
value: function walkCurve(sprite, // The sprite
pathArray) // Delay, in milliseconds, between sections
{
var totalFrames = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 300;
var type = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'smoothstep';
var loop = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var _this4 = this;
var yoyo = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
var delayBeforeContinue = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;
// Divide the `totalFrames` into sections for each part of the path
var frames = totalFrames / pathArray.length;
// Set the current curve to 0, which will be the first one
var currentCurve = 0;
// The `makePath` function
var makePath = function makePath(currentCurve) {
// Use the custom `followCurve` function to make
// a sprite follow a curve
var tween = _this4.followCurve(sprite, pathArray[currentCurve], frames, type);
// When the tween is complete, advance the `currentCurve` by one.
// Add an optional delay between path segments, and then make the
// next path
tween.onComplete = function () {
currentCurve += 1;
if (currentCurve < pathArray.length) {
_this4.wait(delayBeforeContinue).then(function () {
tween = makePath(currentCurve);
});
}
// If we've reached the end of the path, optionally
// loop and reverse it
else if (loop) {
if (yoyo) {
// Reverse order of the curves in the `pathArray`
pathArray.reverse();
// Reverse the order of the points in each curve
pathArray.forEach(function (curveArray) {
return curveArray.reverse();
});
}
// After an optional delay, reset the sprite to the
// beginning of the path and make the next new path
_this4.wait(delayBeforeContinue).then(function () {
currentCurve = 0;
sprite.x = pathArray[0][0];
sprite.y = pathArray[0][1];
tween = makePath(currentCurve);
});
}
};
// Return the path tween to the main function
return tween;
};
// Make the first path
var tween = makePath(currentCurve);
// Pass the tween back to the main program
return tween;
}
// 4. Utilities
/**
* The `wait` method lets you set up a timed sequence of events.
*
* wait(1000)
* .then(() => console.log("One"))
* .then(() => wait(1000))
* .then(() => console.log("Two"))
* .then(() => wait(1000))
* .then(() => console.log("Three"))
*
* @param {number} [duration=0] how long to wait
* @return {Promise}
*/
}, {
key: 'wait',
value: function wait() {
var duration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return new Promise(function (resolve, reject) {
setTimeout(resolve, duration);
});
}
/**
* Adds a tween to this object.
*
* @param {BaseTween} tween the tween to add
* @return {BaseTween} the tween that was added
*/
}, {
key: 'addTween',
value: function addTween(tween) {
this._tweens.push(tween);
return tween;
}
/**
* A utility to remove tweens from the game.
*
* @param {Tween} tween the tween to remove
*/
}, {
key: 'removeTween',
value: function removeTween(tween) {
tween.pause();
// array.splice(-1,1) will always remove last elemnt of array, so this
// extra check prevents that (Thank you, MCumic10! https://github.com/kittykatattack/charm/issues/5)
var index = this._tweens.indexOf(tween);
if (index !== -1) {
this._tweens.splice(index, 1);
}
}
/**
* Update all the tween objects in the `globalTweens` array.
*
* @param {number} deltaTime the time passed in by the ticker
*/
}, {
key: 'update',
value: function update(deltaTime) {
this._tweens.forEach(function (tween) {
return tween.update(deltaTime);
});
}
}, {
key: 'tweens',
get: function get() {
return this._tweens;
}
}]);
return Charm;
}();
exports.default = Charm;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _util = __webpack_require__(4);
var _util2 = _interopRequireDefault(_util);
var _ = __webpack_require__(0);
var _lodash = __webpack_require__(5);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* The base tween class.
*
* @param {PIXI.Sprite} sprite the sprite to tween
* @param {number} data contains the tween values
* @param {number} duration the number of frames that the tween will take to complete
* @param {String} [type='smoothstep'] the type of easing
* @param {Boolean} [yoyo=false] should the sprite yoyo
* @param {Number} [delayBeforeRepeat=0] Delay in frames before repeating
* @abstract
*/
var BaseTween = function () {
function BaseTween(sprite, data, duration) {
var type = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'smoothstep';
var yoyo = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var delayBeforeRepeat = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
_classCallCheck(this, BaseTween);
// If the tween is a bounce type (a spline), set the
// start and end magnitude values
this.typeArray = type.split(' ');
if (this.typeArray[0] === 'bounce') {
this.startMagnitude = parseInt(this.typeArray[1]);
this.endMagnitude = parseInt(this.typeArray[2]);
}
// Clone the data to make sure we don't modify any external objects unintentionally
this.data = (0, _lodash2.default)(data);
this.duration = duration;
this.delayBeforeRepeat = delayBeforeRepeat;
this.yoyo = yoyo;
this.type = type;
this.sprite = sprite;
this.frameCounter = 0;
}
_createClass(BaseTween, [{
key: 'restart',
value: function restart() {
this.frameCounter = 0;
this.play();
}
/**
* Advances to the next frame.
*
* @param {number} deltaTime the deltaTime passed in from the ticker
*/
}, {
key: 'next',
value: function next(deltaTime) {
var curvedTime = void 0;
// Find the normalized value
var normalizedTime = this.frameCounter / this.duration;
// Select the correct easing function from the
// `ease` object’s library of easing functions
// If it's not a spline, use one of the ordinary easing functions
if (this.typeArray[0] !== 'bounce') {
curvedTime = _.easingFormulas[this.type](normalizedTime);
}
// If it's a spline, use the `spline` function and apply the
// 2 additional `type` array values as the spline's start and
// end points
else {
curvedTime = this.easingFormulas.spline(normalizedTime, this.startMagnitude, 0, 1, this.endMagnitude);
}
this._modifyProperty(curvedTime);
this.frameCounter++;
}
/**
* The `update` method will be called on each frame by the game loop.
*
* @param {number} deltaTime the time passed in by the ticker
*/
}, {
key: 'update',
value: function update(deltaTime) {
if (this._playing) {
// If the elapsed frames are less than the total frames,
// use the tweening formulas to move the sprite
if (this.frameCounter < this.duration) {
this.next();
} else {
// When the tween has finished playing, run the end tasks
this._setUpForEnd();
this.end();
}
}
}
/**
* The `end` method will be called when the tween is finished.
*/
}, {
key: 'end',
value: function end() {
var _this = this;
this.pause();
// Call the tween's `onComplete` method, if it's been assigned
if (this.onComplete) this.onComplete();
// If the tween's `yoyo` property is `true`, create a new tween
// using the same values, but use the current tween's `startValue`
// as the next tween's `endValue`
if (this.yoyo) {
this.wait(this.delayBeforeRepeat).then(function () {
_this._setUpForYoyo();
_this.restart();
});
}
}
/**
* Play the tween.
*/
}, {
key: 'play',
value: function play() {
this._playing = true;
}
/**
* Pause the tween.
*/
}, {
key: 'pause',
value: function pause() {
this._playing = false;
}
}, {
key: '_setUpForYoyo',
value: function _setUpForYoyo() {
throw (0, _util2.default)(this);
}
}, {
key: '_setUpForEnd',
value: function _setUpForEnd() {
throw (0, _util2.default)(this);
}
}, {
key: '_modifyProperty',
value: function _modifyProperty(curvedTime) {
throw (0, _util2.default)(this);
}
}, {
key: 'playing',
get: function get() {
return this._playing;
}
}]);
return BaseTween;
}();
exports.default = BaseTween;
module.exports = exports['default'];
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _index = __webpack_require__(0);
var _index2 = _interopRequireDefault(_index);
var _gameUtilities = __webpack_require__(9);
var _gameUtilities2 = _interopRequireDefault(_gameUtilities);
var _smoothie = __webpack_require__(10);
var _smoothie2 = _interopRequireDefault(_smoothie);
var _spriteUtilities = __webpack_require__(11);
var _spriteUtilities2 = _interopRequireDefault(_spriteUtilities);
var _tileUtilities = __webpack_require__(12);
var _tileUtilities2 = _interopRequireDefault(_tileUtilities);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = { Charm: _index2.default, GameUtilities: _gameUtilities2.default, Smoothie: _smoothie2.default, SpriteUtilities: _spriteUtilities2.default, TileUtilities: _tileUtilities2.default };
module.exports = exports['default'];
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _baseTween = __webpack_require__(1);
var _baseTween2 = _interopRequireDefault(_baseTween);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* The basic tween class used for stright tweens.
*
* @param {PIXI.Sprite} sprite the sprite to tween
* @param {string} property the sprite property to modify
* @param {number} startValue the starting value
* @param {number} endValue the ending value
* @param {number} duration the number of frames that the tween will take to complete
* @param {String} [type='smoothstep'] the type of easing
* @param {Boolean} [yoyo=false] should the sprite yoyo
* @param {Number} [delayBeforeRepeat=0] Delay in frames before repeating
*/
var Tween = function (_BaseTween) {
_inherits(Tween, _BaseTween);
function Tween(sprite, property, startValue, endValue, duration) {
var type = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 'smoothstep';
var yoyo = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false;
var delayBeforeRepeat = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0;
_classCallCheck(this, Tween);
var _this = _possibleConstructorReturn(this, (Tween.__proto__ || Object.getPrototypeOf(Tween)).call(this, sprite, [startValue, endValue], duration, type, yoyo, delayBeforeRepeat));
_this.property = property;
return _this;
}
_createClass(Tween, [{
key: '_setUpForYoyo',
value: function _setUpForYoyo() {
this.data = this.data.reverse();
}
}, {
key: '_setUpForEnd',
value: function _setUpForEnd() {
this.sprite[this.property] = this.data[1];
}
}, {
key: '_modifyProperty',
value: function _modifyProperty(curvedTime) {
this.sprite[this.property] = this.data[1] * curvedTime + this.data[0] * (1 - curvedTime);
}
}]);
return Tween;
}(_baseTween2.default);
exports.default = Tween;
module.exports = exports['default'];
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AbstractInstantiationError = AbstractInstantiationError;
function AbstractInstantiationError(obj) {
return new TypeError('Do not instantiate `' + obj.constructor.name + '` directly, use a subclass instead');
}
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, module) {/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array ? array.length : 0;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array ? array.length : 0;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
Symbol = root.Symbol,
Uint8Array = root.Uint8Array,
getPrototype = overArg(Object.getPrototypeOf, Object),
objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeKeys = overArg(Object.keys, Object);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
Map = getNative(root, 'Map'),
Promise = getNative(root, 'Promise'),
Set = getNative(root, 'Set'),
WeakMap = getNative(root, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();