76 lines
2.1 KiB
C#
76 lines
2.1 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
[RequireComponent(typeof(RectTransform))]
|
|
public class LineConnectorUI : MonoBehaviour
|
|
{
|
|
public RectTransform start;
|
|
public RectTransform end;
|
|
public Image lineImage;
|
|
public float thickness = 4f;
|
|
public bool dynamicUpdate = true;
|
|
|
|
private RectTransform rectTransform;
|
|
|
|
private void Awake()
|
|
{
|
|
rectTransform = GetComponent<RectTransform>();
|
|
if (lineImage == null)
|
|
{
|
|
lineImage = GetComponent<Image>();
|
|
}
|
|
}
|
|
|
|
private void LateUpdate()
|
|
{
|
|
if (dynamicUpdate)
|
|
{
|
|
UpdateLine();
|
|
}
|
|
}
|
|
|
|
public void SetEndpoints(RectTransform startPoint, RectTransform endPoint)
|
|
{
|
|
start = startPoint;
|
|
end = endPoint;
|
|
UpdateLine();
|
|
}
|
|
|
|
public void UpdateLine()
|
|
{
|
|
if (start == null || end == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (rectTransform == null)
|
|
{
|
|
rectTransform = GetComponent<RectTransform>();
|
|
}
|
|
|
|
RectTransform parent = rectTransform.parent as RectTransform;
|
|
if (parent == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
Vector2 startPosition = GetCenterInParentSpace(parent, start);
|
|
Vector2 endPosition = GetCenterInParentSpace(parent, end);
|
|
Vector2 delta = endPosition - startPosition;
|
|
|
|
rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
|
|
rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
|
|
rectTransform.pivot = new Vector2(0.5f, 0.5f);
|
|
rectTransform.anchoredPosition = startPosition + delta * 0.5f;
|
|
rectTransform.sizeDelta = new Vector2(delta.magnitude, Mathf.Max(1f, thickness));
|
|
rectTransform.localRotation = Quaternion.Euler(0f, 0f, Mathf.Atan2(delta.y, delta.x) * Mathf.Rad2Deg);
|
|
}
|
|
|
|
private Vector2 GetCenterInParentSpace(RectTransform parent, RectTransform target)
|
|
{
|
|
Vector3 worldCenter = target.TransformPoint(target.rect.center);
|
|
Vector3 localCenter = parent.InverseTransformPoint(worldCenter);
|
|
return new Vector2(localCenter.x, localCenter.y);
|
|
}
|
|
}
|