Creating a Simple Platformer Game with Unity (C#)

Learn how to make a classic 2D platformer with Unity and C#, including player movement, jumping, and collisions.

Full Blog:

Platformers like Mario are timeless. With Unity, creating one isn’t as hard as it looks.

Step 1: Set Up the Scene

  • Create a 2D project.
  • Add a Player sprite and Ground tile.
  • Add Rigidbody2D and BoxCollider2D to both.

Step 2: Player Movement Script

Create PlayerMovement.cs:

using UnityEngine;

public class PlayerMovement : MonoBehaviour {
    public float speed = 5f;
    public float jumpForce = 7f;
    private Rigidbody2D rb;
    private bool isGrounded;

    void Start() {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update() {
        float move = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(move * speed, rb.velocity.y);

        if (Input.GetButtonDown("Jump") && isGrounded) {
            rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
        }
    }

    void OnCollisionEnter2D(Collision2D collision) {
        if (collision.gameObject.CompareTag("Ground")) {
            isGrounded = true;
        }
    }

    void OnCollisionExit2D(Collision2D collision) {
        if (collision.gameObject.CompareTag("Ground")) {
            isGrounded = false;
        }
    }
}

Step 3: Adding Obstacles and Goals

  • Add enemies as prefabs with colliders.
  • Detect collision to reduce health or restart level.
  • Add a coin or goal object for level completion.

Step 4: Polish the Game

  • Add background music
  • Include animations with Animator Controller
  • Add UI for score and lives.

Key Takeaways:

  • Unity simplifies physics and collisions.
  • Platformers rely heavily on movement, collision, and timing.
  • You can easily extend this to a full game.