using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbitCamera : MonoBehaviour
{
public Transform TargetLookAt;
public float Distance = 10.0f;
public float DistanceMin = 5.0f;
public float DistanceMax = 15.0f;
float startingDistance = 0.0f;
float desiredDistance = 0.0f;
float mouseX = 0.0f;
float mouseY = 0.0f;
public float X_MouseSensitivity = 5.0f;
public float Y_MouseSensitivity = 5.0f;
public float MouseWheelSensitivity = 5.0f;
public float Y_MinLimit = 15.0f;
public float Y_MaxLimit = 70.0f;
public float DistanceSmooth = 0.025f;
float velocityDistance = 0.0f;
Vector3 desiredPosition = Vector3.zero;
public float X_Smooth = 0.05f;
public float Y_Smooth = 0.1f;
float velX = 0.0f;
float velY = 0.0f;
float velZ = 0.0f;
Vector3 position = Vector3.zero;
void Start()
{
Distance = Vector3.Distance(TargetLookAt.transform.position, gameObject.transform.position);
if (Distance > DistanceMax)
DistanceMax = Distance;
startingDistance = Distance;
Reset();
}
void LateUpdate()
{
if (TargetLookAt == null)
return;
HandlePlayerInput();
CalculateDesiredPosition();//计算预期位置
UpdatePosition();
}
void HandlePlayerInput()
{
float deadZone = 0.01f;
if (Input.GetMouseButton(0))
{
mouseX += Input.GetAxis("Mouse X") * X_MouseSensitivity;
mouseY -= Input.GetAxis("Mouse Y") * Y_MouseSensitivity;
}
mouseY = ClampAngle(mouseY, Y_MinLimit, Y_MaxLimit);
if (Input.GetAxis("Mouse ScrollWheel") < -deadZone || Input.GetAxis("Mouse ScrollWheel") > deadZone)
{
desiredDistance = Mathf.Clamp(Distance - (Input.GetAxis("Mouse ScrollWheel") * MouseWheelSensitivity),
DistanceMin, DistanceMax);
}
if (Input.GetMouseButton(1))
{
Reset();
}
}
void CalculateDesiredPosition()
{
Distance = Mathf.SmoothDamp(Distance, desiredDistance, ref velocityDistance, DistanceSmooth);
desiredPosition = CalculatePosition(mouseY, mouseX, Distance);
}
Vector3 CalculatePosition(float rotationX, float rotationY, float distance)
{
Vector3 direction = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(rotationX, rotationY + 178, 0);
return TargetLookAt.position + (rotation * direction);
}
void UpdatePosition()
{
float posX = Mathf.SmoothDamp(position.x, desiredPosition.x, ref velX, X_Smooth);
float posY = Mathf.SmoothDamp(position.y, desiredPosition.y, ref velY, Y_Smooth);
float posZ = Mathf.SmoothDamp(position.z, desiredPosition.z, ref velZ, X_Smooth);
position = new Vector3(posX, posY, posZ);
transform.position = position;
transform.LookAt(TargetLookAt);
}
void Reset()
{
mouseX = 0;
mouseY = 0;
Distance = startingDistance;
desiredDistance = Distance;
}
float ClampAngle(float angle, float min, float max)
{
while (angle < -360.0f || angle > 360.0f)
{
if (angle < -360.0f)
angle += 360.0f;
if (angle > 360.0f)
angle -= 360.0f;
}
return Mathf.Clamp(angle, min, max);
}
}
摄像机小功能的实现
最新推荐文章于 2021-07-13 10:41:00 发布