using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingFunction : MonoBehaviour
{
//相机
public Camera cam;
//点击到的物体
GameObject gameObj;
//得到物体计算后相机移动到的点
Vector3 targetPos;
//速度
float speed = 1f;
//步
float step;
//是否点击按钮1
bool isB1 = false;
//是否点击按钮2
bool isB2 = false;
//是否点击按钮3
bool isB3 = false;
//是否鼠标点击物体
bool isMouseClick = false;
//镜头移动状态(若当前移动状态为真,为正在移动,则点击其他物体或点击按钮不产生效果)
bool isMoving = false;
//是否旋转
bool isrotate = false;
void Start()
{
step = (speed * Time.deltaTime);
}
void Update()
{
//发出射线,当点击到物体且摄像机非移动状态(Moving==false)时
//得到该物体坐标,摄像机移动到该物体z轴-10的位置
//运行射线方法移动函数,位移状态改变为真
if (Input.GetMouseButtonDown(0) && isMoving == false)
// if(Input.GetKey(KeyCode.Mouse0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
//得到鼠标左键点击的物体gameObj
gameObj = hitInfo.collider.gameObject;
//输出物体的位置
//Debug.Log(gameObj.transform.position);
//输出物体名称
//Debug.Log(gameObj.name);
//输出目标位置
//Debug.Log("target location"+gameObj.transform.position);
//输出处理后摄像机移动位置
//Debug.Log(gameObj.transform.position + new Vector3(0, 0, -10));
//摄像机移动的目标点位置
targetPos = gameObj.transform.position + new Vector3(0, 0, -10);
//鼠标点击,移动状态,旋转状态
isMouseClick = true;
isMoving = true;
isrotate = true;
}
}
if (isMouseClick) {
moving_check(targetPos);
}
if (isB1 || isB2 || isB3) {
if (isB1)
{
moving_check(new Vector3(0, 0, -10), ref isB1,new Vector3(0,0,0));
}
if (isB2)
{
moving_check(new Vector3(5, 0, -10), ref isB2, new Vector3(5, 0, 0));
}
if (isB3)
{
moving_check(new Vector3(10, 0, -10), ref isB3, new Vector3(10, 0, 0));
}
}
if (isrotate) {
RotateCamera(cam.transform.position, gameObj.transform.position);
}
}
void moving_check(Vector3 v) {
//摄像机位置移动到v位置
cam.transform.localPosition = Vector3.MoveTowards(cam.transform.localPosition, v, step);
//当到达目的地,关闭移动状态
if (cam.transform.localPosition == v)
{
isMouseClick = false;
isMoving = false;
isrotate = false;
}
}
void moving_check(Vector3 v, ref bool b,Vector3 v2)
{ //摄像机移动目的地,按钮状态(启用/未启用),目标点
//调用按钮方法
RotateCamera(cam.transform.position, v2);
cam.transform.localPosition = Vector3.MoveTowards(cam.transform.localPosition, v, step);
if (cam.transform.localPosition == v)
{
b = false;
isMoving = false;
}
}
public void RotateCamera (Vector3 v1,Vector3 v2)
{ //v1=摄像机,v2=目标
Quaternion q = Quaternion.LookRotation(v2 - v1);
cam.transform.rotation=Quaternion.Slerp(cam.transform.rotation, q, 10 * Time.deltaTime);
}
public void clickButton()
{ //当移动状态为假时执行
if (isMoving==false) {
var button = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject;
//print(button.name);
switch (button.name)
{
case "cube1": isB1 = true;isMoving = true; break;
case "cube2": isB2 = true;isMoving = true; break;
case "cube3": isB3 = true;isMoving = true; break;
}
}
}
}