Skip to content Skip to sidebar Skip to footer

Widget HTML #1

The Complete Guide to Unity 2D : Platformer Development

The Complete Guide to Unity 2D : Platformer Development

A practical guide to help you get started and gain the most value developing 2D games with Unity. Table of Contents.

Enroll Now

Creating a 2D platformer game in Unity can be an incredibly rewarding experience. Unity is a powerful game engine that offers a plethora of tools and resources to help developers bring their ideas to life. This guide will walk you through the essential steps of developing a 2D platformer, from setting up your project to adding complex mechanics and polish to your game.

Getting Started with Unity

Installing Unity

Before you start, you need to install Unity Hub, which is the management tool for Unity installations and projects. After installing Unity Hub, you can download the latest version of the Unity Editor. Make sure to select the 2D Game Kit during the installation process.

Setting Up Your Project

  1. Create a New Project: Open Unity Hub, click on the "New" button, and select the 2D template. Give your project a name and set the location where you want to save it.

  2. Configure the Project Settings: Go to Edit -> Project Settings and configure settings such as the aspect ratio for your game, the default background color, and the physics settings (like gravity) to match your game's requirements.

Basic Game Objects and Components

Creating the Player Character

  1. Design the Player Sprite: Use a tool like Photoshop, GIMP, or Aseprite to create a sprite for your player character. Import the sprite into Unity by dragging it into the Assets folder.

  2. Set Up the Player GameObject: Create a new GameObject in the scene and attach the player sprite to it. Add a SpriteRenderer component to display the sprite. Adjust the sprite's settings like the sorting layer to ensure it renders correctly in the game view.

  3. Add a Rigidbody2D Component: This component handles the physics of the player character. Set the gravity scale to an appropriate value for your platformer.

  4. Add a Collider2D Component: This defines the physical shape of the player for collisions. A common choice is the BoxCollider2D or CircleCollider2D, depending on your character's shape.

Creating the Ground and Platforms

  1. Design the Ground Sprites: Create or download ground and platform sprites. Import them into Unity and arrange them in your scene.

  2. Add Collider2D Components: Attach BoxCollider2D components to your ground and platforms to define their physical boundaries. This ensures the player can stand and walk on them.

Player Movement

Writing the Movement Script

  1. Create a New Script: In the Assets folder, right-click and select Create -> C# Script. Name it PlayerMovement.

  2. Edit the Script: Double-click to open it in your code editor. Define variables for speed, jump force, and references to the Rigidbody2D component.

csharp
using UnityEngine; public class PlayerMovement : MonoBehaviour { public float speed = 5f; public float jumpForce = 10f; 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(0f, jumpForce), ForceMode2D.Impulse); } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("Ground")) { isGrounded = true; } } private void OnCollisionExit2D(Collision2D collision) { if (collision.gameObject.CompareTag("Ground")) { isGrounded = false; } } }
  1. Attach the Script to the Player: Drag the PlayerMovement script onto the player GameObject in the Inspector.

Camera Setup

Making the Camera Follow the Player

  1. Create a CameraFollow Script: Similar to the player movement script, create a new script named CameraFollow.
csharp
using UnityEngine; public class CameraFollow : MonoBehaviour { public Transform player; public float smoothing = 5f; private Vector3 offset; void Start() { offset = transform.position - player.position; } void FixedUpdate() { Vector3 targetPosition = player.position + offset; transform.position = Vector3.Lerp(transform.position, targetPosition, smoothing * Time.deltaTime); } }
  1. Attach the Script to the Camera: Select the main camera in the scene and attach the CameraFollow script to it. Set the player GameObject as the target in the Inspector.

Level Design

Creating Levels

  1. Design Levels in a Tilemap: Unity’s Tilemap system allows for efficient creation of 2D levels. Create a Tilemap by going to GameObject -> 2D Object -> Tilemap -> Rectangular.

  2. Import and Set Up Tiles: Import your tile sprites and create a new Tile palette. Use the Tile Palette window to paint your level by dragging tiles onto the grid.

  3. Add Colliders to Tiles: Use the TilemapCollider2D component to add colliders to your Tilemap. This ensures that the player can interact with the environment.

