85 lines
2.4 KiB
C#
85 lines
2.4 KiB
C#
using Base;
|
|
using UnityEngine;
|
|
|
|
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;
|
|
|
|
protected override void OnStart()
|
|
{
|
|
_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()
|
|
{
|
|
HandleMiddleMouseDrag();
|
|
HandleMouseZoom();
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
|
|
}
|
|
} |