我们分两种情况,一种是UI上连线,一种是世界坐标下连线。
UI用
效果图
UI代码示例
public class DrawLine : MonoBehaviour
{
[Header("Point")]
public RectTransform startPoint;
public RectTransform endPoint;
public GameObject linePrefab;
public float lineWidth;
private GameObject m_line;
private RectTransform m_rect;
private RectTransform m_lineRect;
private void Awake()
{
m_rect = GetComponent<RectTransform>();
}
private void Start()
{
m_line = CreateLine(m_rect.anchoredPosition, endPoint.anchoredPosition);
m_line.transform.SetAsFirstSibling();
}
private void Update()
{
DrawStraightLine(m_line, m_rect.anchoredPosition, endPoint.anchoredPosition);
}
public GameObject CreateLine(Vector2 startPoint, Vector2 endPoint)
{
GameObject line = Instantiate(linePrefab, transform.parent);
m_lineRect = line.GetComponent<RectTransform>();
return line;
}
private void DrawStraightLine(GameObject line, Vector2 a, Vector2 b)
{
float distance = Vector2.Distance(a, b);
float angle = Vector2.SignedAngle(a - b, Vector2.left);
line.GetComponent<RectTransform>().anchoredPosition = (a + b) / 2;
line.GetComponent<RectTransform>().sizeDelta = new Vector2(distance, lineWidth);
line.transform.localRotation = Quaternion.AngleAxis(-angle, Vector3.forward);
}
}
挂载示例
世界坐标用
挂载示例
简单一点的方法是直接用Unity自带的Line Renderer 在一个游戏对象上挂载Line Renderer
效果图
世界坐标代码示例
public class LineRendererText : MonoBehaviour
{
public Transform startPoint;
public Transform endPoint;
private LineRenderer m_lineRenderer;
private void Awake()
{
m_lineRenderer = GetComponent<LineRenderer>();
}
private void Update()
{
m_lineRenderer.SetPosition(0, startPoint.position);
m_lineRenderer.SetPosition(1, endPoint.position);
}
}
|