繁体   English   中英

如何在随机方向上向刚体2d游戏对象添加力

[英]How to addforce in a random direction to a rigidbody2d game object

如何向刚体 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>();
}

暂无
暂无

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

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