117 lines
3.2 KiB
C#
117 lines
3.2 KiB
C#
using Base;
|
|
using UnityEngine;
|
|
using UnityEngine.SceneManagement;
|
|
|
|
namespace CameraControl
|
|
{
|
|
public class CameraControl : Utils.MonoSingleton<CameraControl>, ITick, ITickUI
|
|
{
|
|
// 当前被聚焦的目标实体
|
|
public Entity.Entity focusedEntity = null;
|
|
|
|
// Camera movement variables
|
|
private Vector3 _dragOrigin;
|
|
private bool _isDragging = false;
|
|
private float _zoomSpeed = 5f;
|
|
private float _minZoom = 2f;
|
|
private float _maxZoom = 20f;
|
|
|
|
private Camera _camera;
|
|
|
|
|
|
private void OnDestroy()
|
|
{
|
|
// 移除事件监听
|
|
SceneManager.sceneLoaded -= OnSceneLoaded;
|
|
}
|
|
|
|
protected override void OnStart()
|
|
{
|
|
// 注册场景加载事件
|
|
SceneManager.sceneLoaded += OnSceneLoaded;
|
|
|
|
// 初始化时调用一次
|
|
Init();
|
|
}
|
|
|
|
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
|
|
{
|
|
// 场景加载完成后调用 Init 方法
|
|
Init();
|
|
}
|
|
|
|
private void Init()
|
|
{
|
|
_camera = Camera.main;
|
|
if (_camera == null)
|
|
{
|
|
_camera = FindFirstObjectByType<Camera>();
|
|
}
|
|
}
|
|
public void Tick()
|
|
{
|
|
if (focusedEntity)
|
|
{
|
|
// Follow the focused entity's position
|
|
var targetPosition = new Vector3(
|
|
focusedEntity.Position.x,
|
|
focusedEntity.Position.y,
|
|
_camera.transform.position.z);
|
|
|
|
_camera.transform.position = Vector3.Lerp(
|
|
_camera.transform.position,
|
|
targetPosition,
|
|
Time.fixedDeltaTime * 5f);
|
|
}
|
|
}
|
|
|
|
public void TickUI()
|
|
{
|
|
if (!_camera)
|
|
return;
|
|
HandleMiddleMouseDrag();
|
|
HandleMouseZoom();
|
|
}
|
|
|
|
public void SetPosition(Vector3 position)
|
|
{
|
|
if (_camera)
|
|
_camera.transform.position = position;
|
|
}
|
|
|
|
private void HandleMiddleMouseDrag()
|
|
{
|
|
// Start drag
|
|
if (Input.GetMouseButtonDown(2)) // Middle mouse button
|
|
{
|
|
_dragOrigin = _camera.ScreenToWorldPoint(Input.mousePosition);
|
|
_isDragging = true;
|
|
focusedEntity = null; // Clear focus when manually moving camera
|
|
}
|
|
|
|
// During drag
|
|
if (Input.GetMouseButton(2) && _isDragging)
|
|
{
|
|
var difference = _dragOrigin - _camera.ScreenToWorldPoint(Input.mousePosition);
|
|
_camera.transform.position += difference;
|
|
}
|
|
|
|
// End drag
|
|
if (Input.GetMouseButtonUp(2))
|
|
{
|
|
_isDragging = false;
|
|
}
|
|
}
|
|
|
|
private void HandleMouseZoom()
|
|
{
|
|
var scroll = Input.GetAxis("Mouse ScrollWheel");
|
|
if (scroll == 0) return;
|
|
var newSize = _camera.orthographicSize - scroll * _zoomSpeed;
|
|
_camera.orthographicSize = Mathf.Clamp(newSize, _minZoom, _maxZoom);
|
|
}
|
|
|
|
|
|
|
|
}
|
|
} |