Preamble

In my previous post I have shown how to make the most basic movement using transform.Translate() with Unity. Now we’ll discuss about movement with RigidBody2D, which means physics. In Unity when we mean physics we should automatically think about RigidBodies.

RigidBody2D and Velocity

So we first add a RigidBody 2d to our Spaceship:

This will provide the essential backend calculations for our movement. To facilitate our movement I’m going to create a script called PhysicsMovement and add it to my Spaceship object as a component; but usually you end up with one type of movement. When I double click it, Visual Studio runs. And I write this code in our PhysicsMovement:

public class PhysicsMovement : MonoBehaviour {

      Rigidbody2D _rigid;
      // Use this for initialization
      void Start () {
          _rigid = GetComponent<Rigidbody2D>();
      }
	// Update is called once per frame
      void Update () {
         _rigid.velocity = new Vector2(_rigid.velocity.x,1);
      }
}

The first lines ending with Update function should be familiar to you as you learn Unity. Basically the first line introduces a handler for RigidBody2D as _rigid and I fill this in the Start function, when the game runs. This way I’ll have access to its methods and properties in Update.

I fill this with GetComponent<> method, because RigidBody2D is on me, speaking as the Spaceship here, I don’t need to search for any GameObject to pull component. I reach out and fill it from myself.

Then, in the Update method I set my velocity to upwards, (y is 1) and my x is the current one. So this makes me rise up in the sky.

Now let’s add some movement to this:

void Update () {
        float verticalInput = Input.GetAxis("Vertical");
        _rigid.velocity = new Vector2(_rigid.velocity.x,verticalInput);
	}

When we run this and push W and S we can see a dragging movement when we pull up our finger. This is caused by Input.GetAxis. If we want a more precise movement we can substitute it with Input.GetAxisRaw() which doesn’t smooth out the movement.

Now let’s add our left and right too:

public class PhysicsMovement : MonoBehaviour {

    Rigidbody2D _rigid;
	// Use this for initialization
	void Start () {
        _rigid = GetComponent<Rigidbody2D>();
	}
	
	// Update is called once per frame
	void Update () {
        float verticalInput = Input.GetAxisRaw("Vertical");
        float horizontalInput = Input.GetAxisRaw("Horizontal");
        _rigid.velocity = new Vector2(horizontalInput,verticalInput);
	}
}

If you didn’t touch the settings on RigidBody 2D your gravity is on, which makes us fall with the time, you can increase or decrease this from Gravity Scale (Zero being no gravity):

As you can see the end result is pretty much the same with transform.Translate() BUT with RigidBody2D we can introduce more variables and create a more realistic movement.

Categories: Unity