Unity 게임 개발 입문
팀프로젝트 / 똥피하기 / Item & Enemy 설정
도도9999
2023. 9. 11. 20:23
1. 제일 구현이 잘 되어있는 병권님 프로젝트를 기준으로 클론해왔다.
2. Item (Bomb) 관련 기능 구현
- Bomb을 먹으면 화면 내에 있던 Poop들이 모두 제거된다.
- Bomb는 화면 내 최대 3개까지만 생성된다.
- (해당 스크립트는 추후 Heal, Speed 등 여러 아이템들을 추가로 구현하고, ItemManager를 만들어 관리할 예정)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemBomb : MonoBehaviour
{
private Animator _anim;
private int _positionX;
private int _positionY;
private static int maxBombCount = 3; // 최대 허용 폭탄 수
private static int currentBombCount = 0; // 현재 폭탄 수
public void GetPosition()
{
if (currentBombCount < maxBombCount)
{
_positionX = Random.Range(0, 19);
_positionY = Random.Range(0, 7);
if (SpawnerManager.I.GetSpawner(_positionX, _positionY) == 0)
{
SpawnerManager.I.SetSpawner(_positionX, _positionY, 1);
Init();
currentBombCount++; // 폭탄 생성 시 폭탄 수 증가
}
else
{
GetPosition();
}
}
}
private void Init()
{
_anim = GetComponent<Animator>();
transform.position = new Vector3(_positionX - 9, _positionY - 3, 0);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
Bullet[] b = FindObjectsOfType<Bullet>();
foreach (Bullet g in b)
{
g.gameObject.SetActive(false);
}
Trap[] t = FindObjectsOfType<Trap>();
foreach (Trap g in t)
{
g.gameObject.SetActive(false);
}
_anim.SetTrigger("Bomb");
StartCoroutine(Bomb());
}
}
IEnumerator Bomb()
{
yield return new WaitForSeconds(0.4f);
SpawnerManager.I.SetSpawner(_positionX, _positionY, 0);
gameObject.SetActive(false);
currentBombCount--; // 폭탄이 사라질 때 폭탄 수 감소
}
}
3. Enemy Spawn 설정
- Enemy는 초기 우측 좌표에 1명으로 시작.
- 추후 우, 좌, 상, 하 순서대로 정해진 시간에 따라 생성
- 난이도를 협의해 생성 주기 설정 예정
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public GameObject enemyPrefab; // 생성할 Enemy 프리팹
public float spawnInterval = 5.0f; // Enemy 생성 간격 (초)
private Vector3[] spawnPositions; // Enemy가 생성될 위치 좌표 배열
private int currentSpawnPositionIndex = 0; // 현재 생성 위치 인덱스
private float timer = 0.0f; // 생성 타이머
// 생성될 위치 좌표를 Awake()에서 초기화
private void Awake()
{
// 원하는 위치 좌표를 직접 설정
spawnPositions = new Vector3[]
{
new Vector3(13f, 0f, 0f), // 오른쪽
new Vector3(-13f, 0f, 0f), // 왼쪽
new Vector3(0f, 7f, 0f), // 위
new Vector3(0f, -7f, 0f) // 아래
};
}
private void Update()
{
// 일정 시간 간격으로 Enemy 생성
timer += Time.deltaTime;
if (timer >= spawnInterval)
{
SpawnEnemy();
timer = 0.0f; // 타이머 초기화
}
}
private void SpawnEnemy()
{
// 현재 인덱스에 해당하는 위치에 Enemy 생성
Vector3 spawnPosition = spawnPositions[currentSpawnPositionIndex];
Instantiate(enemyPrefab, spawnPosition, Quaternion.identity);
// 다음 인덱스로 이동 (순환)
currentSpawnPositionIndex = (currentSpawnPositionIndex + 1) % spawnPositions.Length;
}
}