[Solved] rigidbody.velocity += tweak not working in Unity 5

I know I shouldn’t be using Unity 5.5.0f3 however I have gone this far and it is too difficult to start over! :slight_smile:

Expected Behavior:

Random movement with the addition of tweak on velocity

Steps to Reproduce:

I have written what Ben has written -

void OnCollisionEnter2D(Collision2D collision)
{
    Vector2 tweak = new Vector2(Random.Range(0f, 0.2f), Random.Range(0f, 0.2f));
    if (hasStarted)
    {
        GetComponent<AudioSource>().Play();
        rigidbody2D.velocity += tweak;
    }
}

rigidbody2D.velocity += tweak; <-- no longer works in Unity 5. I get the error Component rigid2Dbody has been deprecated. Generally when I run into these issues someone has already addressed this issue however I don’t see this issue addressed exactly.

Things I have tried:

  1. (as suggested by editor) Changed rigidbody2D.velocity += tweak; to…
    GetComponent().velocity = new Vector2 () + tweak;

Result - Once the ball collides with anything the ball loses all momentum and comes to a complete stop

  1. List item

Changed rigidbody2D.velocity += tweak; to…
GetComponent().velocity = new Vector2 (2f, 10f) + tweak;

Result - (same as above) Once the ball collides with anything the ball loses all momentum and comes to a complete stop

  1. Finally…

    public Rigidbody2D rb;

    void Start() {
    rb = GetComponent();
    }

    void Update() {
    rb.AddForce(transform + tweak);
    }

This just gave me errors.

Please help! Thank you!

You already have the idea there. You need to GetComponent<Rigidbody2D>().velocity += tweak;

3 Likes

Here’s mine, working in Unity 5.

1 Like

Thanks guys. @ninjachimp @AndrewD2

I think I had tried this early on but it didn’t seem to be adding much randomness to the ball’s velocity. It seemed to be affecting Ben’s ball more so this time I added a larger number to the randomness just to check it was working and it seemed to move a lot more when I increased the range on random.range. The 0.2 alters movement very slightly. I reverted the randomness back to 0.2. I just raised the randomness to verify it was working.

A couple of tips to optimize the code:

  • You don’t need anywhere the keyword this., there’re no hidden variables.
  • It’s better to declare a general class RigidBody2D variable and give the reference to the component in Start(), and then use the reference elsewhere in the class, GetComponent is a slow method so better to execute it just once if possible.
3 Likes

Privacy & Terms