using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class CameraChange : MonoBehaviour
{
public GameObject CameraMain;
public GameObject Camera2;
public GameObject Camera3;
private Vector3 Position;
private Quaternion Rotation;//临时存储相机的位置和旋转信息
void Update()
{
//首先检查鼠标左键是否按下。如果按下且光标位于某个UI元素上方,则调用Skode_GetCurrentSelect()获取当前选中的UI对象。
//接着判断该对象的名称,若为"View1"或"View2",则调用CameraLocationExChange()方法交换相应相机的位置和旋转
if (Input.GetMouseButtonDown(0))
{
if (EventSystem.current.IsPointerOverGameObject())
{
GameObject obj = Skode_GetCurrentSelect();
if (obj != null)
{
//点击视角1
if (obj.name == "View1")
{
CameraLocationExChange(CameraMain, Camera2);
}
//点击视角2
else if (obj.name == "View2")
{
CameraLocationExChange(CameraMain, Camera3);
}
}
Debug.Log("点击到UGUI的UI界面");
}
else
{
Debug.Log("没点击到UGUI上的任何东西");
}
}
}
//先将cameraMain的当前位置和旋转保存到临时变量Position和Rotation,然后将cameraMain设置为camera2的位置和旋转,最后将camera2恢复为之前保存的Position和Rotation,从而实现视角的互换
private void CameraLocationExChange(GameObject cameraMain, GameObject camera2)//交换两个相机(cameraMain和camera2)的位置和旋转
{
Position = cameraMain.transform.position;
Rotation = cameraMain.transform.rotation;
cameraMain.transform.position = camera2.transform.position;
cameraMain.transform.rotation = camera2.transform.rotation;
camera2.transform.position = Position;
camera2.transform.rotation = Rotation;
}
/// <summary>
/// 获得当前点击到的UI物体
/// </summary>
public GameObject Skode_GetCurrentSelect()
{
GameObject obj = null;
GraphicRaycaster[] graphicRaycasters = FindObjectsOfType<GraphicRaycaster>();// 查找场景中所有GraphicRaycaster组件
PointerEventData eventData = new PointerEventData(EventSystem.current);
eventData.pressPosition = Input.mousePosition;
eventData.position = Input.mousePosition;// 创建并初始化PointerEventData对象,设置其位置为鼠标光标位置
List<RaycastResult> list = new List<RaycastResult>();
foreach (var item in graphicRaycasters)
{
item.Raycast(eventData, list);//Raycast方法对UI元素进行射线检测,并将结果存储在list中。如果列表中有检测到的UI元素,将最后一个元素对应的gameObject赋值给obj
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
obj = list[i].gameObject;
}
}
}
return obj;
}
}