1 /**
  2  * Hilo
  3  * Copyright 2015 alibaba.com
  4  * Licensed under the MIT License
  5  */
  6 
  7 /**
  8  * @class Camera类表示摄像机。
  9  * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
 10  * @module hilo/game/Camera
 11  * @requires hilo/core/Class
 12  * @requires hilo/util/util
 13  * @property {Number} width 镜头宽
 14  * @property {Number} height 镜头高
 15  * @property {Object} scroll 滚动值 {x:0, y:0}
 16  * @property {View} target 摄像机跟随的目标
 17  * @property {Array} bounds 摄像机移动边界的矩形区域 [x, y, width, height]
 18  * @property {Array} deadzone 摄像机不移动的矩形区域 [ 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      * 更新
 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      * 跟随目标
 72      * @param {Object} target 跟随的目标,必须是有x,y属性的对象
 73      * @param {Array} deadzone 摄像机不移动的矩形区域 [ 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