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