using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class GameObjectPiaker : MonoBehaviour { private IPicked currentPickedGO;//当前拾起的物体 // Start is called before the first frame update void Start() { } //注入一个待放置的物体 无法重复注入 即当前正持有物体时 不在捡起新的物体 public void InjectGO(IPicked picked) { if (currentPickedGO != null) { Debug.Log("当前持有物体,无法捡起新的物体"); return; } CameraCtrl.Instance.rightButtonEvent += TryStopPick; currentPickedGO = picked; picked.PickUp();//捡起该物体 } public GameObject GetCurrentPickGO() { return currentPickedGO?.GetGameObject(); } //移动物体 public void MoveGO(Vector3 vector) { if (currentPickedGO==null) return; currentPickedGO.GetGameObject().transform.position = vector; } //尝试放置物体在地面上 private void TrySetGOOnFloor(Vector3 pos) { if (currentPickedGO == null) return; if (!currentPickedGO.CanPickDown()) { Debug.Log(currentPickedGO.GetGameObject().name + "不能放置在当前位置"); return; } currentPickedGO.PickDown(); currentPickedGO = null; } //尝试放弃物体 void TryStopPick() { if (currentPickedGO == null) return; if (!currentPickedGO.CanStopPick())//尝试停止 { currentPickedGO.StopPick(); currentPickedGO = null;//删除当前控制的物体时 移除移动/右键空白地面/点击地面事件 CameraCtrl.Instance.rightButtonEvent -= TryStopPick; } } float doubleClickTime; //射线检测捡起或删除物体 private void Update() { if (EventSystem.current != null && EventSystem.current.IsPointerOverGameObject()) return; //相机控制时屏蔽UI部分 if (currentPickedGO == null)//当前物体未放下时 不允许拾取新的物体 { if (Input.GetKey(KeyCode.LeftControl) && Input.GetMouseButtonDown(0))//左Ctrl+左键点击物体时 拾取指定层级的物体 { GameObject hitGo = GetMouseRayHitGO("Flag"); if (hitGo) { IPicked pciked = hitGo.GetComponent(); if (pciked != null && pciked.CanPickUpByRay()) InjectGO(pciked); } } } else//不为空时 实时检测射线位置 在射线检测点击到的地面 尝试放置物体 { RaycastHit hit;//鼠标射线检测 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, 2000, LayerMask.GetMask("Floor"))) { MoveGO(hit.point); if (Input.GetMouseButtonDown(0))//左键 点击到地面时 放置该物体 { TrySetGOOnFloor(hit.point); } } } } //获取射线检测到的当前物体 GameObject GetMouseRayHitGO(string layer) { RaycastHit hit;//鼠标射线检测 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, 2000, LayerMask.GetMask(layer)))//点到指定层级的物体 { return hit.collider.gameObject; } return null; } }