一個Egret的正交攝像機的簡單實現,主要功能大致如下:
可參考根據實際進行調整
module Camera {
/**一個正交攝像機demo*/
export class Camera {
/**攝像機顯示的對象,實際是鏡頭所對應的世界*/
m_container: eui.UILayer;
/**攝像機寬 */
m_width: number;
/**攝像機高 */
m_height: number;
/**攝像機的焦點X */
m_zoomX: number;
/**攝像機的焦點Y */
m_zoomY: number;
/**攝像機焦距*/
m_zoom: number;
/**跟隨對象 */
m_follower: eui.Component;
/**攝像機X軸偏移值 */
m_cameraOffsetX: number;
/**攝像機Y軸偏移值 */
m_cameraOffsetY: number;
public constructor(width: number, height: number) {
this.m_width = width;
this.m_height = height;
this.m_cameraOffsetX = 0;
this.m_cameraOffsetY = 0;
}
/**初始化相機,綁定鏡頭 */
public init(container: eui.UILayer) {
this.m_container = container;
this.m_zoomX = this.m_container.x;
this.m_zoomY = this.m_container.y;
}
/**設置鏡頭錨點
* @param LRRate 左右比例
* @param UDRate 上下比例
* 根據左右及上下的比例確定鏡頭的聚焦點
*/
public setAnchor(LRRate: number, UDRate: number) {
if (this.m_container != null) {
this.m_container.anchorOffsetX = this.m_container.width * LRRate;
this.m_container.anchorOffsetY = this.m_container.height * UDRate;
this.m_container.x = this.m_container.anchorOffsetX;
this.m_container.y = this.m_container.anchorOffsetY;
this.m_zoomX = this.m_container.anchorOffsetX;
this.m_zoomY = this.m_container.anchorOffsetY;
}
}
/**設置鏡頭焦距
* @param zoom 焦距,鏡頭距離世界的比例,默認爲1,焦距越小,視覺越大
*/
public setZoom(zoom: number) {
if (this.m_container != null) {
this.m_container.scaleX = this.m_container.width / this.m_width / zoom;
this.m_container.scaleY = this.m_container.height / this.m_height / zoom;
}
}
/**旋轉
* @param rotation 旋轉角度
*
*/
public setRotation(rotation: number) {
if (this.m_container != null) {
this.m_container.rotation = rotation;
}
}
/**設置跟隨者 */
public follow(follower: eui.Component) {
if (this.m_container != null) {
this.m_follower = follower;
this.m_zoomX = this.m_follower.x;
this.m_zoomY = this.m_follower.y;
this.setAnchor(this.m_follower.x / this.m_container.width, this.m_follower.y / this.m_container.height);
}
}
/**攝像機X軸移動
* @param x 沿x軸移動的有向速度
*
*/
public CameraMoveX(x: number) {
console.log(x);
this.m_cameraOffsetX = x;
this.CameraUpdate();
this.m_cameraOffsetX = 0;
}
/**攝像機Y軸移動
* @param y 沿y軸移動的有向速度
*
*/
public CameraMoveY(y: number) {
this.m_cameraOffsetY = y;
this.CameraUpdate();
this.m_cameraOffsetY = 0;
}
/**通過攝像頭偏移值計算世界內物品的偏移值
* 如果設置了跟隨者,則跟隨者在世界內的距離不變,其他物體根據鏡頭偏移量進行座標修正
* 如果沒有設置跟隨者,則視世界全局可見,全員根據鏡頭偏移量進行座標修正
* 注意1:攝像機移動的實現方式實際是世界內物品相對於世界進行的座標的移動,但世界本身是固定的,變化的只是世界內部的物體
* 注意2:實際上,這裏的座標修正應該交給各個世界對象去自行實現,以便各物體對象能以此修正自身的行爲,這裏爲了形成一個
* 統一的認識而把偏移的工作放進攝像機,就造成攝像機的功能比較單一的問題
*/
public CameraUpdate() {
for (let i = 0; i < this.m_container.numChildren; i++) {
if (this.m_follower != null) {
if (this.m_follower != this.m_container.getChildAt(i)) {
this.m_container.getChildAt(i).x -= this.m_cameraOffsetX;
this.m_container.getChildAt(i).y -= this.m_cameraOffsetY;
}
} else {
this.m_container.getChildAt(i).x -= this.m_cameraOffsetX;
this.m_container.getChildAt(i).y -= this.m_cameraOffsetY;
}
}
}
}
}