Unity에서 Flappy Bird에서 영감을 받은 게임을 만드는 방법

Unity 튜토리얼에서는 플래피 버드 게임을 만드는 과정을 안내합니다. 이 고전적인 모바일 게임은 새가 펄럭거리고 장애물을 피하도록 탭하여 일련의 파이프를 통해 새를 안내하는 작업을 포함합니다. 단계별 지침을 살펴보겠습니다.

1단계: Unity 프로젝트 설정

  • 아직 작성하지 않았다면 Unity을 열고 새 2D 프로젝트를 만듭니다.
  • 해상도 및 플랫폼 타겟팅을 포함한 프로젝트 설정을 구성합니다.

2단계: 게임 자산 가져오기

  • 새, 파이프 및 배경에 대한 자산을 찾거나 만듭니다.
  • 이러한 자산을 Unity 프로젝트로 가져옵니다.

3단계: 플래피 버드 만들기

  • 새에 대한 2D 스프라이트를 추가합니다.
  • 새가 펄럭이는 모습을 만들기 위해 간단한 탭 컨트롤을 구현하세요.
  • 새가 자연스럽게 떨어지도록 중력을 적용합니다.

4단계: 파이프 설계

  • 2D 스프라이트를 사용하여 파이프 prefab를 만듭니다.
  • 일정한 간격으로 파이프를 생성하도록 스폰 시스템을 설정합니다.

5단계: 게임 로직 구현

  • 파이프를 성공적으로 통과하기 위한 점수 시스템을 추가합니다.
  • 새가 파이프나 땅에 닿으면 게임이 종료되도록 충돌 감지를 구현합니다.

아래 스크립트를 확인하면 파트 3, 4, 5가 캡슐화되어 있습니다.

'FlappyBird.cs'

using UnityEngine;
using System.Collections.Generic;

public class FlappyBird : MonoBehaviour
{
    public float jumpForce = 5f;
    public Transform pipeSpawnPoint;
    public GameObject pipePrefab;
    public float pipeSpawnInterval = 2f;
    public float pipeSpeed = 2f;

    private Rigidbody2D rb;
    private Transform mainCameraTransform;

    private List<GameObject> pipes = new List<GameObject>();

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        mainCameraTransform = Camera.main.transform;

        // Start spawning pipes
        InvokeRepeating("SpawnPipe", 2f, pipeSpawnInterval);
    }

    void Update()
    {
        // Flap when the screen is tapped or clicked
        if (Input.GetMouseButtonDown(0))
        {
            Flap();
        }

        // Move towards the pipes
        transform.Translate(Vector3.right * pipeSpeed * Time.deltaTime);

        // Move and manage spawned pipes
        foreach (GameObject pipe in pipes)
        {
            if (pipe != null)
            {
                pipe.transform.Translate(Vector3.left * pipeSpeed * Time.deltaTime);

                // End the game when colliding with pipes or ground
                if (pipe.CompareTag("Pipe") && IsCollidingWithPipe(pipe))
                {
                    EndGame();
                    return; // Exit the loop and update immediately
                }

                if (pipe.CompareTag("Ground") && IsCollidingWithGround(pipe))
                {
                    EndGame();
                    return; // Exit the loop and update immediately
                }

                // Remove pipes that are out of camera view
                if (pipe.transform.position.x < mainCameraTransform.position.x - 10f)
                {
                    Destroy(pipe);
                    pipes.Remove(pipe);
                    break; // Exit the loop to avoid modifying a collection while iterating
                }
            }
        }
    }

    void Flap()
    {
        // Apply force to make the bird jump
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);
    }

    void SpawnPipe()
    {
        GameObject newPipe = Instantiate(pipePrefab, pipeSpawnPoint.position, Quaternion.identity);
        pipes.Add(newPipe);
    }

    bool IsCollidingWithPipe(GameObject pipe)
    {
        Collider2D pipeCollider = pipe.GetComponent<Collider2D>();
        return pipeCollider != null && pipeCollider.bounds.Intersects(GetComponent<Collider2D>().bounds);
    }

    bool IsCollidingWithGround(GameObject ground)
    {
        Collider2D groundCollider = ground.GetComponent<Collider2D>();
        return groundCollider != null && groundCollider.bounds.Intersects(GetComponent<Collider2D>().bounds);
    }

    void EndGame()
    {
        // Implement game over logic (e.g., display score, restart menu)
        Debug.Log("Game Over!");
    }
}

제공된 Unity 스크립트는 플레이어가 제어하는 ​​새가 스크롤 환경을 통해 탐색하는 단순화된 Flappy Bird 게임을 나타냅니다. 새는 사용자 입력에 따라 점프할 수 있으며, 게임은 파이프와 지면과의 충돌을 확인하여 감지되면 게임을 종료합니다. 파이프는 일정한 간격으로 동적으로 생성되어 플레이어를 향해 이동합니다. 스크립트에는 성능 최적화를 위해 카메라 뷰 외부로 나가는 파이프를 제거하는 로직이 포함되어 있습니다. 'EndGame' 함수는 충돌 시 호출되며 점수 표시, 게임 재시작 등 다양한 게임 종료 시나리오를 처리하도록 확장될 수 있습니다. 이 코드는 Unity 환경 내에서 Flappy Bird 메커니즘의 기본 구현을 제공하는 것을 목표로 합니다.

6단계: UI 및 메뉴

  • 점수를 표시하기 위한 UI를 디자인합니다.
  • 게임을 시작하고 다시 시작하기 위한 메뉴를 만듭니다.

7단계: 게임플레이 미세 조정

  • 균형있고 즐거운 경험을 위해 게임 물리학 및 속도를 조정하세요.
  • 원활하고 도전적인 게임플레이를 보장하기 위해 게임을 테스트하고 반복하세요.

8단계: 음향 효과 추가

'FlappyBird.cs'에 사운드 효과를 추가하기 위한 수정 예:

using UnityEngine;
using System.Collections.Generic;

public class FlappyBird : MonoBehaviour
{
    // Existing variables...

    public AudioClip jumpSound;
    public AudioClip collisionSound;
    public AudioClip gameOverSound;

    private AudioSource audioSource;

    void Start()
    {
        // Existing Start() code...

        // Add AudioSource component and reference
        audioSource = gameObject.AddComponent<AudioSource>();
    }

    void Flap()
    {
        // Apply force to make the bird jump
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);

        // Play jump sound
        audioSource.PlayOneShot(jumpSound);
    }

    void EndGame()
    {
        // Play game over sound
        audioSource.PlayOneShot(gameOverSound);

        // Implement other game over logic...
    }

    // Existing code...
}

9단계: 빌드 및 배포

  • 대상 플랫폼(iOS, Android 등)에 맞게 게임을 빌드하세요.
  • 선택한 장치나 에뮬레이터에서 배포하고 테스트하세요.

결론

이 튜토리얼에서는 이 고전적인 플래피 버드 게임을 Unity에서 재현하는 필수 단계를 다룹니다. 추가 기능과 개선 사항을 실험하여 자신만의 게임을 만들어보세요. 즐거운 게임 개발 되세요!

추천 기사
Unity의 미니 게임 | 플래피 큐브
Unity에서 스네이크 게임을 만드는 방법
Unity에서 2D 벽돌깨기 게임 만들기
Unity에서 슬라이딩 퍼즐 게임 만들기
Unity용 Endless Runner 튜토리얼
농장 좀비 | Unity로 2D 플랫폼 게임 만들기
Unity의 미니 게임 | 큐브피하다