Unity开发无人机游戏时如何让物体升降后悬停在固定Y轴位置
问题核心原因
- 现有代码仅在按下Q/E时修改
upForce数值,松开按键后upForce不会重置,会一直给升降方向的力,导致无人机不会停下 - 没有抵消重力的基础推力,也没有锁定目标高度的逻辑,无法实现悬停位置修正
可用修复代码
using UnityEngine; public class Levitating : MonoBehaviour { Rigidbody ourDrone; [Header("无人机参数设置")] public float hoverBaseForce = 9.81f; // 抵消重力的基础力,默认对应Mass=1的刚体 public float heightAdjustSpeed = 2f; // 按下升降键时的高度变化速度 public float hoverStrength = 5f; // 悬停位置修正力度,越大修正越快 private float targetHeight; // 存储需要悬停的目标Y轴高度 private void Awake() { ourDrone = GetComponent<Rigidbody>(); // 初始化目标高度为无人机出生时的Y轴位置 targetHeight = transform.position.y; } private void FixedUpdate() { MovementUpDown(); // 计算当前高度和目标高度的差值,生成修正力 float heightGap = targetHeight - transform.position.y; float finalUpForce = hoverBaseForce + heightGap * hoverStrength; // 限制推力范围避免出现异常过大的力 finalUpForce = Mathf.Clamp(finalUpForce, 0f, 20f); ourDrone.AddRelativeForce(Vector3.up * finalUpForce); } void MovementUpDown() { if (Input.GetKey(KeyCode.E)) { // 按下上升键时抬高目标高度 targetHeight += heightAdjustSpeed * Time.fixedDeltaTime; } else if (Input.GetKey(KeyCode.Q)) { // 按下下降键时降低目标高度 targetHeight -= heightAdjustSpeed * Time.fixedDeltaTime; } } }
参数调整说明
- 若你的无人机Rigidbody组件的Mass数值不是1,将
hoverBaseForce修改为9.81 * Mass数值即可适配 hoverStrength建议在3~10的区间调整,数值过大会导致无人机上下弹跳,数值过小会导致悬停高度修正过慢heightAdjustSpeed控制手动升降的速度,可根据你的操作手感需求自由调整
内容的提问来源于stack exchange,提问作者Culling_Card2121
相关产品推荐
相关产品推荐

