?
- 資源初始化:在類中通過?
@property
?裝飾器定義主相機、小地圖相機、小地圖精靈等資源屬性,便于在編輯器中賦值。在?start
?方法里,當確認這些資源存在后,創建渲染紋理并設置其大小,將渲染紋理與小地圖相機關聯,再創建精靈幀并把渲染紋理應用到精靈幀上,最后將精靈幀設置給小地圖精靈,完成小地圖顯示的初始化配置。- 位置跟隨:在?
update
?方法中,不斷檢查主相機和小地圖相機是否存在,若存在則獲取主相機位置,讓小地圖相機的?x
、y
?坐標跟隨主相機,同時保持小地圖相機的?z
?軸坐標不變,以維持穩定視角,實現小地圖相機對主相機位置的實時跟隨。- 交互功能處理:定義?
calculateAndSetOrthoHeight
?方法,用于實現小地圖的縮放功能。該方法先獲取小地圖相機當前的正交高度,依據鼠標滾輪滾動方向計算新的正交高度,并對新高度進行范圍檢查,保證其在合理區間內才更新小地圖相機的正交高度。通過?onMouseWheel
?方法監聽鼠標滾輪事件,獲取滾輪滾動值并調用?calculateAndSetOrthoHeight
?方法,從而實現用戶通過鼠標滾輪操作來縮放小地圖的交互功能。
import { _decorator, Component, Camera, Node, RenderTexture, SpriteFrame, Sprite, Vec3, Canvas, EventMouse, Vec2 } from 'cc';
const { ccclass, property } = _decorator;@ccclass('MainCameraBindMiniController')
export class MainCameraController extends Component {// 主攝像機@property(Camera)mainCamera: Camera | null = null;// 小地圖攝像機@property(Camera)miniMapCamera: Camera | null = null;// 小地圖展示的精靈@property(Sprite)miniMapSprite: Sprite | null = null;// 小地圖的大小private miniMapSize = { width: 200, height: 200 };// 縮放速度@propertyzoomSpeed: number = 0.02;// 移動速度因子@propertymoveSpeedFactor: number = 1;// 小地圖的渲染紋理private renderTexture: RenderTexture | null = null;start() {if (this.mainCamera && this.miniMapCamera && this.miniMapSprite) {// 創建一個渲染紋理this.renderTexture = new RenderTexture();this.renderTexture.reset({width: this.miniMapSize.width,height: this.miniMapSize.height});// 將渲染紋理設置給小地圖攝像機this.miniMapCamera.targetTexture = this.renderTexture;// 創建一個精靈幀,并將渲染紋理應用到精靈幀const spriteFrame = new SpriteFrame();spriteFrame.texture = this.renderTexture;// 將精靈幀設置到小地圖的精靈上this.miniMapSprite.spriteFrame = spriteFrame;// 小地圖反轉(如果需要)this.miniMapCamera.node.scale = new Vec3(1, 1, 1);}}update(deltaTime: number) {if (this.mainCamera && this.miniMapCamera) {// 獲取主攝像機的位置const mainCameraPos = this.mainCamera.node.position;// 讓小地圖攝像機的位置跟隨主攝像機// 小地圖攝像機的 Z 軸保持不變,確保它的視角穩定this.miniMapCamera.node.setPosition(new Vec3(mainCameraPos.x, mainCameraPos.y, this.miniMapCamera.node.position.z));}}calculateAndSetOrthoHeight(move: Vec3) {if (this.miniMapCamera) {// 獲取攝像機的正交高度let currentOrthoHeight = this.miniMapCamera.orthoHeight;// 計算新的正交高度let newOrthoHeight = currentOrthoHeight + (move.y < 0 ? -this.zoomSpeed : this.zoomSpeed);// 確保新的正交高度在合理范圍內if (newOrthoHeight > 500 && newOrthoHeight < 1000000) {this.miniMapCamera.orthoHeight = newOrthoHeight;}}}onMouseWheel(event: EventMouse) {let scrollValueY = event.getScrollY();this.calculateAndSetOrthoHeight(new Vec3(0, scrollValueY, 0));}
}