1 /** 2 * Hilo 3 * Copyright 2015 alibaba.com 4 * Licensed under the MIT License 5 */ 6 7 /** 8 * @language=zh 9 * @class Camera类表示摄像机。 10 * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。 11 * @module hilo/game/Camera 12 * @requires hilo/core/Hilo 13 * @requires hilo/core/Class 14 * @property {Number} width 镜头宽 15 * @property {Number} height 镜头高 16 * @property {Object} scroll 滚动值 {x:0, y:0} 17 * @property {View} target 摄像机跟随的目标 18 * @property {Array} bounds 摄像机移动边界的矩形区域 [x, y, width, height] 19 * @property {Array} deadzone 摄像机不移动的矩形区域 [ x, y, width, height] 20 */ 21 var Camera = Class.create(/** @lends Camera.prototype */{ 22 constructor:function(properties){ 23 this.width = 0; 24 this.height = 0; 25 26 this.target = null; 27 this.deadzone = null; 28 this.bounds = null; 29 30 this.scroll = { 31 x:0, 32 y:0 33 }; 34 35 Hilo.copy(this, properties); 36 }, 37 /** 38 * @language=zh 39 * 更新 40 * @param {Number} deltaTime 41 */ 42 tick:function(deltaTime){ 43 var target = this.target; 44 var scroll = this.scroll; 45 var bounds = this.bounds; 46 var deadzone = this.deadzone; 47 48 if(target){ 49 var viewX, viewY; 50 if(deadzone){ 51 viewX = Math.min(Math.max(target.x - scroll.x, deadzone[0]), deadzone[0] + deadzone[2]); 52 viewY = Math.min(Math.max(target.y - scroll.y, deadzone[1]), deadzone[1] + deadzone[3]); 53 } 54 else{ 55 viewX = this.width * .5; 56 viewY = this.height * .5; 57 } 58 59 scroll.x = target.x - viewX; 60 scroll.y = target.y - viewY; 61 62 if(bounds){ 63 scroll.x = Math.min(Math.max(scroll.x, bounds[0]), bounds[0] + bounds[2]); 64 scroll.y = Math.min(Math.max(scroll.y, bounds[1]), bounds[1] + bounds[3]); 65 } 66 } 67 else{ 68 scroll.x = 0; 69 scroll.y = 0; 70 } 71 }, 72 /** 73 * @language=zh 74 * 跟随目标 75 * @param {Object} target 跟随的目标,必须是有x,y属性的对象 76 * @param {Array} deadzone 摄像机不移动的矩形区域 [ x, y, width, height] 77 */ 78 follow:function(target, deadzone){ 79 this.target = target; 80 if(deadzone !== undefined){ 81 this.deadzone = deadzone; 82 } 83 this.tick(); 84 } 85 }); 86