请写出unity的关于点击图标摄像头自动靠近的脚本,并写出注释
时间: 2024-05-02 12:17:46 浏览: 11
以下是一份Unity中实现点击图标摄像头自动靠近的脚本,附有注释。
```
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target; // 目标物体的Transform组件
public float smoothSpeed = 0.125f; // 摄像机移动的平滑速度
public Vector3 offset; // 摄像机距离目标物体的偏移量
private bool isZoomedIn = false; // 是否已经缩小视角的标志
void LateUpdate()
{
if (Input.GetMouseButtonDown(0)) // 当左键被点击时
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // 从鼠标位置发出一条射线
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject.CompareTag("Zoomable")) // 如果物体的标签为Zoomable
{
isZoomedIn = true; // 标记为已经缩小视角
}
else
{
isZoomedIn = false; // 标记为没有缩小视角
}
}
}
if (isZoomedIn) // 如果已经缩小视角
{
Vector3 desiredPosition = target.position + offset; // 计算摄像机应该到达的位置
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed); // 计算平滑后的移动位置
transform.position = smoothedPosition; // 更新摄像机位置
}
}
}
```
注释中解释了每个变量和函数的作用,以及代码的执行逻辑。其中,通过Raycast和物体标签的判断实现了点击特定物体缩小视角的功能,而平滑移动的效果则通过Vector3.Lerp函数实现。