繁体   English   中英

无法在 Unity3D 中向我的 object 添加Force

[英]Unable to addForce to my object in Unity3D

我已经完成了这段代码,但 object 没有前进。 你能帮我解决这个问题吗?

我正在使用统一版本 2019.4.3f1


public class Movements : MonoBehaviour
{
    // A reference to Rigidbody component called "rb"
    public Rigidbody rb;
    public float forwardForce = 10f;
    public float sidewaysForce = 5f;
    
    // Update is called once per frame
    
    void FixedUpdate()
    {
        rb.AddForce(0f , 0f, forwardForce * Time.deltaTime); //Higher the frame rate --> lower the value of force | Time.deltaTime = amount of time since the computer drew last frame
    
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            Debug.Log("Left");
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0f, 0f, ForceMode.VelocityChange);
        }
        else if (Input.GetKey(KeyCode.RightArrow))
        {
            Debug.Log("Right");
            rb.AddForce(sidewaysForce * Time.deltaTime, 0f, 0f, ForceMode.VelocityChange);
        }
    }
}

将您的代码更改为:

public class Movements : MonoBehaviour
    {
        // A reference to Rigidbody component called "rb"
        public Rigidbody rb;
        public float forwardForce = 10f;
        public float sidewaysForce = 5f;
    
        // Update is called once per frame
    
        void FixedUpdate()
        {
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                Debug.Log("Left");
                rb.AddForce(-sidewaysForce * Time.deltaTime, 0f, 0f, ForceMode.Impulse);
            }
            else if (Input.GetKey(KeyCode.RightArrow))
            {
                Debug.Log("Right");
                rb.AddForce(sidewaysForce * Time.deltaTime, 0f, 0f, ForceMode.Impulse);
            }
        }
    }

您应该对代码进行一些更改:) 以下是一些建议:

  • 首先,FixedUpdate() 用于物理内容 (=rb.AddForce) 但您应该在 Update 中获取输入。
  • 在 FixedUpdate 中,您不需要 Time.deltaTime,因为它已经被称为每秒固定的次数。
  • 如果你使用 rb.AddForce 它会在每次调用时添加越来越多的 Force,所以你的 Rigidbody 会越来越快。 如果您不想要这个,请尝试通过直接更改 rb.velocity 来移动刚体或使用 rb.MovePosition 来移动它(我更喜欢直接更改 rb.velocity)。

要在 Update 和 FixedUpdate 中分离 Inputs 和 Physics 内容,您可以在顶部引入一些私有变量,如下所示:

private bool leftPressed;
private bool rightPressed;

然后您可以在 FixedUpdate 中访问这些变量

希望我能帮上忙:D

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM