File: src/link/Camera.js
/**
* @author Vsevolod Strukchinsky @floatdrop
*/
/**
Camera class represents DisplayObjectContainer, that autotrack one of DisplayObject positions.
@example
var stage = new PIXI.Stage();
var layers = new LINK.Layers("game","ui");
stage.addChild(layers);
var camera = new LINK.Camera();
camera.follow(player).on(layers.game);
@class Camera
@extends DisplayObjectContainer
@constructor
**/
LINK.Camera = function () {
PIXI.DisplayObjectContainer.call(this);
/**
* The bounds of that the camera can move to
*
* @property bounds
* @type PIXI.Rectangle
* @readOnly
* @private
*/
this.bounds = {
get: value() {
return _bounds;
},
set: value(n) {
if (!(bounds instanceof PIXI.Rectangle)) throw new Error(n + " bounds must be instance of PIXI.Rectangle");
_bounds = n;
_bounds.maxX = n.x + n.width;
_buonds.maxY = n.y + n.height;
}
};
this.bounds = new PIXI.Rectangle(0, 0, 0, 0);
/**
* Freezes the camera
* @property freeze
* @type Boolean
*/
this.freeze = false;
/**
* Freezes the camera
* @property freeze
* @type Boolean
* @private
*/
this._linkedObject = null;
};
LINK.Camera.constructor = LINK.Camera;
LINK.Camera.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
/**
* Wraps DisplayObject to pan him and all his childrens.
* @method on
* @param object {DisplayObjectContainer}
*/
LINK.Camera.prototype.on = function(object)
{
if (!(object instanceof PIXI.DisplayObjectContainer)) throw new Error(object + " object should be instance of DisplayObjectContainer");
if (this.parent) {
this.off();
}
var parent = object.parent;
var index = parent.children.indexOf( object );
parent.removeChild(object);
this.addChild(object);
this._on = object;
object = this;
parent.addChildAt(object, index);
return this;
};
/**
* Unwraps DisplayObject that was wrapped by "on" method.
* @method off
*/
LINK.Camera.prototype.off = function()
{
var parent = this.parent;
var index = parent.children.indexOf( this );
parent.removeChild(this);
if (this.children[0]) {
parent.addChildAt(this.children[0], index);
}
return this;
};
/**
* Starts follow on DisplayObject
* @method follow
* @param object {DisplayObject}
*/
LINK.Camera.prototype.follow = function(object)
{
this._linkedObject = object;
return this;
}
/**
@method updateTransform
@internal
*/
LINK.Camera.prototype.updateTransform = function()
{
if (this._linkedObject && !this.freeze) {
var anchor = this._linkedObject.position;
if (anchor.x < this.bounds.x) anchor.x = this.bounds.x;
else if (anchor.x > this.bounds.maxX) anchor.x = this.bounds.maxX;
if (anchor.y < this.bounds.y) anchor.y = this.bounds.y;
else if (anchor.y > this.bounds.maxY) anchor.y = this.bounds.maxX;
this.anchor = anchor;
}
PIXI.Sprite.prototype.updateTransform.call(this);
}