0

堆栈溢出的人。我想为我的个人学校项目制作无人机游戏。一切都很顺利,但我现在面临一个问题。当我按下所选按钮时,我的无人机脚本不会使无人机保持恒定高度。换句话说,当我按下 E 或 Q 时,无人机会持续上升或持续下降。只要我按下选定的键,我就希望它上升。我该怎么做?

代码->

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Levitating : MonoBehaviour
{
    Rigidbody ourDrone;

private void Awake()
{
    ourDrone = GetComponent<Rigidbody>();
}

// Make the drone default velocity the same value of the gravity acceleration, with opposite direction
private Vector3 DRONE_DEFAULT_VELOCITY = new Vector3(0, 9.81f, 0);

public float upForce;

private void Update()
{
    MovementUpDown();
}

private void FixedUpdate()
{
    ourDrone.AddRelativeForce(DRONE_DEFAULT_VELOCITY * upForce);
}

void MovementUpDown()
{
    if (Input.GetKey(KeyCode.E))
    {
        upForce = 15;
    }
    else if (Input.GetKey(KeyCode.Q))
    {
        upForce = -3;
    }
    else
    {
        // Resetting the force muultiplier
        upForce = 1;
    }
}
}
4

1 回答 1

0

问题是你的物理是错误的。在默认模式下(upForce = 1),您将抵消重力,因此不会对您的 rb 应用加速度。但是,当您按下一个控制按钮时,您正在添加一个力,因此,根据牛顿定律,您正在添加一个加速度,这将导致即使在您停止按下后仍会保持速度按钮。现在,我不知道您为什么要像以前那样对其进行建模,但是解决问题的最简单方法是禁用刚体上的重力并直接修改 rb 的速度。或者在您的 AddForce 中使用不同的 forceMode。https://docs.unity3d.com/ScriptReference/ForceMode.html使用速度变化。

如果你想模拟一架实际的无人机,就像在现实生活中那样,你应该研究控制系统,比如 PID,但这可能是矫枉过正。

祝你好运

于 2021-09-25T12:55:59.430 回答