
[풍선을 지켜라]는 '떨어지는 오브젝트'로부터 '마우스를 따라 움직이는 쉴드 오브젝트'를 이용하여 하단의 '풍선 오브젝트'를 지키는 간단한 게임이다.
public class Shield : MonoBehaviour
{
void Update()
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = mousePos;
}
}
public class Square : MonoBehaviour
{
// Start is called before the first frame update
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_x = Random.Range(0.5f, 1.5f);
float size_y = Random.Range(0.5f, 1.5f);
transform.localScale = new Vector2(size_x, size_y);
// 다양한 크기와 모양을 가짐
}
// Update is called once per frame
void Update()
{
if (transform.position.y < -6.0f)
{
Destroy(gameObject);
} // Square가 화면 아래로 나가면 사라짐
}
private void OnCollisionEnter2D(Collision2D collision) // Balloon에 Player태그 설정
{
if (collision.gameObject.CompareTag("Player"))
{
GameManager.Instance.GameOver();
}
} // Square가 Balloon에 닿으면 GameManager의 GameOver() Method를 호출.
}
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public GameObject square;
public GameObject endPanel;
public Text timeTxt;
public Text nowScoreTxt;
public Text bestScoreTxt;
public Animator anim;
bool isPlay = true;
float time = 0.0f;
string key = "bestScore";
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
}
// Start is called before the first frame update
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);
nowScoreTxt.text = time.ToString("N2");
if (PlayerPrefs.HasKey(key))
{
float best = PlayerPrefs.GetFloat(key);
if (best < time)
{
PlayerPrefs.SetFloat(key, time);
bestScoreTxt.text = time.ToString("N2");
}
else
{
bestScoreTxt.text = best.ToString("N2");
}
}
else
{
PlayerPrefs.SetFloat(key, time);
bestScoreTxt.text = time.ToString("N2");
}
endPanel.SetActive(true);
}
void TimeStop()
{
Time.timeScale = 0.0f;
}
}
public class RetryBtn : MonoBehaviour
{
public void Retry()
{
SceneManager.LoadScene("MainScene");
}
}
public class ResetScoreBtn : MonoBehaviour
{
public Text bestScoreTxt;
public void ResetScore()
{
PlayerPrefs.DeleteAll();
bestScoreTxt.text = "0.00";
}
}