Building a Simple 2D Game in Unity

Unity is a powerful game engine that makes creating 2D games accessible to beginners. In this tutorial, we'll walk through the process of building a simple 2D game from scratch, covering project setup, player movement, collectibles, and game rules.

Setting up a 2D Project in Unity

Let's start by creating our project:

  1. Open Unity Hub and click "New Project"
  2. Select the "2D" template
  3. Name your project (e.g., "Simple2DGame") and choose a location
  4. Click "Create Project"

Once your project loads, set up your initial scene:

1. Right-click in Hierarchy → Create Empty (name it "GameManager")
2. Right-click → 2D Object → Sprite (name it "Player")
3. Right-click → Create → Folder (name it "Scripts")

Don't forget to save your scene (Ctrl+S or File → Save) as "MainScene".

Player Movement and Camera Follow

Let's make our player character move and have the camera follow it.

Player Movement Script

Create a new C# script in your Scripts folder named "PlayerController" and attach it to your Player object:

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f;
    private Rigidbody2D rb;

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

    void Update()
    {
        float moveX = Input.GetAxis("Horizontal");
        float moveY = Input.GetAxis("Vertical");
        
        Vector2 movement = new Vector2(moveX, moveY);
        rb.velocity = movement * moveSpeed;
    }
}

Camera Follow Script

Create another script called "CameraFollow" and attach it to your Main Camera:

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform target;
    public float smoothSpeed = 0.125f;
    public Vector3 offset;

    void LateUpdate()
    {
        Vector3 desiredPosition = target.position + offset;
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
        transform.position = smoothedPosition;
    }
}

Don't forget to assign your Player object to the Target field in the CameraFollow component.

Collectibles and Score System

Now let's add collectible items and track the player's score.

Creating Collectibles

  1. Create a new Sprite object (name it "Collectible")
  2. Add a Circle Collider 2D with "Is Trigger" checked
  3. Create a script called "Collectible"
using UnityEngine;

public class Collectible : MonoBehaviour
{
    public int scoreValue = 10;
    
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            GameManager.instance.AddScore(scoreValue);
            Destroy(gameObject);
        }
    }
}

Score System in GameManager

Create a GameManager script:

using UnityEngine;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    public static GameManager 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;
    }
}

Create a UI Text element (Right-click in Hierarchy → UI → Text) and assign it to the scoreText field in GameManager.

Winning and Losing Conditions

Every game needs rules! Let's implement simple win/lose conditions.

Losing Condition (Player Health)

Modify your PlayerController to include health:

public class PlayerController : MonoBehaviour
{
    // ... existing code ...
    public int maxHealth = 100;
    private int currentHealth;
    
    void Start()
    {
        // ... existing code ...
        currentHealth = maxHealth;
    }
    
    public void TakeDamage(int damage)
    {
        currentHealth -= damage;
        
        if (currentHealth <= 0)
        {
            GameManager.instance.GameOver();
        }
    }
}

Winning Condition (Score Threshold)

Add to your GameManager:

public int winScore = 100;
public GameObject winPanel;
public GameObject losePanel;

public void AddScore(int value)
{
    score += value;
    scoreText.text = "Score: " + score;
    
    if (score >= winScore)
    {
        WinGame();
    }
}

public void WinGame()
{
    winPanel.SetActive(true);
    Time.timeScale = 0f; // Pause game
}

public void GameOver()
{
    losePanel.SetActive(true);
    Time.timeScale = 0f; // Pause game
}

Create two UI Panels (Right-click in Hierarchy → UI → Panel) named "WinPanel" and "LosePanel" with appropriate text, and assign them in the GameManager.

Next Steps

Congratulations! You now have a basic 2D game framework in Unity. From here you could:

  • Add animations to your player character
  • Create more complex level designs
  • Implement different types of collectibles
  • Add sound effects and music

Remember that game development is an iterative process - start simple and gradually add complexity as you become more comfortable with Unity's systems.

Post a Comment

0 Comments