1
votes

How can I add a force to a rigidbody2D game object and keep it moving at a fixed velocity? The game object also has a bounce material attached.

private Rigidbody2D rb2D;
private float thrust = 10.0f;

void Start() {
}


void FixedUpdate() {
        rb2D.AddForce(new Vector2(0, 1) * thrust);
    }

This is what i got off of the Unity documentations website but this doesn't seem to do anything.

Here is the code I ended up going with and it appears to be functioning properly. The Vector2 direction and speeds can be adjusted depending on mass/ gravity.

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;
}
1

1 Answers

1
votes

Your code as written, once it works will accelerate the rigidbody infinitely. You'll want to cap the velocity at its maximum speed: 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;

If you want it to immediately set the velocity to the fixed value, then you can just set the velocity on every frame:

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;
        }
    }
}

Your code doesn't show it so in case you aren't doing it yet, you'll want to make sure that rb2D is actually set to the Rigidbody2d on the object you want to manipulate. E.g. by doing in the start method:

void Start()
{
    rb2D = gameObject.GetComponent<Rigidbody2D>();
}