diff options
| author | 魏曹先生 <1992414357@qq.com> | 2026-01-31 00:58:15 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2026-01-31 00:58:15 +0800 |
| commit | 81cc6cf8bbc2572528252b6ed67f90aa179c6542 (patch) | |
| tree | 0e2ab869f1e4501aa76be74c8a673d847eb9c98e /Assets/Scripts | |
| parent | bdd0c3eee905c5dc6fcf22344f7fdbd4cc3e3a02 (diff) | |
增加拖拽功能
Diffstat (limited to 'Assets/Scripts')
| -rw-r--r-- | Assets/Scripts/DragItem.cs | 79 | ||||
| -rw-r--r-- | Assets/Scripts/DragItem.cs.meta | 2 |
2 files changed, 81 insertions, 0 deletions
diff --git a/Assets/Scripts/DragItem.cs b/Assets/Scripts/DragItem.cs new file mode 100644 index 0000000..46ba50f --- /dev/null +++ b/Assets/Scripts/DragItem.cs @@ -0,0 +1,79 @@ +using UnityEngine; + +public class DragItem : MonoBehaviour +{ + private Vector3 SelfPivot + { + get + { + var p = transform.position; + return new Vector3(p.x, 0, p.z); + } + } + + private Vector3 DraggerPivot + { + get + { + var p = dragger.position; + return new Vector3(p.x, 0, p.z); + } + } + + private bool _dragging; + public Transform dragger; + + private Vector3 _lastDirection; + private Vector3 _lastSelfPivot; + private float _lastAngle; + private float _lastLength; + private int _currentStep; + + private void FixedUpdate() + { + FixedUpdateDragger(); + + // 判断是否在拖拽 + if (! _dragging) return; + + // 位置计算 + var draggerPivot = DraggerPivot; + var selfPivot = SelfPivot; + var direction = (_lastSelfPivot - draggerPivot).normalized; + var position = draggerPivot + direction * _lastLength; + var y = transform.position.y; + transform.position = new Vector3( + position.x, + y, + position.z + ); + + // 角度计算 + if (direction != _lastDirection) + { + var angle = Vector3.SignedAngle(direction, _lastDirection, Vector3.up); + var selfAngle = transform.eulerAngles; + selfAngle.y -= angle; + transform.eulerAngles = selfAngle; + } + + // 记录值 + _lastSelfPivot = selfPivot; + _lastDirection = direction; + } + + private void FixedUpdateDragger() + { + if (!_dragging && dragger != null) + { + _dragging = true; + var draggerPivot = DraggerPivot; + _lastSelfPivot = SelfPivot; + _lastLength = Vector3.Distance(draggerPivot, SelfPivot); + _lastDirection = (_lastSelfPivot - draggerPivot).normalized; + } + + if (_dragging && dragger == null) + _dragging = false; + } +} diff --git a/Assets/Scripts/DragItem.cs.meta b/Assets/Scripts/DragItem.cs.meta new file mode 100644 index 0000000..d32339a --- /dev/null +++ b/Assets/Scripts/DragItem.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c69e2aa4d45550a818a819efbd91c846
\ No newline at end of file |
