Unity项目迁移至笔记本后火箭仅能旋转无法推进问题求助
我正在学习Unity并跟随教程开发一款火箭穿越障碍的游戏,将项目从PC迁移到笔记本电脑后,火箭仅能左右旋转却无法实现推进功能。以下是火箭移动代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Movement : MonoBehaviour { Rigidbody rb; [SerializeField] float mainThrust = 100f; [SerializeField] float rotationSpeed = 50f; void Start() { rb = GetComponent<Rigidbody>(); } void Update() { ProcessThrust(); ProcessRotation(); } void ProcessThrust() { if (Input.GetKey(KeyCode.Space)) { //Boost rb.AddRelativeForce(Vector3.up * mainThrust * Time.deltaTime); } } void ProcessRotation() { if (Input.GetKey(KeyCode.LeftArrow)) { //Rotate left ApplyRotate(rotationSpeed); } else if (Input.GetKey(KeyCode.RightArrow)) { //Rotate right ApplyRotate(-rotationSpeed); } } void ApplyRotate(float rotationPreFrame) { rb.freezeRotation = true; // freezing rotation so we can manually rotate transform.Rotate(0, 0, 1 * rotationPreFrame * Time.deltaTime); rb.freezeRotation = true; // unfreezing rotation so the physics system can take over } }
问题原因及修复方案
推力计算逻辑错误:
AddRelativeForce默认使用ForceMode.Force模式,该模式已经是按时间累积的力,不需要额外乘以Time.deltaTime。当前代码中mainThrust * Time.deltaTime会让实际推力被大幅缩小(比如100*0.02=2),导致火箭无法获得足够推力。
修复:将推力代码改为rb.AddRelativeForce(Vector3.up * mainThrust);;如果教程使用的是瞬时力模式,可改为rb.AddRelativeForce(Vector3.up * mainThrust, ForceMode.Impulse);。笔记本Space键输入异常:部分笔记本的Space键可能被Fn功能锁定、系统快捷键占用,或者存在硬件故障。可以临时修改代码中的触发按键为
KeyCode.LeftCtrl测试,或者在Unity的Input Manager中添加自定义按键绑定验证。Rigidbody参数异常:迁移项目后可能意外修改了Rigidbody设置:比如
Mass值过大(如设为1000)、Use Gravity被错误勾选(太空场景应关闭),甚至Rigidbody组件被意外移除。检查火箭对象的Rigidbody组件,确保Mass值合理(建议1-10),并根据游戏需求设置重力开关。旋转方法的隐藏bug:
ApplyRotate方法最后一行错误地将rb.freezeRotation设为true,应该改为false。虽然该问题不直接影响推进,但会导致Rigidbody一直处于旋转冻结状态,物理系统无法正常处理其他旋转相关的物理效果,需要修复。
内容的提问来源于stack exchange,提问作者flako

