using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class MyDungeonCamera : MonoBehaviour {
public GameObject target = null;
public float rotateX = 0f;
public float rotateY = 0f;
public float distance = 10.0f;
public float moveSmoothTime = 0.3f;
public float rotateSmoothTime = 0.3f;
public float scrollWheelSpeed = 1000.0f;
public Vector3 targetOffset = Vector3.zero;
private Vector3 velocity = Vector3.zero;
private Vector3 offset = Vector3.zero;
private const float minDistance = 5.0f;
private const float maxDistance = 100.0f;
private Quaternion tempRotation = Quaternion.identity;
private Vector3 tempPosition = Vector3.zero;
private float speedX = 120;
private float speedY = 240;
private float RotateDamping
{
get
{
if (rotateSmoothTime <= 0f) rotateSmoothTime = 0.001f;
return 1f / rotateSmoothTime;
}
}
void LateUpdate()
{
if (Input.GetMouseButton(0))
rotateX += Input.GetAxis("Mouse X") * speedX * Time.deltaTime;
if (Input.GetMouseButton(1))
rotateY -= Input.GetAxis("Mouse Y") * speedY * Time.deltaTime;
if (target == null) return;
tempRotation = transform.rotation;
tempPosition = transform.position;
CalculateDistance();
CalculateRotation();
CalculatePosition();
transform.rotation = tempRotation;
transform.position = tempPosition;
}
private void CalculateRotation()
{
if (!IsNeedRotate()) return;
Quaternion wantedRotation = Quaternion.Euler(rotateY, rotateX, 0f);
tempRotation = Quaternion.Slerp(tempRotation, wantedRotation, Time.deltaTime * RotateDamping);
}
private void CalculatePosition()
{
if (!IsNeedRotate())
{
offset = Quaternion.Euler(rotateX, rotateY, 0f) * Vector3.forward * distance;
Vector3 wantedPos = target.transform.position - offset + targetOffset;
tempPosition = Vector3.SmoothDamp(tempPosition, wantedPos, ref velocity, moveSmoothTime);
}
else
{
offset = tempRotation * Vector3.forward * distance;
tempPosition = target.transform.position - offset + targetOffset;
}
}
private void CalculateDistance()
{
float horizontal = Input.GetAxis("Mouse ScrollWheel") * scrollWheelSpeed * Time.deltaTime;
distance -= horizontal;
distance = Mathf.Clamp(distance, minDistance, maxDistance);
}
private bool IsNeedRotate()
{
Vector3 eulerAngles = transform.rotation.eulerAngles;
return !(FloatEqual(eulerAngles.x, rotateX) && FloatEqual(eulerAngles.y, rotateY));
}
public static bool FloatEqual(float value1, float value2)
{
float ret = value1 - value2;
return ret > -0.0005f && ret < 0.0005f;
}
}
可以控制的第三人称摄像机
最新推荐文章于 2024-08-18 07:30:00 发布