Unity设置图片绘制线条,比GL好用N倍

Unity设置图片绘制线条,比GL好用N倍

  • 首先,得说明这是相对于需要渲染的GL来说(打包在手机上)性能上更优化;

  • 其次,感谢上一搏主的解析,十分通俗易懂适合新手;

  • 最后,记得看清楚注释。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class SetImageLine: MonoBehaviour {
    
    
    public Image image;//导入直线素材(图片转精灵后拉入)  给个红颜色用于识别
    public Vector2 rectA;//指的是直线起点
    public  Vector2 rectB;//直线终点
    public Button button;//画直线按钮
    public RectTransform point;//导入一张圆形(图片并转精灵后拉入)辅助显示起点终点位置的小圆形,圆形图片给个黄色用于识别
    public RectTransform LineParent;//设置直线的父物体(一般可直接挂Canvas/Panel)
    void Start () 
    {
    
    
        Debug.Log(GetComponent<RectTransform>().anchoredPosition);
        button.onClick.AddListener(DrawLineClick);//给按钮添加事件
	}
  
    //划线功能
    void DrawLineClick()
    {
    
    
        DrawStraightLine(rectA, rectB, image.rectTransform, point,transform);
    }
 
    //划线功能
    void DrawStraightLine(Vector2 a,Vector2 b, RectTransform prefab,RectTransform point,Transform LP)
    {
    
    
        if (a != b)
        {
    
    
           	LP = LineParent;
            GameObject point1 = Instantiate(point.gameObject, LineParent);
            GameObject point2 = Instantiate(point.gameObject, LineParent);
            point1.SetActive(true);
            point2.SetActive(true);
            point1.GetComponent<RectTransform>().anchoredPosition = a;
            point2.GetComponent<RectTransform>().anchoredPosition = b;
 
            float distance = Vector2.Distance(a, b);//计算起点终点两点距离
            float angle = Vector2.SignedAngle(a - b, Vector2.left);//求夹角  计算起点终点的向量和 Vector2.left的夹角
 
            GameObject go = Instantiate(image.gameObject, LineParent);//克隆预设进行划线
            go.gameObject.SetActive(true);
            go.GetComponent<RectTransform>().anchoredPosition = (a + b) / 2;
            go.GetComponent<RectTransform>().sizeDelta = new Vector2(distance, 5);
            go.transform.localRotation = Quaternion.AngleAxis(-angle, Vector3.forward);
            Debug.Log("distance:" + distance + "  angle:" + angle + "  imagePos:" + image.rectTransform.anchoredPosition);
        }
 
    }
 
    // Update is called once per frame
    void Update () {
    
    
		
	}
}

————————————————

版权声明:本文为CSDN博主「那个妹子留步」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/weixin_41995872/article/details/85695099

猜你喜欢

转载自blog.csdn.net/lds1942816258/article/details/119758024
今日推荐