using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class MouseLookSS : MonoBehaviour {
public enum RotationAxes
{
MouseXAndY = 0,
MouseX = 1,
MouseY = 2
}
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityHor = 9.0f;
public float sensitivityVert = 9.0f;
public float minimumVert = -45.0f;
public float maximumVert = 45.0f;
private float _rotationX = 0;
bool isonui;//判斷是否需要旋轉攝像頭
void Start()
{
// Make the rigid body not change rotation
Rigidbody body = GetComponent<Rigidbody>();
if (body != null)
body.freezeRotation = true;
}
void Update()
{
Ispointetovergameobject(Input.mousePosition);
if(!isonui)
{
if (Input.GetMouseButton(0))
{
RotateView();
Cursor.visible = false;
}
}
if (Input.GetMouseButtonUp(0))
{
Cursor.visible = true;
RotateView();
isonui = false;
}
}
/// <summary>
/// 旋轉攝像頭第一人稱視角
/// </summary>
private void RotateView()
{
if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityHor, 0);
}
else if (axes == RotationAxes.MouseY)
{
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
transform.localEulerAngles = new Vector3(_rotationX, transform.localEulerAngles.y, 0);
}
else
{
float rotationY = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityHor;
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
}
/// <summary>
/// 判斷是否點選到UI
/// </summary>
/// <param name="input"></param>
void Ispointetovergameobject(Vector2 input)
{
PointerEventData eventData = new PointerEventData(EventSystem.current);
eventData.position = input;
List<RaycastResult> rayresults = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventData, rayresults);
if (Input.GetMouseButtonDown(0))
{
for (int i = 0; i < rayresults.Count; i++)
{
if (rayresults[i].gameObject.tag == "ui")
{
isonui = true;
}
}
}
}
}