介绍
unity,如何怎么让相机平滑移动
方法
ws控制前进、ad控制转向
using UnityEngine;
using System.Collections;
public class SmoothFollow : MonoBehaviour {
// 声明变量 distance、height、heightDamping、rotationDamping 和 offsetHeight
public float distance = 10.0f; // 相机与目标的距离
public float height = 5.0f; // 相机与目标的高度差
public float heightDamping = 2.0f; // 相机高度的平滑度
public float rotationDamping = 3.0f; // 相机旋转的平滑度
public float offsetHeight = 1.0f; // 摄像机偏移高度
Transform selfTransform; // 自身Transform组件
public Transform Target; // 跟随的目标对象
void Start () {
selfTransform = GetComponent<Transform>(); // 获取自身Transform组件
}
void LateUpdate () {
if (!Target)
return;
// 计算希望的旋转角度和高度
float wantedRotationAngle = Target.eulerAngles.y;
float wantedHeight = Target.position.y + height;
// 计算当前的旋转角度和高度
float currentRotationAngle = selfTransform.eulerAngles.y;
float currentHeight = selfTransform.position.y;
// 平滑地旋转到希望的角度
currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
// 平滑地高度到希望的高度
currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);
// 计算当前的旋转角度的四元数
Quaternion currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);
// 设置相机的位置
selfTransform.position = Target.position;
selfTransform.position -= currentRotation * Vector3.forward * distance;
// 设置相机的高度
Vector3 currentPosition = transform.position;
currentPosition.y = currentHeight;
selfTransform.position = currentPosition;
// 让相机朝向目标对象
selfTransform.LookAt(Target.position + new Vector3(0, offsetHeight, 0));
}
}