自由摄像机
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
[AddComponentMenu("Camera/FreeCamera")]
public class FreeCamera : MonoBehaviour
{
private Vector3 _oldMousePosition;
private Vector3 _newMousePosition;
[SerializeField]
private float _flMinimumY = 0.2f;
[SerializeField]
private float _flZoomSpeed = 30.0f;
[SerializeField]
private float _flKeyBoardMoveSpeed = 1f;
[SerializeField]
private float _flRoteSpeed = 0.05f;
private float _fldistance = 5;
private Vector3 _initPos = Vector3.zero;
private Vector3 _initRot = Vector3.zero;
private void Awake()
{
_initPos = transform.position;
_initRot = transform.eulerAngles;
}
private void OnEnable()
{
transform.position = _initPos;
transform.eulerAngles = _initRot;
}
void Update()
{
MoveCameraKeyBoard();
ZoomCamera();
CameraRotation();
_oldMousePosition = Input.mousePosition;
}
private void MoveCameraKeyBoard()
{
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
transform.Translate(new Vector3(-_flKeyBoardMoveSpeed, 0, 0), Space.Self);
}
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
transform.Translate(new Vector3(_flKeyBoardMoveSpeed, 0, 0), Space.Self);
}
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(new Vector3(0, 0, _flKeyBoardMoveSpeed), Space.Self);
}
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(new Vector3(0, 0, -_flKeyBoardMoveSpeed), Space.Self);
}
if (Input.GetKey(KeyCode.E))
{
transform.Translate(new Vector3(0, _flKeyBoardMoveSpeed, 0), Space.World);
}
if (Input.GetKey(KeyCode.Q))
{
if (transform.transform.position.y - _flKeyBoardMoveSpeed >= this._flMinimumY)
transform.Translate(new Vector3(0, -_flKeyBoardMoveSpeed, 0), Space.World);
}
}
private void CameraRotation()
{
if (Input.GetMouseButton(1))
{
_newMousePosition = Input.mousePosition;
Vector3 dis = _newMousePosition - _oldMousePosition;
float angleX = dis.x * _flRoteSpeed;
float angleY = dis.y * _flRoteSpeed;
transform.Rotate(new Vector3(-angleY, 0, 0), Space.Self);
transform.Rotate(new Vector3(0, angleX, 0), Space.World);
}
}
private void ZoomCamera()
{
float offset = Input.GetAxis("Mouse ScrollWheel");
if (offset != 0)
{
offset *= _flZoomSpeed;
_fldistance -= offset;
transform.Translate(Vector3.forward * offset, Space.Self);
}
}
}