You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 13:42:40