점수, 라이프, 재시작 버튼 등 간단한 UI를 만들어보겠습니다.
UI를 만들고 앵커와 Position으로 위치를 잡아줍니다.
라이프가 0이되었을때, 게임오버를 띄울 것이므로 Over Set 오브젝트는 비활성화 시켜놓습니다.
우선 플레이어 스크립트에 두가지 변수를 추가합니다.
public int life; //라이프
public int score; //점수
public bool isHit; //이중피격을 방지하기 위한 변수
그리고 플레이어 스크립트의 OnTriggerEnter2D 함수에 다음 코드를 입력합니다.
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Border")
{
...
}
else if (collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "EnemyBullet") {
if (isHit) { //isHit가 true라면 return으로 함수 끝
return;
};
isHit = true; //isHit을 true로 바꿔 피격상태임을 인식
life--; 라이프 개수 -1
gm.updateLifeIcon(life); //GameManager 스크립트의 함수 호출
if (life == 0) //라이프가 0이 되면
{
gm.gameOver(); //GameManager의 게임오버 함수 호출
}
else {
gm.respawnPlayer(); //라이프가 0이 아니라면 GameManager의 리스폰 함수 호출
}
gameObject.SetActive(false); //플레이어 비 활성화
Destroy(collision.gameObject); //콜라이더 충돌한 적 전투기 또는 적 총알 삭제
}
}
다음으로 GameManager 스크립트에 아래 코드를 입력합니다.
using UnityEngine.UI;
using UnityEngine.SceneManagement;
//UI
public Image[] lifeImage;
public Text scoreText;
public GameObject gameOverSet;
void Update()
{
...
Player playerScript = player.GetComponent<Player>();
scoreText.text = string.Format("{0:n0}",playerScript.score); //점수 천단위 끊기 포맷
}
public void updateLifeIcon(int life) {
//Life Icon 다 끄기
for (int index = 0; index < 3; index++)
{
lifeImage[index].color = new Color(1, 1, 1, 0.2f);
}
//남은 목숨 갯수만큼만 Life Icon 다시 켜기
for (int index = 0; index < life; index++) {
lifeImage[index].color = new Color(1, 1, 1, 1);
}
}
public void gameOver() {
gameOverSet.SetActive(true); //Over Set 오브젝트 활성화
}
public void gameRetry() {
SceneManager.LoadScene(0); //Scene을 다시 로드
}
public void respawnPlayer() {
Invoke("respawnPlayerExe", 2f);
}
void respawnPlayerExe()
{
Player playerScript = player.GetComponent<Player>(); //플레이어 스크립트 불러오기
playerScript.isHit = false; //플레이어 리스폰 시 isHit false로 원상복귀
player.transform.position = Vector3.down * 3.5f;
player.SetActive(true);
}
그리고 Enemy 스크립트에 아래 코드를 추가합니다.
public int enemyScore;
void onHit(int dmg) {
...
if (health <= 0) {
Player playerScript = player.GetComponent<Player>();
playerScript.score += enemyScore; //플레이어 스크립트의 score 변수에 enemy score을 더해줌
Destroy(gameObject);
}
}
이제 맵핑을 합니다.
결과
'종스크롤 슈팅게임(1942)' 카테고리의 다른 글
7. 원근감 있는 무한 배경 만들기 (0) | 2022.01.21 |
---|---|
6. 아이템과 필살기 구현하기 (0) | 2022.01.20 |
4. 적 전투기 총알 & 플레이어 피격 이벤트 구현 (0) | 2022.01.18 |
3. 적 전투기 만들기 (0) | 2022.01.18 |
2. 플레이어 총알 구현 (0) | 2022.01.18 |