You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
1.3 KiB
42 lines
1.3 KiB
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class LineBetweenObjects : MonoBehaviour
|
|
{
|
|
[SerializeField] RectTransform start;
|
|
[SerializeField] RectTransform end;
|
|
[SerializeField] Image lineImg;
|
|
|
|
public void SetStart(RectTransform start) => this.start = start;
|
|
public void SetEnd(RectTransform end) => this.end = end;
|
|
|
|
private void OnEnable()
|
|
{
|
|
lineImg?.gameObject.SetActive(true);
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
lineImg?.gameObject.SetActive(false);
|
|
}
|
|
|
|
private void Start()
|
|
{
|
|
lineImg.rectTransform.pivot = new Vector2(0.5f, 0.5f);
|
|
lineImg.rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
|
|
lineImg.rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
|
|
}
|
|
|
|
private void LateUpdate()
|
|
{
|
|
Vector2 lineCenterPos = Vector2.Lerp(start.anchoredPosition, end.anchoredPosition, 0.5f);
|
|
float lineLength = Vector2.Distance(start.anchoredPosition, end.anchoredPosition);
|
|
|
|
Vector2 diff = end.anchoredPosition - start.anchoredPosition;
|
|
float angle = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
|
|
|
|
lineImg.rectTransform.sizeDelta = new Vector2(lineLength, lineImg.rectTransform.sizeDelta.y);
|
|
lineImg.rectTransform.anchoredPosition = lineCenterPos;
|
|
lineImg.rectTransform.localEulerAngles = new Vector3(0, 0, angle);
|
|
}
|
|
}
|