unity-移动脚本和镜头跟随脚本

目录

移动脚本

镜头跟随脚本


移动脚本

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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值