summaryrefslogtreecommitdiff
path: root/Assets/Scripts/PlayerDrag.cs
diff options
context:
space:
mode:
Diffstat (limited to 'Assets/Scripts/PlayerDrag.cs')
-rw-r--r--Assets/Scripts/PlayerDrag.cs55
1 files changed, 31 insertions, 24 deletions
diff --git a/Assets/Scripts/PlayerDrag.cs b/Assets/Scripts/PlayerDrag.cs
index 10300af..8e7a69d 100644
--- a/Assets/Scripts/PlayerDrag.cs
+++ b/Assets/Scripts/PlayerDrag.cs
@@ -1,56 +1,63 @@
+using System;
using UnityEngine;
/// <summary>
/// 简化版玩家拖拽脚本(Trigger触发判定,仅保留核心拖拽逻辑)
/// </summary>
+[RequireComponent(typeof(PlayerControl))]
public class PlayerDrag : MonoBehaviour
{
- // 拖拽核心配置
- [SerializeField] private KeyCode grabKey = KeyCode.G; // 抓取按键
+ private DragItem _currentDragItem;
- // 临时缓存:当前触发接触的可拖拽物品
- private DragItem currentDragItem;
- // 标记是否处于拖拽状态
- private bool isDragging;
+ private bool _isDragging;
- private void Update()
+ private bool _lastFrameGrabbing;
+
+ private PlayerControl _control;
+
+ private void Awake()
{
- // 仅检测G键输入,控制抓取/松开(核心逻辑不变)
- CheckGrabInput();
+ _control = GetComponent<PlayerControl>();
}
-
- private void CheckGrabInput()
+ private void Update()
{
+ var grabbing = _control.grabbing;
+ var keyDown = !_lastFrameGrabbing && grabbing;
+ var keyUp = _lastFrameGrabbing && !grabbing;
+
// 按下G键:抓取物品(仅当触发接触且未拖拽时生效)
- if (Input.GetKeyDown(grabKey) && !isDragging && currentDragItem != null)
+ if (keyDown && !_isDragging && _currentDragItem != null)
{
- isDragging = true;
- currentDragItem.dragger = this.transform; // 给物品赋值拖拽锚点(玩家)
+ _isDragging = true;
+ _currentDragItem.dragger = transform; // 给物品赋值拖拽锚点(玩家)
}
// 松开G键:放下物品(解除关联)
- if (Input.GetKeyUp(grabKey) && isDragging)
+ if (keyUp && _isDragging)
{
- isDragging = false;
- if (currentDragItem != null)
+ _isDragging = false;
+ if (_currentDragItem != null)
{
- currentDragItem.dragger = null; // 清空物品的拖拽锚点
+ _currentDragItem.dragger = null; // 清空物品的拖拽锚点
}
- currentDragItem = null;
+ _currentDragItem = null;
}
+
+ // 更新抓取
+ _lastFrameGrabbing = grabbing;
}
private void OnTriggerStay(Collider other)
{
// 如果已在拖拽状态,直接返回,不处理新物品
- if (isDragging) return;
+ if (_isDragging) return;
// 尝试获取对方的DragItem组件,缓存为当前可抓取物品
DragItem dragItem = other.GetComponent<DragItem>();
if (dragItem != null)
{
- currentDragItem = dragItem;
+ _currentDragItem = dragItem;
}
}
@@ -58,13 +65,13 @@ public class PlayerDrag : MonoBehaviour
private void OnTriggerExit(Collider other)
{
// 如果已在拖拽状态,直接返回(避免拖拽中丢失目标)
- if (isDragging) return;
+ if (_isDragging) return;
// 确认离开的是当前缓存的物品,清空缓存
DragItem dragItem = other.GetComponent<DragItem>();
- if (dragItem != null && dragItem == currentDragItem)
+ if (dragItem != null && dragItem == _currentDragItem)
{
- currentDragItem = null;
+ _currentDragItem = null;
}
}
} \ No newline at end of file