Skip to content Skip to sidebar Skip to footer

Widget Atas Posting

Unity Basics: Create a Flappy Bird Clone from Scratch

Unity Basics: Create a Flappy Bird Clone from Scratch

Creating a Flappy Bird clone is a great way to dive into game development using Unity

Order Now

In this tutorial, we'll walk through the basics of setting up a simple Flappy Bird game, focusing on the key concepts such as Unity’s 2D system, physics, scripting, and UI elements. By the end of this guide, you'll have a basic but functional Flappy Bird clone that you can expand upon and refine.

1. Setting Up the Unity Project

First, ensure you have Unity installed on your machine. Open Unity Hub, click on "New Project," select the 2D template, and name your project “Flappy Bird Clone.” This sets up a project with a 2D perspective, which is ideal for our game.

2. Importing Assets

Before we start coding, we need to prepare our game assets. You can create your own or download free assets from sources like the Unity Asset Store. For simplicity, we'll need:

  • A background image
  • A sprite for the bird
  • A sprite for the pipes
  • A ground image

Once you have your assets, drag them into the Assets folder in Unity.

3. Setting Up the Game Scene

a. Background and Ground

Drag your background image into the Scene view. Adjust the size and position to cover the entire camera view. Next, drag the ground image into the scene. Position it at the bottom of the camera view, ensuring it spans the screen width.

b. Bird

Drag the bird sprite into the Scene view. Center it horizontally and position it slightly above the ground. This will be the player’s character. Add a Rigidbody2D component to the bird by selecting the bird GameObject, clicking on "Add Component," and choosing Rigidbody2D. This component allows us to apply physics to the bird. Set the gravity scale to 1 to ensure the bird falls naturally when not flapping. Then, add a BoxCollider2D component to give the bird collision detection.

4. Creating the Pipe Prefab

The pipes are the obstacles the bird must avoid. To create them, drag the pipe sprite into the Scene view. You’ll need two pipes per obstacle, one facing upwards and one downwards. To achieve this:

  • Create an empty GameObject called "PipePair."
  • Drag the pipe sprite into the "PipePair" GameObject twice.
  • Rename one pipe to "PipeTop" and the other to "PipeBottom."
  • Rotate the "PipeBottom" by 180 degrees.

Now, position the pipes so there’s a gap between them that the bird can pass through. Once positioned, drag the "PipePair" GameObject into the Assets folder to create a prefab. This prefab can be reused to spawn multiple pipes during the game.

5. Writing the Bird Script

Now, we need to script the bird's movement and controls. Create a new C# script called Bird and attach it to the bird GameObject. Open the script and add the following code:

csharp
using UnityEngine; public class Bird : MonoBehaviour { public float flapStrength = 5f; private Rigidbody2D rb; void Start() { rb = GetComponent<Rigidbody2D>(); } void Update() { if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)) { rb.velocity = Vector2.up * flapStrength; } } private void OnCollisionEnter2D(Collision2D collision) { // Restart the game on collision UnityEngine.SceneManagement.SceneManager.LoadScene(0); } }

This script does a few things:

  • It adds an upward force to the bird when the player clicks the mouse or presses the space bar.
  • It restarts the game when the bird collides with an obstacle.

6. Spawning Pipes

Next, we need to spawn pipes at regular intervals to create the obstacles. Create a new C# script called PipeSpawner. Attach it to an empty GameObject named "GameController." Here’s the code for the PipeSpawner:

csharp
using UnityEngine; public class PipeSpawner : MonoBehaviour { public GameObject pipePrefab; public float spawnRate = 2f; public float heightOffset = 1f; private float timer = 0f; void Start() { SpawnPipe(); } void Update() { timer += Time.deltaTime; if (timer >= spawnRate) { SpawnPipe(); timer = 0f; } } void SpawnPipe() { float lowestPoint = transform.position.y - heightOffset; float highestPoint = transform.position.y + heightOffset; Instantiate(pipePrefab, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation); } }

This script spawns a pipe pair at regular intervals:

  • spawnRate controls how often pipes appear.
  • heightOffset randomizes the vertical position of the pipes.

7. Moving the Pipes

To create the illusion of the bird moving forward, we'll make the pipes move left. Create a new C# script called PipeMovement and attach it to the PipePair prefab. Here’s the code:

csharp
using UnityEngine; public class PipeMovement : MonoBehaviour { public float speed = 5f; void Update() { transform.position += Vector3.left * speed * Time.deltaTime; if (transform.position.x < -10f) { Destroy(gameObject); } } }

This script moves the pipes leftward at a constant speed. Once they move off-screen, they are destroyed to free up memory.

8. Adding a Score System

To add a scoring system, create a new UI Text element. Go to GameObject > UI > Text, and rename it to "ScoreText". Position it at the top center of the screen. Then, create a new C# script called Score and attach it to the "GameController" GameObject. Here’s the code:

csharp
using UnityEngine; using UnityEngine.UI; public class Score : MonoBehaviour { public Text scoreText; private int score = 0; void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Pipe")) { score++; scoreText.text = "Score: " + score.ToString(); } } }

In this script:

  • The score increases each time the bird successfully passes through a pipe.
  • The score is displayed on the screen using the UI Text element.

To make this work, add a BoxCollider2D to the bird, set it as a trigger, and tag the pipes as "Pipe." Adjust the collider’s size so it fits within the gap of the pipes.

9. Fine-Tuning and Testing

Now that we have the core mechanics in place, test your game by clicking "Play" in Unity. Fine-tune the values for gravity, flap strength, pipe speed, and spawn rate until you’re happy with how the game feels.

10. Enhancing the Game

Once the basic clone is working, you can add enhancements:

  • Graphics: Improve the visual appeal with better sprites and animations.
  • Sound: Add sound effects for flapping, scoring, and collisions.
  • Difficulty: Increase difficulty over time by speeding up the pipes or reducing the gap between them.
  • Menus: Create start, game over, and pause menus to improve user experience.

Conclusion

Congratulations! You've built a basic Flappy Bird clone from scratch. This project covered essential Unity concepts like 2D physics, prefabs, scripting, and UI elements. With this foundation, you can further expand the game, add new features, or use what you've learned to build entirely new games. Keep experimenting and learning as you dive deeper into game development!