Unity2D Canvas多对象画线功能实现求助
Unity2D Canvas关卡绘制问题求助

我需要在Unity2D的Canvas中制作如图所示的关卡,但尝试多种方法均未成功。
我找到一段使用Image而非Line Renderer在Canvas上绘制两点连线的代码,但将其应用到多个对象时无法正常工作。已耗时4天仍未解决问题,希望能获得实现指南或相关协助,感谢。
using UnityEngine; using UnityEngine.UI; public class SimpleLineUI : MonoBehaviour { [SerializeField] private Image lineImage; [SerializeField] private float thickness = 5; [SerializeField] private Color color = Color.black; public float Length => length; private Vector2 startPoint; private Vector2 targetPoint; private float length; private void Awake() { lineImage.color = color; ResetLine(); } public void SetStartPoint(Vector2 position, bool update = true) { startPoint = position; if (update) UpdateLine(); } public void SetTargetPoint(Vector2 position, bool update = true) { targetPoint = position; if (update) UpdateLine(); } public void SetThickness(float thickness) { if (this.thickness != thickness) { this.thickness = thickness; lineImage.rectTransform.sizeDelta = new Vector2(length, thickness); } } public void SetColor(Color color) { if (this.color != color) { this.color = color; lineImage.color = color; } } public void ResetLine() { length = 0; SetStartPoint(Vector2.zero, false); SetTargetPoint(Vector2.zero, false); lineImage.rectTransform.sizeDelta = Vector2.zero; } private void UpdateLine() { var direction = targetPoint - startPoint; var rotationAngle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; length = direction.magnitude; lineImage.rectTransform.anchoredPosition = startPoint; lineImage.rectTransform.sizeDelta = new Vector2(length, thickness); lineImage.rectTransform.rotation = Quaternion.Euler(0, 0, rotationAngle); } }
该代码使用Image而非Line Renderer,以确保线条显示在Canvas上。
内容的提问来源于stack exchange,提问作者Salman Moussa
相关产品推荐
相关产品推荐

