게임 개발이 처음이어도 쉽게 배우는 모바일 게임 개발/Sparta_Unity

풍선을 지켜라 - 2

gaon99 2025. 1. 6. 17:14

지난번에 이어

 

목차

5. 게임 종료 로직

6. 최고 점수 구현

7. 풍선 애니메이션

8. 과제

9. 최종 시현 영상

10. 마무리 및 느낀점


5. 게임 종료 로직

 

5-1 GameManager 싱글톤

// GameManager.cs
public static GameManager Instance;

public void Awake()
{
    if(Instance == null)
    {
        Instance = this;
    }
}

 

5-2 종료함수 만들기

//GameManager.cs
public GameObject endPanel;

public void GameOver()
{
    Time.timeScale = 0.0f;
    endPanel.SetActive(true);
}

 

게임 종료가 되는 조건 생성

플레이어 태그가 있는 게임오브젝트와 충돌시 (풍선과 장애물(Square)충돌)

//Square.cs
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        GameManager.Instance.GameOver();
    }
}

 

 

 

5-3 현재 스코어 구현

//GameManager.cs
public Text nowScore;
public void GameOver()
{
    Time.timeScale = 0.0f;
    nowScore.text = time.ToString("N2");
    endPanel.SetActive(true);
}

 

5-4 딜레이 제거

Update() 와 Gameover() 간의 시간 차가 있기에 이를 제거해야 timeTxt와 nowscoretxt가 동일 값으로 나옴

bool 은 true or false 밖에 없는 자료형이다

//GameManager.cs
bool isPlay= true;

void Update()
{
    if (isPlay)
    {
        time += Time.deltaTime;
        timeTxt.text = time.ToString("N2");
    }
}

public void GameOver()
{
    isPlay= false;
    Time.timeScale = 0.0f;
    thisScoreTxt.text = time.ToString("N2");
    endPanel.SetActive(true);
}

 

5-5 다시하기 구현

Assets → Scripts → retry.cs 생성

MainScene을 다시 로드하는 코드 작성

using UnityEngine;
using UnityEngine.SceneManagement;

public class RetryButton : MonoBehaviour
{
    public void Retry()
    {
        SceneManager.LoadScene("MainScene");
    }
}

 

5-6 시간 재설정

Gameover()를 통해 Timescale = 0f 로 설정했기에 

시작시에 Timescale을 다시 1f로 설정

//GameManager.cs
void Start()
{
    Time.timeScale = 1.0f;
    InvokeRepeating("MakeSquare", 0.0f, 1.0f);
}

 

5-7 retrybtn에 스크립트 붙이기

지난 주차에 했던 On Click도 같이 설정

 

6. 최고 점수 구현

 

6-1 PlayerPrefs

// 데이터 저장
PlayerPrefs.SetFloat("bestScore", 어떤숫자값);
PlayerPrefs.SetString("bestScore", 어떤문자열);

// 데이터 불러오기
어떤숫자값 = PlayerPrefs.GetFloat("bestScore");
어떤문자열 = PlayerPrefs.GetString("bestScore");

//데이터를 저장했는지 True or False
PlayerPrefs.HasKey("bestScore")

//데이터 지우기
PlayerPrefs.DeleteAll();

 

6-2 조건문 작성

//GameManager.cs
String key = "bestScore";

public void GameOver()
{
    isRunning = false;
    Time.timeScale = 0.0f;
    nowScore.text = time.ToString("N2");

    if (PlayerPrefs.HasKey(key)) 
    {
        float best = PlayerPrefs.GetFloat(key);
        if(best < time) 
        {
            PlayerPrefs.SetFloat(key, time);
            bestScore.text = time.ToString("N2");
        }
        else
        {
            bestScore.text = best.ToString("N2");
        }
    }
    else
    {
        PlayerPrefs.SetFloat(key, time);
        bestScore.text = time.ToString("N2");
    }

    endPanel.SetActive(true);
}

 

 

7. 풍선 애니메이션

 

7-1 애니메이션

풍선과 장애물이 닿이면 풍선이 터지는듯한 애니메이션 실행 후 Gameover

Balloon_idle → Balloon Object 선택 → Animation 창에서 Add New Clip → Balloon_die 생성

0 Balloon 

0.20 : Scale X = 2, Y = 2 (R G B A : 255, 0, 0, 125)

 

7-2 애니메이션 클립

balloon animator → idle, die /  Transition 만들기

마우스 우클릭 후 make Transition

 

Parameters 에 bool 형식의 isDie 생성

Transition 클릭 후 사진처럼 설정

 

7-3 애니메이션 전환

Animator Component를 받기

//GameManager.cs
public Animator anim;

 

Gameover() 에 isDie 값 바꿔주기

그리고 애니메이션이 처리 할 여유를 주기

//GameManager.cs
String key = "bestScore";

public void GameOver()
{
    isplay = false;
    anim.SetBool("isDie",True);
    Invoke("TimeStop", 0.5f);
    Time.timeScale = 0.0f;
    nowScore.text = time.ToString("N2");

    if (PlayerPrefs.HasKey(key)) 
    {
        float best = PlayerPrefs.GetFloat(key);
        if(best < time) 
        {
            PlayerPrefs.SetFloat(key, time);
            bestScore.text = time.ToString("N2");
        }
        else
        {
            bestScore.text = best.ToString("N2");
        }
    }
    else
    {
        PlayerPrefs.SetFloat(key, time);
        bestScore.text = time.ToString("N2");
    }

    endPanel.SetActive(true);
}
void timestop()
    {
        Time.timeScale = 0f;
    }
}

 

 

8. 과제

떨어지는 네모 없애기

- 화면 밖에 나간 네모들이 삭제 되지않고 쌓여있다.

- 화면 밖에 네모가 나가면 삭제하는 로직 생성하기

Square.cs에 아래 코드 추가

//Square.cs
  void Update()
  {
      if (transform.position.y < -5)
      {
          Destroy(this.gameObject);
      }    
  }

9. 최종 시현 영상

 

 

10. 마무리 및 느낀점

 

1주차 내용의 복습인 내용이 많아 처음하던 1주차 보단 수월하게 할 수 있었다.

현재는 가벼운 로직들로 만들어진 기초이지만 점차 늘려가

내가 상상하는 것들을 게임으로 만들 수 있는 두 번째 발자국이라 느낀다.