wangguan
2020-10-21 c4b8dbd94f555b599bc847b7fa8a2e1c6caf31e1
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
80
81
82
83
84
85
86
87
88
using UnityEngine;
 
namespace TowerDefense.UI
{
    /// <summary>
    /// A class for controlling conditional motion of the canvas
    /// </summary>
    [RequireComponent(typeof(Canvas))]
    public class MovingCanvas : MonoBehaviour
    {
        /// <summary>
        /// The RectTransform used to check against the screen bounds
        /// </summary>
        public RectTransform content;
 
        /// <summary>
        /// To offset the position the canvas is placed at
        /// </summary>
        public Vector2 offset;
 
        /// <summary>
        /// The attached canvas
        /// </summary>
        Canvas m_Canvas;
 
        /// <summary>
        /// Property for disabling and enabling the attached canvas
        /// </summary>
        public bool canvasEnabled
        {
            get
            {
                if (m_Canvas == null)
                {
                    m_Canvas = GetComponent<Canvas>();
                }
                return m_Canvas.enabled;
            }
            set
            {
                if (m_Canvas == null)
                {
                    m_Canvas = GetComponent<Canvas>();
                }
                m_Canvas.enabled = value;
            }
        }
 
        /// <summary>
        /// Try to move the canvas based on <see cref="content"/>'s rect
        /// </summary>
        /// <param name="position">
        /// The position to move to
        /// </param>
        public void TryMove(Vector3 position)
        {
            Rect rect = content.rect;
            position += (Vector3) offset;
            rect.position = position;
 
            if (rect.xMin < rect.width * 0.5f)
            {
                position.x = rect.width * 0.5f;
            }
            if (rect.xMax > Screen.width - rect.width * 0.5f)
            {
                position.x = Screen.width - rect.width * 0.5f;
            }
            if (rect.yMin < rect.height * 0.5f)
            {
                position.y = rect.height * 0.5f;
            }
            if (rect.yMax > Screen.height - rect.height * 0.5f)
            {
                position.y = Screen.height - rect.height * 0.5f;
            }
            transform.position = position;
        }
 
        /// <summary>
        /// Cache the attached canvas
        /// </summary>
        protected virtual void Awake()
        {
            canvasEnabled = false;
        }
    }
}