目录
移动脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
// 公共变量,可以在Unity编辑器中设置角色的移动速度
public float moveSpeed = 5f;
// Start方法在脚本启用时调用一次
void Start()
{
}
// Update方法在每一帧调用
void Update()
{
// 获取水平轴(左右方向)的输入值,使用键盘的箭头键或A/D键
float horizontalInput = Input.GetAxis("Horizontal");
// 获取垂直轴(前后方向)的输入值,使用键盘的箭头键或W/S键
float verticalInput = Input.GetAxis("Vertical");
// 根据输入值创建一个新的方向向量,并将其归一化
Vector3 moveDirection = new Vector3(horizontalInput, 0, verticalInput).normalized;
// 计算移动量:方向向量乘以移动速度再乘以时间间隔
Vector3 moveAmount = moveDirection * moveSpeed * Time.deltaTime;
// 使用Translate方法将角色沿着计算好的向量移动,Space.World表示在世界坐标系中移动
transform.Translate(moveAmount, Space.World);
}
}
镜头跟随脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class follow : MonoBehaviour
{
public Transform target; // 目标对象,即摄像机要跟随的对象
public Vector3 offset; // 摄像机与目标对象之间的偏移量
public float smoothSpeed = 0.125f; // 用于平滑摄像机移动的速度
void LateUpdate()
{
Vector3 desiredPosition = target.position + offset; // 计算摄像机的目标位置
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed); // 使用 Lerp 函数平滑摄像机移动
transform.position = smoothedPosition; // 更新摄像机的位置
// 可选:让摄像机始终朝向目标对象
// transform.LookAt(target);
}
}