0. 들어가며
리듬 게임에는 리듬이 필수이다.
오늘은 유니티에서 음악을 재생하는 방법과,
화살표를 버튼에 맞춰 누르지 못했을 때, 그리고 눌렀을 때 Hit와 Miss를 체크할 수 있도록 한다.
1. 음악 재생과 설정을 위한 GameManager 생성
하이어라키 창에서 Create Empty로 GameManager를 만들고,
그 아래 스크립트 컴포넌트로 GameManager를 넣어준다
using UnityEngine;
public class GameManager : MonoBehaviour
{
public AudioSource music; // 음악 넣기
public bool startPlaying; // 플레이 시작
public BeatScroller beatsroller; // 스크롤 시작 컨트롤
public static GameManager instance; // 싱글톤
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
instance = this;
}
// Update is called once per framed
void Update()
{
if(!startPlaying)
{
if(Input.anyKeyDown) // 아무런 키가 눌리면
{
startPlaying = true;
beatsroller.hasStarted = true; // 게임 매니저에서 한 번에 해결
music.Play();
}
}
}
public void NoteHit()
{
Debug.Log("Hit On Time");
}
public void NoteMissed()
{
Debug.Log("Missed Note");
}
}
Gamanager의 Update에서 게임을 실행하게 한다. 사실 기존 BeatScroller와 동일한 처리를 해주었다.
그래서 BeatScroller.cs에서는 이 부분을 주석 처리하였다.
NoteHit와 NoteMissed 함수를 만들어, 로그로 Hit와 Miss 처리를 확인해보려고 한다.
AudioSource로 음악을 넣고, 게임이 실행 될 시 Play 해 줄 것이기 때문에 Play on Awake는 비활성화로 체크해준다.
2. GameManager에서 만든 Hit와 Miss 호출 처리
NoteObject.cs에서 처리해주도록 한다.
using UnityEngine;
public class NoteObject : MonoBehaviour
{
public bool canBePressed;
public KeyCode keyToPress;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(keyToPress))
{
if(canBePressed)
{
gameObject.SetActive(false);
GameManager.instance.NoteHit(); // 추가
}
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Activator")
{
canBePressed = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Activator")
{
// 노트가 이미 비활성화되었으면 미스 처리 안함
if (gameObject.activeSelf)
{
canBePressed = false;
GameManager.instance.NoteMissed();
}
}
}
}
canBePressed 상태에서 setActive(false)가 되었다면, Hit 판정으로 들어간다.
OnTriggerExit2D에서 Miss 처리를 해줄것인데, 기존 코드에 GameManager.instance.NoteMissed(); 를 추가하면
노트가 판정 구역을 벗어날 때 무조건 호출되기 때문에 노트의 개수대로 로그가 무조건 찍히게 된다.
즉, 노트가 Activator라는 태그를 가진 판정 구역을 떠날 때마다 canBePressed가 false로 설정되고, 동시에 NoteMissed()가 실행되는 것이다.
노트가 사라졌을 경우 OnTriggerExit2D에서 NoteMissed()가 호출되지 않도록 조건을 추가한다.
- 노트가 아직 활성화된 상태일 때만 NoteMissed()가 호출되도록 보장
- gameObject.activeSelf는 해당 오브젝트가 활성화된 상태인지 여부를 확인
3. 결과
디버그 로그가 알맞게 출력되는 것을 확인했다.
'개발일지 > Unity 6 [미제]' 카테고리의 다른 글
[Unity 6 - 프로젝트] 리듬 게임 4) Timing Hits에 따른 Score와 Effect (2) | 2024.10.27 |
---|---|
[Unity 6 - 프로젝트] 리듬 게임 3) Score & Combo System 개발 (1) | 2024.10.26 |
[Unity 6 - 프로젝트] 리듬 게임 1) Note Hit (0) | 2024.10.23 |
[Unity 6 - 프로젝트] 3D 캐릭터 이동 및 애니메이션 구현 (1) | 2024.10.23 |
[Unity6] 를 활용한 프로젝트 시작 (0) | 2024.10.23 |