1 /**
  2  * Hilo
  3  * Copyright 2015 alibaba.com
  4  * Licensed under the MIT License
  5  */
  6 
  7 /**
  8  * @class Camera.
  9  * @param {Object} properties The properties to create a view object, contains all writeable props of this class
 10  * @module hilo/game/Camera
 11  * @requires hilo/core/Class
 12  * @requires hilo/util/util
 13  * @property {Number} width The width of the camera.
 14  * @property {Number} height The height of the camera.
 15  * @property {Object} scroll The scrolling value of the camera {x:0, y:0}.
 16  * @property {View} target The target that the camera follow.
 17  * @property {Array} bounds The rect area where camera is allowed to move [x, y, width, height].
 18  * @property {Array} deadzone The rect area where camera isn't allowed to move[ x, y, width, height].
 19  */
 20 var Camera = Class.create(/** @lends Camera.prototype */{
 21     constructor:function(properties){
 22         this.width = 0;
 23         this.height = 0;
 24 
 25         this.target = null;
 26         this.deadzone = null;
 27         this.bounds = null;
 28 
 29         this.scroll = {
 30             x:0,
 31             y:0
 32         };
 33 
 34         util.copy(this, properties);
 35     },
 36     /**
 37      * update.
 38      * @param {Number} deltaTime
 39     */
 40     tick:function(deltaTime){
 41         var target = this.target;
 42         var scroll = this.scroll;
 43         var bounds = this.bounds;
 44         var deadzone = this.deadzone;
 45 
 46         if(target){
 47             var viewX, viewY;
 48             if(deadzone){
 49                 viewX = Math.min(Math.max(target.x - scroll.x, deadzone[0]), deadzone[0] + deadzone[2]);
 50                 viewY = Math.min(Math.max(target.y - scroll.y, deadzone[1]), deadzone[1] + deadzone[3]);
 51             }
 52             else{
 53                 viewX = this.width * .5;
 54                 viewY = this.height * .5;
 55             }
 56 
 57             scroll.x = target.x - viewX;
 58             scroll.y = target.y - viewY;
 59 
 60             if(bounds){
 61                 scroll.x = Math.min(Math.max(scroll.x, bounds[0]), bounds[0] + bounds[2]);
 62                 scroll.y = Math.min(Math.max(scroll.y, bounds[1]), bounds[1] + bounds[3]);
 63             }
 64         }
 65         else{
 66             scroll.x = 0;
 67             scroll.y = 0;
 68         }
 69     },
 70     /**
 71      * Follow the target.
 72      * @param {Object} target The target that the camera follow. It must has x and y properties.
 73      * @param {Array} deadzone The rect area where camera isn't allowed to move[ x, y, width, height].
 74     */
 75     follow:function(target, deadzone){
 76         this.target = target;
 77         if(deadzone !== undefined){
 78             this.deadzone = deadzone;
 79         }
 80         this.tick();
 81     }
 82 });
 83