如何将随机方向的forceforce添加到rigidbody2d游戏对象中

问题描述 投票:1回答:1

如何向刚体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;
}
unity3d
1个回答
1
投票

你编写的代码,一旦工作,将无限加速刚体。你想要以最大速度限制速度: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>();
}
© www.soinside.com 2019 - 2024. All rights reserved.