红警框选功能,我这里大概的思路就是用Unity里面的GL来实现,然后把士兵都放在一个链表集合里面,把士兵的坐标转化为屏幕坐标,然后判断是否在框选的范围内,如果在范围内,就进行移动。
(1)建一个材质,这个材质的颜色决定框选的颜色,然后材质的类型设置成UI/Default。
(2)写如下代码
using UnityEngine; using System.Collections; /// <summary> /// GL画框, 该脚本一定要挂载在摄像机上面才可以的 /// </summary> public class CameraGL : MonoBehaviour { public Material mat; //把第一步建的材质托在上面 public bool shouldDrawRect; public Vector2 startPos; public FrameSelect fs; void OnPostRender() { if (shouldDrawRect) { Vector2 endPos = Input.mousePosition; GL.PushMatrix(); mat.SetPass(0); GL.LoadPixelMatrix(); GL.Begin(GL.QUADS); GL.Vertex(startPos); GL.Vertex(new Vector3(startPos.x, endPos.y, 0)); GL.Vertex(endPos); GL.Vertex(new Vector3(endPos.x, startPos.y, 0)); GL.End(); GL.PopMatrix(); fs.selectSoliders.Clear(); foreach (Solider m in fs.allSoliders) { Vector3 pos = m.transform.position; Vector3 tempPos = Camera.main.WorldToScreenPoint(pos); //把世界坐标转化为屏幕坐标 Vector3 p1 = startPos; Vector3 p2 = endPos; if (startPos.x < endPos.x) { p1.x = endPos.x; p2.x = startPos.x; } if (startPos.y < endPos.y) { p1.y = endPos.y; p2.y = startPos.y; } if (tempPos.x > p2.x && tempPos.x < p1.x && tempPos.y > p2.y && tempPos.y < p1.y) { m.select= true; fs.selectSoliders.Add(m); } } } } void Update() { if (Input.GetMouseButtonDown(0)) { shouldDrawRect = true; startPos = Input.mousePosition; } if (Input.GetMouseButtonUp(0)) { shouldDrawRect = false; } } }
3 代码框选控制
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; /// <summary> /// 框选控制 /// </summary> public class FrameSelect : MonoBehaviour { public List<Solider> allSoliders; public List<Solider> selectSoliders; void Awake() { selectSoliders = new List<Solider>(); } void Update() { if(Input.GetKeyDown(KeyCode.Escape)) { foreach (Solider item in selectSoliders) { item.select = false; } selectSoliders.Clear(); } } }
4士兵类
using UnityEngine; using System.Collections; /// <summary> /// 每一个士兵挂载的类 /// </summary> public class Solider : MonoBehaviour { [SerializeField] private bool _select; [SerializeField] private Color color; void Awake() { _select = false; color = GetComponent<MeshRenderer>().material.color; } public bool select { set { _select = value; if (_select) { GetComponent<MeshRenderer>().material.color = Color.green; } else { GetComponent<MeshRenderer>().material.color = color; } } get { return _select; } } }
大概的就是这样,具体的工程文件,我打成了包在下面的地址上面,可以下载,我用的unity版本是5.1.2f的,如果版本低了会打不开,版本高的话可能存在问题
https://files.cnblogs.com/files/ZhiXing-Blogs/FrameSelect.rar