网上找了很多都没有看到保持z值不变的方法,自己写了一下:
将下面这个脚本绑到摄像机运行就可。
using UnityEngine;
public class CameraMove : MonoBehaviour
{
public float rotateSpeed = 3.5f;//摄像机旋转速度。
public float moveSpeed = 3.5f;//摄像机移动速度。
private bool isRotate;
void Update()
{
CameraRotateView();
Move();
}
//按下左键镜头跟随鼠标移动,松开不移动
void CameraRotateView()
{
if (Input.GetMouseButtonUp(0))
isRotate = false;
if (Input.GetMouseButtonDown(0))
isRotate = true;
if (isRotate)
{
float swipeUpOrDown = rotateSpeed * Input.GetAxis("Mouse Y");
float swipeLeftAndRight = rotateSpeed * Input.GetAxis("Mouse X");
if (Mathf.Abs(swipeUpOrDown) < Mathf.Abs(swipeLeftAndRight))
{
//向右滑动时正值,向左滑动是负值。
transform.RotateAround(transform.position, Vector3.up, swipeLeftAndRight);
}
else
{
//使用自身的x轴作为旋转轴,这样保证z轴不会发生数值变化
transform.RotateAround(transform.position, transform.right, -swipeUpOrDown);
}
}
}
void Move()
{
float beforeOrAfter = Input.GetAxis("Horizontal");
float swipeLeftAndRight = Input.GetAxis("Vertical");
transform.position += transform.forward * swipeLeftAndRight * Time.deltaTime*moveSpeed;
transform.position += transform.right * beforeOrAfter * Time.deltaTime*moveSpeed;
}
}