Moving the character to the new position

The last step for our PlayerController is to move the character to the new position that we calculated in the last section.
We could do this by changing the transform of the character, but since we are using the physics engine of Unity, and we don’t want to force the character to go against a wall ignoring the collisions, we need to find another way.
Thankfully, the Rigidbody that we created a couple of sections ago, has a built-in function to move the Rigidbody into a new position and respect the collisions. Exactly what we need! The function is called MovePosition() and we can use it as shown here:

void FixedUpdate () {
//Get the new position of our character
var x = transform.position.x + Input.GetAxis("Horizontal") * Time.deltaTime * speed;
var y = transform.position.y + Input.GetAxis("Vertical") * Time.deltaTime * speed;

//Set the position of our character throught the RigidBody2D component (since we are using
physics)
rigidBody.MovePosition(new Vector2(x, y));
}

And with this, you can save the PlayerController script, and we have finished with it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset