
To move the character, you have to apply force to them by either changing the gameobject's velocity or by applying force to them.
After getting the component from Awake(), you can manipulate it in the FixedUpdate() to move it.
Rigidbody2D rigid;
float h;
public float walkSpeed;
private void Awake()
{
rigid = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
h = Input.GetAxisRaw("Horizontal");
rigid.velocity = new Vector2(h * walkSpeed, rigid.velocity.y);
}
In the FixedUpdate, we need a variable to store our Input.GetAxisRaw code.
Input.GetAxisRawgets the value of virtue axis. For this case, -1 or 1 for x-axis.
Input.GetAxisRaw, we declare h as our float value before Awake() and set h = Input.GetAxisRaw("Horizontal")
"Horizontal"is unity's built in system which captures the gameObjects horizontal movements. By default it is set toleft arrow&right arrowanda&dkeys on the keyboard.- This can be found on Edit -> Project Settings -> Input Management.


Rigidbody2D rigid;
float h;
public float walkSpeed;
private void Awake()
{
rigid = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
h = Input.GetAxisRaw("Horizontal");
rigid.velocity = new Vector2(h * walkSpeed, rigid.velocity.y);
}
}
rigid.velocity = new Vector2(h * walkSpeed, rigid.velocity.y);
We are going to tap in to our rigidbody 2D's velocity so write rigid.velocity
Since we want to specify our Vector2, we will use new Vector2
new Vector2is used when we need to create a new Vector2 with specific x and y components.
For our x-axis value, we will use h value which is -1 or 1, since we want to move from left to right.
For our y-axis value, we don't want to move vertically when we move horizontally. Therefore, we will leave it as it is. This can be done by rigid.velocity.y.
rigid.velocity = new Vector2(h, rigid.velocity.y);
Our gameObject can move with this code, but it will only move at -1 or 1 speed becuase of our h value which is our Input.GetAxisRaw("Horizontal") value.
We can solve this problem by making another variable called public float walkSpeed; before Awake().
- By making
public float walkSpeed;public, we can access it from the gameObject's script section from the inspector window.

walkSpeed to our h value to make it go faster.rigid.velocity = new Vector2(h * walkSpeed, rigid.velocity.y);
Make sure to save the script before playing the scene!

- This can be fixed by freezing the gameObject's z-axis in constraints for Rigidbody 2D component.
Apply force to the gameObject to move.