Unity中如何实现玩家朝向Cinemachine Free Look相机指向方向移动
适配Cinemachine相机朝向的移动脚本修改方案
以下是修复后的完整可运行代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CapsuleMovement : MonoBehaviour { public float speed = 10f; public float jumpForce = 5f; public Rigidbody rb; public bool BeanOnTheGround = true; // 可直接将场景中的主相机拖入该字段,不赋值会自动取当前主相机 public Camera mainCam; private void Start() { // 修复原代码小写start的问题,Unity生命周期函数首字母必须大写 if (rb == null) rb = GetComponent<Rigidbody>(); if (mainCam == null) mainCam = Camera.main; } // 物理相关操作放在FixedUpdate中运行更稳定 private void FixedUpdate() { float horizontalInput = Input.GetAxis("Horizontal"); float verticalInput = Input.GetAxis("Vertical"); // 提取相机水平方向朝向,消除俯仰角度对移动方向的影响 Vector3 camForward = mainCam.transform.forward; Vector3 camRight = mainCam.transform.right; camForward.y = 0; camRight.y = 0; camForward.Normalize(); camRight.Normalize(); // 计算基于相机朝向的世界空间移动方向 Vector3 moveDir = (camForward * verticalInput + camRight * horizontalInput).normalized; // 用Rigidbody移动避免物理冲突,比transform.Translate更稳定 if (moveDir.magnitude > 0.1f) { rb.MovePosition(rb.position + moveDir * speed * Time.fixedDeltaTime); // 可选功能:取消下方注释即可让玩家自动面朝移动方向 // transform.forward = moveDir; } if(Input.GetButtonDown("Jump") && BeanOnTheGround) { rb.AddForce(new Vector3(0, jumpForce, 0), ForceMode.Impulse); BeanOnTheGround = false; } } private void OnCollisionEnter(Collision collision) { if(collision.gameObject.CompareTag("Ground")) { BeanOnTheGround = true; } } }
核心修改说明
- 修复了原代码
start方法小写的错误,Unity生命周期函数Start首字母必须大写,否则不会自动调用,会导致Rigidbody无法自动获取的问题 - 新增相机朝向计算逻辑,提取相机的水平朝向(消除Y轴俯仰的影响),将输入的前后左右和相机方向绑定,实现移动方向随相机转动动态调整
- 将物理移动逻辑移到
FixedUpdate中执行,同时用Rigidbody.MovePosition替换原有的transform.Translate,避免出现穿模、物理卡顿的问题 - 把跳跃力度改成可配置的公共变量,方便后续调整参数
- 替换了标签判断方法为
CompareTag,比直接字符串比对性能更好
内容的提问来源于stack exchange,提问作者Mercury
相关产品推荐
相关产品推荐

