Moving the player in a 2D game with Unity and C# code

This video explains how to move your player in a 2D game in Unity with C# code. After watching this video, you will be able to move your player left and right in a scene using keyboard input.

Watch the video below and scroll down to see the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
  }
  
  // Update is called once per frame
  void Update () {
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }
  }
}

Next tutorial: Making the player jump with C# code