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 @   三页菌  阅读(904)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
历史上的今天:
2020-01-09 unity Addressable Asset
2020-01-09 Unity直接读取Excel之Unity quick sheet
2020-01-09 使用markdown
2019-01-09 unity 优化之overdraw查看
点击右上角即可分享
微信分享提示