Files
zeling_v2/Assets/Scripts/Camera/CameraStateController.cs
2026-05-12 15:34:08 +08:00

83 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Generic;
using UnityEngine;
using Unity.Cinemachine;
using BaseGames.Core;
namespace BaseGames.Camera
{
/// <summary>
/// 相机状态单例控制器。管理房间相机切换、限位器更新与屏幕抖动。
/// 须放置在持久化场景中。
/// </summary>
[DefaultExecutionOrder(-100)]
public class CameraStateController : MonoBehaviour, ICameraService
{
[Header("引用")]
[SerializeField] private CinemachineBrain _brain;
[SerializeField] private CinemachineImpulseSource _impulseSource;
[Header("默认混合配置")]
[SerializeField] private CameraBlendProfileSO _defaultBlendProfile;
// ── 注册表 ────────────────────────────────────────────────────────────
private readonly HashSet<RoomCamera> _registeredCameras = new HashSet<RoomCamera>();
private RoomCamera _activeCamera;
// ── Unity Lifecycle ───────────────────────────────────────────────────
private void Awake()
{
if (ServiceLocator.GetOrDefault<ICameraService>() != null) { Destroy(gameObject); return; }
ServiceLocator.Register<ICameraService>(this);
}
private void OnDestroy()
{
ServiceLocator.Unregister<ICameraService>(this);
}
// ── 公开 API ──────────────────────────────────────────────────────────
/// <summary>向控制器注册一个房间相机(可选,也可由触发器直接调用 SwitchRoom。</summary>
public void RegisterRoomCamera(RoomCamera camera)
{
if (camera != null) _registeredCameras.Add(camera);
}
/// <summary>注销房间相机。</summary>
public void UnregisterRoomCamera(RoomCamera camera)
{
if (camera != null) _registeredCameras.Remove(camera);
}
/// <summary>切换到目标房间相机,并应用对应的混合配置。</summary>
public void SwitchRoom(RoomCamera targetCamera)
{
if (targetCamera == null || targetCamera == _activeCamera) return;
// 应用混合配置到 Brain
if (_brain != null)
{
var profile = targetCamera.BlendProfile ?? _defaultBlendProfile;
if (profile != null)
_brain.DefaultBlend = profile.ToBlendDefinition();
}
// 禁用旧相机、启用新相机
_activeCamera?.Deactivate();
_activeCamera = targetCamera;
_activeCamera.Activate();
}
/// <summary>触发屏幕抖动。</summary>
public void TriggerImpulse(Vector3 velocity)
{
if (_impulseSource != null)
_impulseSource.GenerateImpulse(velocity);
}
/// <summary>以默认强度触发屏幕抖动。</summary>
public void TriggerImpulse(float strength = 0.3f)
=> TriggerImpulse(Vector3.down * strength);
}
}