개발/유니티(UNITY)

5-6 유니티로 화살 피하기 게임 만들기(심화2)

새벽감성개발자 2023. 10. 30. 15:00
반응형

이전단계에서 어느정도 게임을 플레이 할 수 있게끔 만들었으니, 이제는 단계별로 점점 어려워지며, 플레이가 까다롭게 구현하는 일만 남았다.

별첨 1.  점수 추가하기

  • 화살표를 피해서, 화살표가 지면보다 아래로 떨어지는 경우 혹은 지면에 맞닫는 경우에 사라지며 점수를 얻게 되는 구조로 작성한다
  • 단계별로 점수를 더 많이 얻거나, 생존에 필요한 물품이 드랍될 수 있게 한다.

Text를 추가해서 점수를 표기할 수 있게 한다
앵커포인트는 상단 중앙에 세팅한다.

GameDirector

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameDirector : MonoBehaviour
{
    GameObject hpGauge;
    GameObject score;
    int point = 0;

    void Start()
    {
        this.hpGauge = GameObject.Find("HPGauge"); 
        this.score = GameObject.Find("Score");
    }

    public void DecreaseHp()
    {
        this.hpGauge.GetComponent<Image>().fillAmount -= 0.1f; 
    }

    public void IncreaseHp()
    {
        this.hpGauge.GetComponent<Image>().fillAmount += 0.2f; 
    }

    private void Update()
    {
        if (this.hpGauge.GetComponent<Image>().fillAmount <= 0)
        {
            SceneManager.LoadScene("ClearScene");
        }

        // 실시간으로 점수가 추가됨을 보여주기 위한
        this.score.GetComponent<TMPro.TextMeshProUGUI>().text = "Score : " + GetPoint();

    }

    public void SetPoint()
    {
        this.point += 1;
    }
    public int GetPoint()
    {
        return this.point;
    }
}

 

ArrowController

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ArrowController : MonoBehaviour
{
    GameObject player;

    void Start()
    {
        this.player = GameObject.Find("player");
    }

    void Update()
    {
        GameObject director = GameObject.Find("GameDirector");

        // 프레임 마다 등속으로 낙하시킨다.
        transform.Translate(0, -0.1f, 0);

        // 화면 밖으로 나오면 오브젝트를 소멸시킨다.
        if (transform.position.y < -5.0f)
        {
            Destroy(gameObject);
            director.GetComponent<GameDirector>().SetPoint(); // 점수를 추가한다.
        }

        // 충돌 판정
        Vector2 dir = transform.position - this.player.transform.position;
        float d = dir.magnitude;
        float arrowRange = 0.5f;
        float playerRange = 1.0f;

        if (d < arrowRange + playerRange)
        {
            // 감독 스크립트에 플레이어와 화살이 충돌했다고 전달한다.
            
            director.GetComponent<GameDirector>().DecreaseHp(); 
            // GameDirector에 public으로 선언한 DecreaseHP() 메서드를 호출한다.

            // 충돌한 경우는 화살을 지운다.
            Destroy(gameObject);
        }
    }

}

화살표가 사라지면서 점수가 오르게 된다.

 

반응형