using UnityEngine;
using System.Collections;
namespace Com.MyCompany.MyGame
{
public class CameraWork : MonoBehaviour
{
[Tooltip("在本地 X-Z 平面到目标的距离")]
public float distance = 7.0f;
[Tooltip("我们希望相机高于目标的高度")]
public float height = 3.0f;
[Tooltip("相机高度的平滑时间滞后.")]
public float heightSmoothLag = 0.3f;
[Tooltip("让相机可以从目标抵消垂直,例如提供更多的视野且更少的地面。")]
public Vector3 centerOffset = Vector3.zero;
[Tooltip("如果预设的组件正在被 Photon Networ 实例化把这个属性设置为false,并在需要的时候手动调用 OnStartFollowing()")]
public bool followOnStart = false;
Transform cameraTransform;
bool isFollowing;
private float heightVelocity = 0.0f;
private float targetHeight = 100000.0f;
void Start()
{
if (followOnStart)
{
OnStartFollowing();
}
}
void LateUpdate()
{
if (cameraTransform == null && isFollowing)
{
OnStartFollowing();
}
if (isFollowing)
{
Apply();
}
}
public void OnStartFollowing()
{
cameraTransform = Camera.main.transform;
isFollowing = true;
Cut();
}
void Apply()
{
Vector3 targetCenter = transform.position + centerOffset;
float originalTargetAngle = transform.eulerAngles.y;
float currentAngle = cameraTransform.eulerAngles.y;
float targetAngle = originalTargetAngle;
currentAngle = targetAngle;
targetHeight = targetCenter.y + height;
float currentHeight = cameraTransform.position.y;
currentHeight = Mathf.SmoothDamp(currentHeight, targetHeight, ref
heightVelocity, heightSmoothLag);
Quaternion currentRotation = Quaternion.Euler(0, currentAngle, 0);
cameraTransform.position = targetCenter;
cameraTransform.position += currentRotation * Vector3.back * distance;
cameraTransform.position = new Vector3(cameraTransform.position.x, currentHeight, cameraTransform.position.z);
SetUpRotation(targetCenter);
}
void Cut()
{
float oldHeightSmooth = heightSmoothLag;
heightSmoothLag = 0.001f;
Apply();
heightSmoothLag = oldHeightSmooth;
}
void SetUpRotation(Vector3 centerPos)
{
Vector3 cameraPos = cameraTransform.position;
Vector3 offsetToCenter = centerPos - cameraPos;
Quaternion yRotation = Quaternion.LookRotation(new
Vector3(offsetToCenter.x, 0, offsetToCenter.z));
Vector3 relativeOffset = Vector3.forward * distance + Vector3.down * height;
cameraTransform.rotation = yRotation * Quaternion.LookRotation(relativeOffset);
}
}
}