Adding Game Mechanics

Collectibles and Scoring

  1. Create a Collectible Item: Design a sprite for your collectible item, import it, and create a new GameObject with a SpriteRenderer and Collider2D.

  2. Write a Collectible Script:

csharp
using UnityEngine; public class Collectible : MonoBehaviour { public int scoreValue = 10; void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Player")) { ScoreManager.instance.AddScore(scoreValue); Destroy(gameObject); } } }
  1. Create a Score Manager: Create a ScoreManager script to handle the player's score.
csharp
using UnityEngine; using UnityEngine.UI; public class ScoreManager : MonoBehaviour { public static ScoreManager instance; public Text scoreText; private int score = 0; void Awake() { if (instance == null) { instance = this; } else { Destroy(gameObject); } } public void AddScore(int value) { score += value; scoreText.text = "Score: " + score; } }
  1. Attach Scripts and UI Elements: Attach the ScoreManager script to a new GameObject and link the UI text element in the Inspector.

Advanced Features

Enemy AI

  1. Create an Enemy Character: Design the enemy sprite, import it, and create a GameObject with a SpriteRenderer, Rigidbody2D, and Collider2D.

  2. Write an Enemy AI Script:

csharp
using UnityEngine; public class EnemyAI : MonoBehaviour { public float speed = 2f; public Transform[] waypoints; private int currentWaypointIndex = 0; void Update() { if (waypoints.Length == 0) return; Transform target = waypoints[currentWaypointIndex]; Vector3 direction = (target.position - transform.position).normalized; transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime); if (Vector3.Distance(transform.position, target.position) < 0.1f) { currentWaypointIndex = (currentWaypointIndex + 1) % waypoints.Length; } } }
  1. Set Up Waypoints: Create empty GameObjects as waypoints and assign them to the enemy AI script in the Inspector.

Game Over and Restart

  1. Create a Game Over UI: Design a Game Over screen using Unity’s UI system. Create a canvas and add a text element and a button.

  2. Write a Game Over Script:

csharp
using UnityEngine; using UnityEngine.SceneManagement; public class GameOver : MonoBehaviour { public GameObject gameOverUI; void Update() { if (PlayerHealth.instance.currentHealth <= 0) { gameOverUI.SetActive(true); } } public void Restart() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } }
  1. Link UI Elements: Attach the script to a new GameObject and link the UI elements in the Inspector. Set the button’s OnClick event to call the Restart function.

Polishing Your Game

Adding Sound and Music

  1. Import Audio Files: Drag your audio files into the Assets folder.

  2. Create an Audio Manager: Write a script to manage background music and sound effects.

csharp
using UnityEngine; public class AudioManager : MonoBehaviour { public static AudioManager instance; public AudioSource musicSource; public AudioSource sfxSource; void Awake() { if (instance == null) { instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } public void PlaySFX(AudioClip clip) { sfxSource.PlayOneShot(clip); } }
  1. Attach Audio Sources: Attach the script to a new GameObject and link the audio sources in the Inspector.

Adding Particle Effects

  1. Create a Particle System: Go to GameObject -> Effects -> Particle System to create a new particle system.

  2. Customize the Effect: Adjust the particle system settings to fit your needs, such as changing the emission rate, lifetime, and color of the particles.

  3. Trigger Particles on Events: Use code to trigger particles, such as on player death or collectible pickup.

csharp
using UnityEngine; public class PlayerDeath : MonoBehaviour { public GameObject deathEffect; void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("Enemy")) { Instantiate(deathEffect, transform.position, Quaternion.identity); Destroy(gameObject); } } }

Conclusion

Creating a 2D platformer in Unity involves several steps, from setting up your project to polishing the final product. By following this guide, you can build a robust and enjoyable game. Remember to keep experimenting with different mechanics, art styles, and features to make your platformer unique. Happy developing!