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);
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM