73 lines
2.0 KiB
C#
73 lines
2.0 KiB
C#
using UnityEngine;
|
|
|
|
namespace AibisDream.Framework
|
|
{
|
|
public class MoveableSystem : IMonoKit
|
|
{
|
|
private bool _isDragging;
|
|
private IMoveable _dragObj;
|
|
private Vector3 _offset;
|
|
private readonly Camera _camera = Camera.main;
|
|
|
|
public void OnUpdate()
|
|
{
|
|
// 鼠标按下
|
|
if (Input.GetMouseButtonDown(0))
|
|
{
|
|
OnMouseClickDown();
|
|
}
|
|
|
|
// 鼠标按住
|
|
if (Input.GetMouseButton(0) && _isDragging)
|
|
{
|
|
OnMouseHolding();
|
|
}
|
|
|
|
// 鼠标松开
|
|
if (Input.GetMouseButtonUp(0))
|
|
{
|
|
OnMouseClickUp();
|
|
}
|
|
}
|
|
|
|
private void OnMouseClickDown()
|
|
{
|
|
// 按下时发出检查射线
|
|
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
|
|
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
|
|
|
|
// 检测命中的物体
|
|
if (hit.collider && hit.collider.CompareTag("Moveable"))
|
|
{
|
|
_dragObj = hit.collider.gameObject.GetComponent<IMoveable>();
|
|
if (_dragObj == null) return;
|
|
|
|
_dragObj.StartMove();
|
|
_offset = hit.collider.transform.position - GetMouseAsWorldPoint();
|
|
|
|
_isDragging = true;
|
|
}
|
|
}
|
|
|
|
private void OnMouseHolding()
|
|
{
|
|
_dragObj.Move(GetMouseAsWorldPoint() + _offset);
|
|
}
|
|
|
|
private void OnMouseClickUp()
|
|
{
|
|
if (!_isDragging) return;
|
|
|
|
_dragObj?.StopMove();
|
|
_dragObj = null;
|
|
_isDragging = false;
|
|
}
|
|
|
|
private Vector3 GetMouseAsWorldPoint()
|
|
{
|
|
Vector3 mousePoint = Input.mousePosition;
|
|
mousePoint.z = _camera.nearClipPlane;
|
|
return _camera.ScreenToWorldPoint(mousePoint);
|
|
}
|
|
}
|
|
} |