如何向刚体2D游戏对象添加力并使其以固定速度移动?游戏对象还附有反弹材料。
private Rigidbody2D rb2D;
private float thrust = 10.0f;
void Start() {
}
void FixedUpdate() {
rb2D.AddForce(new Vector2(0, 1) * thrust);
}
这是我从Unity文档网站上得到的,但这似乎没有做任何事情。
这是我最终使用的代码,它似乎运行正常。 Vector2方向和速度可根据质量/重力进行调整。
float topSpeed = 15;
private Rigidbody2D rb2D;
private float thrust = 0.1f;
void Start()
{
rb2D = gameObject.GetComponent<Rigidbody2D>();
rb2D.AddForce(new Vector2(0, 1) * thrust);
}
void Update()
{
if (rb2D.velocity.magnitude > topSpeed || rb2D.velocity.magnitude < topSpeed)
rb2D.velocity = rb2D.velocity.normalized * topSpeed;
}
你编写的代码,一旦工作,将无限加速刚体。你想要以最大速度限制速度:http://answers.unity.com/answers/330805/view.html
rigidbody.AddForce(new Vector2(0, 1) * thrust * Time.deltaTime);
if (rigidbody.velocity.magnitude > topSpeed)
rigidbody.velocity = rigidbody.velocity.normalized * topSpeed;
如果你想让它立即将速度设置为固定值,那么你可以在每一帧上设置速度:
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html
void FixedUpdate()
{
if (Input.GetButtonDown("Jump"))
{
// the cube is going to move upwards in 10 units per second
rb2D.velocity = new Vector3(0, 10, 0);
moving = true;
Debug.Log("jump");
}
if (moving)
{
// when the cube has moved over 1 second report it's position
t = t + Time.deltaTime;
if (t > 1.0f)
{
Debug.Log(gameObject.transform.position.y + " : " + t);
t = 0.0f;
}
}
}
你的代码没有显示它,所以如果你还没有这样做,你需要确保rb2D
实际设置为你要操作的对象上的Rigidbody2d。例如。通过在start方法中执行:
void Start()
{
rb2D = gameObject.GetComponent<Rigidbody2D>();
}