大家好,我是Zander,我们接着来开发Rts3D即时战略游戏开发。上一章我们对单位选中时进行了处理,接下来我们来处理 一下输入控制。
现在我简单的来说一下鼠标控制管理器的作用,它用于检测鼠标点击,特别是在3D空间内的点击物体。如果检测到点击交互我们就调用之前写好的Select函数,取消选择时我们就会调用Deselect 函数,此外当按下Shift键时还能处理多选功能,下面我们来实现一下这些功能:首先创建一个MouseManager脚本,相关代码如下:
using UnityEngine;
using System.Collections.Generic;
public class MouseManager : MonoBehaviour {
private List<Interactive> Selections = new List<Interactive>(); //被选中物体的集合
// Update is called once per frame
void Update () {
if (!Input.GetMouseButtonDown (0)) //如果没有点击鼠标左键就跳过处理,节省性能
return;
var es = UnityEngine.EventSystems.EventSystem.current;
if (es != null && es.IsPointerOverGameObject())//如果用户点击了2D空间中的某些UI元素,我们就要避免选中UI后的3D对象,同时还要检测是否点击了2D元素
return;
if (Selections.Count > 0) {
if (!Input.GetKey(KeyCode.LeftShift) && !Input.GetKey(KeyCode.RightShift)) //移除已经被鼠标右键选中的和被按键左Shift键多选的
{
foreach(var sel in Selections)
{
if (sel != null) sel.Deselect();
}
Selections.Clear();
}
}
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (!Physics.Raycast (ray, out hit)) //如果没有点到任何东西,return
return;
var interact = hit.transform.GetComponent<Interactive> (); //检测物体的Interactive组件,如果Null 则返回
if (interact == null)
return;
Selections.Add (interact);
interact.Select ();
}
}
然后把MouseManager脚本拖拽到场景中的Manager上,因为我们使用的是物理检测,所以在射线检测时要求物体必须有碰撞体。所以我们要为DroneUnit预设体添加碰撞盒子,建议使用性能消耗低的SphereCollider碰撞体。
好了,这节的内容就到这了,欢迎大家加入QQ群:280993838 或者关注我的公众号: