using AibisDream.Utility; using DG.Tweening; using UnityEngine; using UnityEngine.EventSystems; namespace AibisDream.FixSystem { public class Plug : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler { #region 插头当前信息 private Vector3 _startPos; private Vector3 _startRotate; private readonly Vector3 _pickupOffset = new(0, 0, 0); private readonly Quaternion _pickupRotationOffset = Quaternion.Euler(0, 0, 30); #endregion #region 索引 private CableSystem _cableSystem; private SpriteRenderer _sprite; private Transform _plugRootPos; #endregion private bool _isDragging; private void Awake() { InitComponentRef(); } private void InitComponentRef() { _cableSystem = transform.parent.GetComponent(); _sprite = GetComponent(); _plugRootPos = transform.Find("Plug Root Pos"); } public void InitPlug(ISocket initSocket) { InsertSocket(initSocket); } /// /// 插入某个socket /// /// 目标socket public void InsertSocket(ISocket targetSocket) { // 修改插头位置 transform.position = targetSocket.GetSocketPos(); _cableSystem.CableRef.SetEndPos(transform); // 处理插槽插入 targetSocket.PlugIn(); AudioManager.RandomPlayInteraction("plug_in"); _sprite.enabled = false; // 触发事件 _cableSystem.BodyModuleSystem.plugInEvent?.Invoke(targetSocket); _cableSystem.curSocket = targetSocket; if (targetSocket is BodyModule bodyModule) { _cableSystem.curBodyModule = bodyModule; } } /// /// 从某个Socket拔出来 /// public void PullUpSocket() { // 修改线头位置 _cableSystem.CableRef.SetEndPos(_plugRootPos); _cableSystem.curSocket?.PlugOut(); AudioManager.RandomPlayInteraction("plug_out"); _sprite.enabled = true; // 触发事件 _cableSystem.BodyModuleSystem.plugOutEvent?.Invoke(_cableSystem.curSocket); _cableSystem.curBodyModule = null; _cableSystem.curSocket = null; } public void OnDrag(PointerEventData eventData) { // 系统被锁定就返回 if (!_cableSystem.IsPlugAvailable()) return; // 未被拖拽也返回 if (!_isDragging) return; transform.position = CommonUtil.GetMouseWorldPos(eventData.position, transform); } public void OnPointerDown(PointerEventData eventData) { // 系统被锁定就返回 if (!_cableSystem.IsPlugAvailable()) return; // 开启拖拽 _isDragging = true; // 进行插拔动作 if (_cableSystem.curSocket != null) PullUpSocket(); // 调整插头形状 AdjustPlugPos(); } public void OnPointerUp(PointerEventData eventData) { // 停止拖拽 _isDragging = false; // 寻找可吸附的Module if (_cableSystem.TryFindClosestModule(transform.position, out var targetModule)) { // 找到了就插入目标Module InsertSocket(targetModule); } else { // 没找到就插回初始Socket,需要播动画 transform.DOMove(_cableSystem.InitSocket.GetSocketPos(), 0.1f).OnComplete(() => { InsertSocket(_cableSystem.InitSocket); }); } } private void AdjustPlugPos() { transform.position += _pickupOffset; transform.rotation = _pickupRotationOffset; } void OnDrawGizmosSelected() { Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(transform.position, 0.5f); } } }