Unity实战 RTS3D即时战略游戏开发(五) 鼠标管理器

来源:互联网 发布:淘宝国产高达禁卖 编辑:程序博客网 时间:2024/05/21 17:55

     大家好,我是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 framevoid 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))  //如果没有点到任何东西,returnreturn;var interact = hit.transform.GetComponent<Interactive> (); //检测物体的Interactive组件,如果Null 则返回if (interact == null)return;Selections.Add (interact);interact.Select ();}}
   然后把MouseManager脚本拖拽到场景中的Manager上,因为我们使用的是物理检测,所以在射线检测时要求物体必须有碰撞体。所以我们要为DroneUnit预设体添加碰撞盒子,建议使用性能消耗低的SphereCollider碰撞体。

    好了,这节的内容就到这了,欢迎大家加入QQ群:280993838  或者关注我的公众号:



1 0
原创粉丝点击