공부/Unity
[Unity] 일정 시간내에 캐릭터를 많이 클릭하는 게임
굴러다니다니
2025. 5. 27. 09:05
일단 2D object -> sprite를 이용해 캐릭터를 만들어주었다
그 다음 캐릭터의 크기에 비슷한 2D collider를 추가해줘야한다
나는 동그래서 circle collider를 넣었고, capsule collider 등 원하는걸로 넣어준다
기본적으로 sprite를 클릭하면 sprite의 색이 바뀌며 랜덤한 좌표, 랜덤한 회전값을 가지는 식을 써야한다.
아무 스크립트를 만들고 캐릭터한테 넣어주자
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class TestClicker : MonoBehaviour
{
[SerializeField] SpriteRenderer m_spr;
private void OnMouseDown()
{
m_spr.color = Random.ColorHSV();
for (int i = 0; i < 5; i++)
{
transform.GetChild(i).GetComponent<SpriteRenderer>().color = m_spr.color;
}
transform.position = new Vector3(Random.Range(-5, 5), Random.Range(-5, 5));
transform.rotation = Quaternion.Euler(0, 0, Random.Range(0f, 360f));
}
}
나는 새의 노란색 날개 부분들 같이 함께 바뀌면 좋겠는 부분들때문에 for문을 썼지만 저 부분은 수정해도 무방하다
클릭을 당하면 Random.ColorHSV()의 값으로 몸통 색을 바꾸고, Range로 지정한 내에서의 랜덤한 값으로 position, rotation을 바꾸는 식이다.
OnMouseDown 함수 이름을 정확히 똑같이 쓸 것
다음으로 시작부터 계속 10초동안 시간초가 흐르고, 클릭하면 score값이 올라가며 maxscore를 갱신하는 코드를 포함하면
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.UI;
public class TestClicker : MonoBehaviour
{
[SerializeField] SpriteRenderer m_spr;
public int score = 0;
public int maxScore = 0;
[SerializeField] Image slider;
[SerializeField] TextMeshProUGUI tmpScore;
[SerializeField] TextMeshProUGUI tmpMaxScore;
[SerializeField] TextMeshProUGUI tmpTimer;
Coroutine currentCo;
private void Start()
{
currentCo = StartCoroutine(nameof(Timer));
}
private void Update()
{
if (currentCo == null) currentCo = StartCoroutine(nameof(Timer));
}
private void OnMouseDown()
{
score++;
if (maxScore < score)
{
maxScore = score;
tmpMaxScore.text = $"Max:{maxScore}";
}
tmpScore.text = score.ToString();
m_spr.color = Random.ColorHSV();
for (int i = 0; i < 5; i++)
{
transform.GetChild(i).GetComponent<SpriteRenderer>().color = m_spr.color;
}
transform.position = new Vector3(Random.Range(-5, 5), Random.Range(-5, 5));
transform.rotation = Quaternion.Euler(0, 0, Random.Range(0f, 360f));
}
IEnumerator Timer()
{
score = 0;
tmpScore.text = score.ToString();
var t = 10f;
while (t >0 )
{
t -= Time.deltaTime;
slider.fillAmount = t / 10f;
tmpTimer.text = t.ToString("0");
yield return null;
}
t = 0;
tmpTimer.text = t.ToString();
currentCo = null;
}
}
위에처럼 짜주었다.
10초에 한번씩 코루틴이 실행되고, update문에서 현재 실행되고 있는 코루틴이 있는지 확인한다
캐릭터를 클릭하면 score값이 올라가고, max score에 반영하는 등 단순한 구조이다
t는 10에서 time.deltatime만큼씩 줄어드는데, 이를 .ToString("0")을 사용해 한자리 수만 보이게 처리해줬다.
728x90
반응형