summaryrefslogtreecommitdiff
path: root/Assets/Scripts/DragItem.cs
blob: 46ba50f9c12002762eebd1bfa8e7f8e434f7a29d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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;
    }
}