Unity之GL画线
一、GL画牵引线
注意:若想GL画出来的线显示在UI(UGUI)上面,将UI的画布Canvas的Render Mode设置为为Screen Space - Camera,下面的Render Camera使用主相机,并且保证Sorting Layer 为 Default、 Order in Sorting 值为 0
二、效果图如下:
注意:图中绿色牵引线为GL画线,两头圆圈为UI
三、代码如下
注意:里面有其他与画线无关的代码,可直接忽略
/*******************************************************************************
* 版权声明:,保留所有版权
* 版本声明:v1.0.0
* 类 名 称: DrawLine
* 创建日期:2019-07-30 09:16:51
* 作者名称:静哥哥
* CLR 版本:4.0.30319.42000
* 修改记录:
* 描述:画牵引线
******************************************************************************/using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
namespace Com.Rainier.WangJing
{ public class DrawLine : MonoBehaviour {public Material mat;public GameObject target;public string targetName;public Vector3[] pos = new Vector3[3];private RectTransform mTip;private Text mText;public Color mycolor = Color.green;public bool isShow = true;public Shader shader;public Button mButton;private void Start(){target = gameObject.transform.parent.GetChild(2).gameObject;targetName = this.gameObject.name;mButton = gameObject.GetComponent<Button>();mat = new Material(shader);Init(); }private void Init(){mTip = this.transform.GetComponent<RectTransform>();mText = mTip.transform.GetComponentInChildren<Text>();// mButton = mTip.transform.GetComponentInChildrenRefresh();mButton.onClick.AddListener(ButtonClickToSwitch);}private void ButtonClickToSwitch(){isShow = !isShow;if (isShow){target.SendMessage("Showing", SendMessageOptions.DontRequireReceiver);}else{target.SendMessage("Closing", SendMessageOptions.DontRequireReceiver);}}private void Update(){Refresh();}public void Refresh(){//初始物体起点//pos[0] = Camera.main.WorldToScreenPoint(target.transform.position);pos[0] = target.transform.position;//判断目标在标签左右哪侧int side = 1;if (pos[0].x > mTip.position.x){side = -1;}//折转点pos[1] = pos[0] + new Vector3(50F, 0F, 0F) * side;//终点为TEXTpos[2] = mTip.position;mText.text = targetName;初始物体起点//pos[0] = Camera.main.WorldToScreenPoint(target.transform.position);//Vector3 m_Screen = RectTransformUtility.WorldToScreenPoint(Camera.main, mTip.position);判断目标在标签左右哪侧//int side = 1;//if (pos[0].x > m_Screen.x)//{// side = -1;//}折转点//pos[1] = pos[0] + new Vector3(50F, 0F, 0F) * side;终点为TEXT//pos[2] = m_Screen;mText.text = targetName;}private void OnRenderObject(){if (!isShow)return;GL.PushMatrix();mat.SetPass(0);GL.LoadOrtho();GL.Begin(GL.LINES);GL.Color(new Color(142F/255F,188F/255F,50F/255F));//遍历所有点for (int i = 0; i < pos.Length - 1; i++){//GL.glLineWidth(5);GL.Vertex3(pos[i].x / Screen.width, pos[i].y / Screen.height, 0);GL.Vertex3(pos[i + 1].x / Screen.width, pos[i + 1].y / Screen.height, 0);}GL.End();GL.PopMatrix();}}
}
综上所示,如有问题欢迎提出,谢谢
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!