unity smoothfollow

2015年02月01日 09:33 0 点赞 0 评论 更新于 2025-11-21 15:52

今天给大家介绍关于 Unity SmoothFollow 的相关内容,下面会放出详细的代码供大家参考学习。

代码实现

// The target we are following
var target : Transform;

// The distance in the x-z plane to the target
var distance = 5.0;

// The height we want the camera to be above the target
var height = 5.0;

// Damping values
var heightDamping = 2.0;
var rotationDamping = 3.0;

// Place the script in the Camera - Control group in the component menu
@script AddComponentMenu("Camera-Control/Smooth Follow")

function LateUpdate () {
// Early out if we don't have a target
if (!target)
return;

// Calculate the current rotation angles
var wantedRotationAngle = target.eulerAngles.y;
var wantedHeight = target.position.y + height - 0.1;
var currentRotationAngle = transform.eulerAngles.y;
var currentHeight = transform.position.y;

// Damp the rotation around the y - axis
currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

// Damp the height
currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

// Convert the angle into a rotation
var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

// Set the position of the camera on the x - z plane to:
// distance meters behind the target
transform.position = target.position;
transform.position -= currentRotation * Vector3.forward * distance;

// Set the height of the camera
transform.position.y = currentHeight;

// Always look at the target
transform.LookAt(target);
}

代码解释

  1. 变量声明

    • target:指定相机要跟随的目标对象的 Transform 组件。
    • distance:相机在 x - z 平面上与目标的距离。
    • height:相机相对于目标的高度。
    • heightDampingrotationDamping:分别用于控制相机高度和旋转的阻尼效果,值越大,相机跟随的速度越快。
  2. 脚本菜单设置

    • @script AddComponentMenu("Camera-Control/Smooth Follow"):将该脚本添加到 Unity 组件菜单的 Camera - Control 组中,方便用户在 Unity 编辑器中使用。
  3. LateUpdate 函数

    • 该函数在每帧的最后执行,确保相机在目标对象移动之后再进行跟随操作。
    • 目标检查:如果没有指定目标对象,函数直接返回,不进行后续操作。
    • 计算旋转和高度:计算相机期望的旋转角度 wantedRotationAngle 和高度 wantedHeight,以及当前的旋转角度 currentRotationAngle 和高度 currentHeight
    • 阻尼处理:使用 Mathf.LerpAngleMathf.Lerp 函数对旋转和高度进行阻尼处理,使相机的移动更加平滑。
    • 设置相机位置:先将相机位置设置为目标对象的位置,然后根据计算得到的旋转和距离,将相机向后移动一定距离。最后设置相机的高度。
    • 相机朝向:使用 transform.LookAt(target) 函数使相机始终朝向目标对象。

通过上述代码和解释,你可以在 Unity 中实现一个平滑跟随目标对象的相机效果。