// 게임개발 종합반 - 1주차
// 빗물받는 르탄이 제작
빗방울 코딩하기
1. 빗방울 그리기
2. 빗방울을 떨어지게 하려면?
- transform.position 을 쓸수있고,
- 중력 세팅으로 쉽게 해결할수도 있음 rigidbody 2D - gravity scale
3. 바닥을 만나면 없어지게 하려면?
- OnCollisionEnter를 쓰려나?
- Collider 를 먼저 먹이자 바닥은 boxcollider, 빗방울은 circlecollider
- 전에는 layer를 쓰기도 했었는데, 강사님은 tag를 사용하심. 충돌 가능한 모든 요소에 태그를 달아줌
- 2d는 OnCollisionEnter2D가 따로 있음
- 빗방울 없어지기는 Destroy(); 사용. 아직 오브젝트풀은 안배우는 듯.
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
Debug.Log("땅이다");
Destroy(gameObject);
}
}
4. 빗방울이 랜덤하게 나타나도록
void Start()
{
// 빗방울 랜덤 포지션 잡기
float x = Random.Range(-2.7f, 2.7f);
float y = Random.Range(3.0f, 5.0f);
transform.position = new Vector3(x, y, 0);
}
5. 3가지 크기 빗방울 만들기
- 목표 - 3가지 크기와 3가지 색깔로 변경한다.
- 사이즈 변경: transform.localScale = new Vector3(size, size, 0);
- 색 변경: GetComponent<SpriteRenderer>().color = new Color(100 / 255f, 100 / 255f, 255 / 255f, 255 / 255f);
public class Rain : MonoBehaviour
{
// 빗방울 타입 변수
int type;
// 빗방울 크기 변수
float size;
// 빗방울 점수 변수
int score;
// Start is called before the first frame update
void Start()
{
// 빗방울 랜덤 포지션 잡기
float x = Random.Range(-2.7f, 2.7f);
float y = Random.Range(3.0f, 5.0f);
transform.position = new Vector3(x, y, 0);
// 1,2,3 3가지 타입을 랜덤
type = Random.Range(1, 4);
if(type == 1)
{
size = 1.2f;
score = 3;
GetComponent<SpriteRenderer>().color = new Color(100 / 255f, 100 / 255f, 255 / 255f, 255 / 255f);
}
if(type == 2)
{
size = 1.0f;
score = 2;
GetComponent<SpriteRenderer>().color = new Color(130 / 255f, 130 / 255f, 255 / 255f, 255 / 255f);
}
else
{
size = 0.8f;
score = 1;
GetComponent<SpriteRenderer>().color = new Color(150 / 255f, 150 / 255f, 255 / 255f, 255 / 255f);
}
transform.localScale = new Vector3(size, size, 0);
6. 빗방울 계속 나오게하기
- 게임매니저 오브젝트/스크립트 만들어 활용
- 게임매니저 역할 : 예) 점수 / 다시 시작 / 3번 째 다시 시작에 부스터 / 광고보기 등
- Rain 오브젝트를 Prefab으로 구현
- instantiate - 빗방울 공장 역할
- InvokeRepeating() - 특정 함수를 반복 실행
public class gameManager : MonoBehaviour
{
public GameObject rain;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("makeRain", 0, 0.5f);
}
// Update is called once per frame
void Update()
{
}
void makeRain()
{
// Debug.Log("비를 내려라");
Instantiate(rain);
}
}
UI 만들기
- UI의 위치는 다른 오브젝트와 다름
- UI는 캔버스아래 정렬
싱글톤
- 게임매니저는 단 하나여야 한다. 단 하나이기 위한 코딩 static
public class gameManager : MonoBehaviour
{
public GameObject rain;
// 싱글톤 화
public static gameManager GM;
void Awake()
{
GM = this;
}
점수 올라가게 하기
- 게임메니저에 아래 함수 추가하고 빗물 OnCollisionEnter 함수에서 아래 함수 활용
public void addScore(int score)
{
totalScore += score;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
Debug.Log("땅이다");
Destroy(gameObject);
}
if (collision.gameObject.tag == "rtan")
{
Debug.Log("르탄이다");
Destroy(gameObject);
gameManager.GM.addScore(score);
}
}
- totalScore 값을 Text 오브젝트에 넣어주기
// 점수판 text
public Text scoreText;
public void addScore(int score)
{
totalScore += score;
// int값을 string으로 바꿔서 넣기
scoreText.text = totalScore.ToString();
}