Unity 使用image绘制线段 直线

一个类即可

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ImageLine : MonoBehaviour
{
    //线条宽度
    public float lineWidth = 10;

    private Transform pos1;
    private Transform pos2;
    
    
    public void SetLine(Vector3 v1, Vector3 v2)
    {
        gameObject.SetActive(true);
        Vector3 mid = (v1 - v2) / 2;
        GetComponent<RectTransform>().anchoredPosition = mid;
        GetComponent<RectTransform>().sizeDelta = new Vector2(Vector3.Distance(v1, v2), lineWidth);
        //最后一个 Vector3.forward 控制方向正负,加负号可逆转方向
        GetComponent<RectTransform>().rotation = Quaternion.AngleAxis(Vector3.Angle(mid, Vector3.right),Vector3.forward);
    }

    //设置线段起点和终点(一般调用这个即可)
    public void SetLine(Transform t1, Transform t2)
    {
        pos1 = t1;
        pos2 = t2;
        Vector3 v1 = t1.transform.position;
        Vector3 v2 = t2.transform.position;
        SetLine(v1, v2);
    }

    //重新调整线段
    public void ResetLine()
    {
        if (pos1 != null && pos2 != null)
        {
            SetLine(pos1, pos2);
        }
    }
}

 

posted @ 2021-01-09 20:12  三页菌  阅读(743)  评论(0编辑  收藏  举报