[英]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);
}
}
}
您应该对代码进行一些更改:) 以下是一些建议:
要在 Update 和 FixedUpdate 中分离 Inputs 和 Physics 内容,您可以在顶部引入一些私有变量,如下所示:
private bool leftPressed;
private bool rightPressed;
然后您可以在 FixedUpdate 中访问这些变量
希望我能帮上忙:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.