using UnityEngine; namespace TowerDefense.UI { /// /// A class for controlling conditional motion of the canvas /// [RequireComponent(typeof(Canvas))] public class MovingCanvas : MonoBehaviour { /// /// The RectTransform used to check against the screen bounds /// public RectTransform content; /// /// To offset the position the canvas is placed at /// public Vector2 offset; /// /// The attached canvas /// Canvas m_Canvas; /// /// Property for disabling and enabling the attached canvas /// public bool canvasEnabled { get { if (m_Canvas == null) { m_Canvas = GetComponent(); } return m_Canvas.enabled; } set { if (m_Canvas == null) { m_Canvas = GetComponent(); } m_Canvas.enabled = value; } } /// /// Try to move the canvas based on 's rect /// /// /// The position to move to /// 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; } /// /// Cache the attached canvas /// protected virtual void Awake() { canvasEnabled = false; } } }