Unity 鼠标控制相机旋转移动
程序员文章站
2024-03-16 20:20:16
...
Unity 鼠标控制相机旋转移动
一直白嫖,尝试写点东西吧,一小段代码,解决了相机旋转后再移动方向跟着变的问题,有不对的地方希望大佬们多多指教
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class CameraMoveTest : MonoBehaviour
{
float moveH, moveV, viewNum;
public float moveSpeed=10f, rotaSpeed=50f, viewSpeed=5f;
private Vector3 resetPosition;
Vector3 dir1=Vector3.right;
Vector3 dir2=Vector3.forward;
// Start is called before the first frame update
void Start()
{
resetPosition = transform.position;
dir1 = (Mathf.Cos(transform.localEulerAngles.x) * transform.right).normalized;
dir2 = new Vector3((Mathf.Cos(transform.localEulerAngles.z) * transform.forward).x, 0, (Mathf.Cos(transform.localEulerAngles.z) * transform.forward).z).normalized;
}
// Update is called once per frame
void Update()
{
#if UNITY_ANDROID
#else
if (!EventSystem.current.IsPointerOverGameObject())
{
if (Input.GetMouseButton(0))
{
CamMove();
}
if (Input.GetMouseButton(1))
{
CamRota();
}
CamView();
}
#endif
}
void CamMove()
{
moveH = Input.GetAxis("Mouse X");
moveV = Input.GetAxis("Mouse Y");
if (moveV != 0 || moveH != 0)
{
transform.localPosition += dir1 * -moveH * moveSpeed * Time.deltaTime;
transform.localPosition += dir2 * -moveV * moveSpeed * Time.deltaTime;
}
}
void CamRota()
{
moveH = Input.GetAxis("Mouse X");
moveV = Input.GetAxis("Mouse Y");
if (moveH!=0||moveV!=0)
{
float anglex = -moveV * rotaSpeed * Time.deltaTime;
float angley = rotaSpeed * moveH * Time.deltaTime;
Quaternion tempRotation1 = Quaternion.Euler(anglex,angley , 0f);
transform.localEulerAngles = new Vector3((transform.localRotation * tempRotation1).eulerAngles.x, (transform.localRotation * tempRotation1).eulerAngles.y, 0);
dir1 = (Mathf.Cos(anglex) * transform.right).normalized;
dir2 = new Vector3((Mathf.Cos(angley) * transform.forward).x,0,(Mathf.Cos(angley) * transform.forward).z).normalized;
}
}
void CamView()
{
viewNum = Input.GetAxis("Mouse ScrollWheel");
if (viewNum!=0)
{
transform.GetComponent<Camera>().fieldOfView +=viewNum * viewSpeed;
}
}
}