111 lines
2.5 KiB
C#
111 lines
2.5 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
|
|
public class CameraController : MonoBehaviour
|
|
{
|
|
public float panSpeed = 20f;
|
|
|
|
public float panAcceleration = 2f;
|
|
|
|
public float turnSpeed = 4f;
|
|
|
|
public float verticalSpeed = 20f;
|
|
|
|
private float horizontalInput;
|
|
|
|
private float verticalInput;
|
|
|
|
private float verticalMovement;
|
|
|
|
private float mouseX;
|
|
|
|
private float mouseY;
|
|
|
|
private Vector3 initialPosition;
|
|
|
|
private Quaternion initialRotation;
|
|
|
|
private bool isReturning;
|
|
|
|
public float returnSpeed = 2f;
|
|
|
|
private void Start()
|
|
{
|
|
initialPosition = base.transform.position;
|
|
initialRotation = base.transform.rotation;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (isReturning)
|
|
{
|
|
ReturnToInitialPositionSmoothly();
|
|
}
|
|
else
|
|
{
|
|
HandleInput();
|
|
}
|
|
}
|
|
|
|
private void HandleInput()
|
|
{
|
|
horizontalInput = Input.GetAxis("Horizontal");
|
|
verticalInput = Input.GetAxis("Vertical");
|
|
mouseX = Input.GetAxis("Mouse X");
|
|
mouseY = Input.GetAxis("Mouse Y");
|
|
if (Input.GetMouseButton(1))
|
|
{
|
|
RotateCamera();
|
|
MoveCamera();
|
|
if (Input.GetKey(KeyCode.Q))
|
|
{
|
|
LowerCamera();
|
|
}
|
|
if (Input.GetKey(KeyCode.E))
|
|
{
|
|
RaiseCamera();
|
|
}
|
|
}
|
|
if (Input.GetKeyDown(KeyCode.R))
|
|
{
|
|
StartCoroutine(ReturnToInitialPositionSmoothly());
|
|
}
|
|
}
|
|
|
|
private void MoveCamera()
|
|
{
|
|
float num = (Input.GetKey(KeyCode.LeftShift) ? (panSpeed * panAcceleration) : panSpeed);
|
|
Vector3 direction = new Vector3(horizontalInput * num * Time.deltaTime, 0f, verticalInput * num * Time.deltaTime);
|
|
direction = base.transform.TransformDirection(direction);
|
|
base.transform.position += direction;
|
|
}
|
|
|
|
private void RotateCamera()
|
|
{
|
|
base.transform.rotation *= Quaternion.Euler((0f - mouseY) * turnSpeed, mouseX * turnSpeed, 0f);
|
|
base.transform.eulerAngles = new Vector3(base.transform.eulerAngles.x, base.transform.eulerAngles.y, 0f);
|
|
}
|
|
|
|
private void LowerCamera()
|
|
{
|
|
base.transform.position -= new Vector3(0f, verticalSpeed * Time.deltaTime, 0f);
|
|
}
|
|
|
|
private void RaiseCamera()
|
|
{
|
|
base.transform.position += new Vector3(0f, verticalSpeed * Time.deltaTime, 0f);
|
|
}
|
|
|
|
private IEnumerator ReturnToInitialPositionSmoothly()
|
|
{
|
|
isReturning = true;
|
|
while (Vector3.Distance(base.transform.position, initialPosition) > 0.01f || Quaternion.Angle(base.transform.rotation, initialRotation) > 0.01f)
|
|
{
|
|
base.transform.position = Vector3.Lerp(base.transform.position, initialPosition, returnSpeed * Time.deltaTime);
|
|
base.transform.rotation = Quaternion.Slerp(base.transform.rotation, initialRotation, returnSpeed * Time.deltaTime);
|
|
yield return null;
|
|
}
|
|
isReturning = false;
|
|
}
|
|
}
|