화면 하단 아래 원형의 풍선이 있고 플레이어는 마우스를 통해 파란 쉴드를 움직이며 떨어지는
상자로부터 풍선을 지키는 게임입니다.
// 쉴드
void Update()
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = mousePos;
}
ScreenToWorldPoint함수를 통해서 마우스의 좌표계를 카메라 좌표계로 변환후 변수에 저장하고
저장된 값을 Shield의 위치로 저장하여 마우스가 위치가 변할때마다 Shield도 따라가게 됩니다.
//상자
void Start()
{
float x = Random.Range(-3.0f, 3.0f);
float y = Random.Range(3.0f, 5.0f);
transform.position = new Vector2(x, y);
float size = Random.Range(0.5f, 1.5f);
transform.localScale = new Vector2(size, size);
}
void Update()
{
Vector3 viewPos = Camera.main.WorldToViewportPoint(transform.position);
if (viewPos.x < 0 || viewPos.x > 1 || viewPos.y < 0 || viewPos.y > 1)
{
Destroy(this.gameObject);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
GameManager.Instance.GameOver();
}
}
일정 구간에 랜덤한 위치에서 생성되고 풍선과 충돌 시 게임오버 함수를 호출하여 게임을 다시 시작하는 UI를 노출합니다.
상자의 위치를 메인 카메라의 시야 영역에서 상대적으로 변환한 값을 변수로 받고 시야밖을
벗어나게 되면 자동으로 삭제되게 하였습니다.
// 게임 매니저
using UnityEngine.UI;
public static GameManager Instance;
public GameObject square;
public GameObject endPanel;
public Text timeTxt;
public Text nowScore;
public Text bestScore;
public Animator anim;
bool isPlay = true;
float time = 0.0f;
string key = "bestScore";
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
}
void Start()
{
Time.timeScale = 1.0f;
InvokeRepeating("MakeSquare",0f,1f);
}
// Update is called once per frame
void Update()
{
if (isPlay)
{
time += Time.deltaTime;
timeTxt.text = time.ToString("N2");
}
}
void MakeSquare()
{
Instantiate(square);
}
public void GameOver()
{
isPlay = false;
anim.SetBool("IsDie",true);
Invoke("TimeStop",0.5f);
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 = 0.0f;
}
게임매니저를 싱글톤 처리하여 상자가 풍선과 충돌했을때 게임매니저 게임오버 함수를 호출하게 해주었고 게임을 멈추고 시작하는 관리를 합니다.
PlayerPrefs클래스를 사용해 플레이를 종료해도 bestScore가 지워지지 않고 남도록 저장합니다.
// 재시작 버튼
public void Retry()
{
SceneManager.LoadScene("MainScene");
}
게임오버 후 UI에서 다시시작 버튼을 누르면 Retry 함수가 호출되고 MainScene이 다시 로드되어 게임을 진행하게 됩니다.