using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class EnemySpawnBox_1 : MonoBehaviour
{
public string compareTag;
public UnityEvent onTriggerExitEvent;
public UnityEvent onTriggerStayEvent;
public bool enableSpawn = false;
public GameObject[] enemiesprefabs;
private BoxCollider2D area;
// ๋์ ์ ์คํฐ ๊ฐฏ์
int enemyVisibleLimit;
// ์ต๋ ์ ์คํฐ ๊ฐฏ์
int enemySpawnLimit;
// ์์ฑ๋ ๊ฐ์ฒด๋ฅผ ๋ฐ์์ฌ ๋ฐฐ์ด
public GameObject[] enemyclonelist;
private new List<GameObject> gameObject = new List<GameObject>();
public void OnTriggerExit2D(Collider2D collision) {
if (collision.gameObject.CompareTag(compareTag)) {
// onTriggerExitEvent.Invoke();
enableSpawn = false;
}
}
public void OnTriggerStay2D(Collider2D collision) {
if (collision.gameObject.CompareTag(compareTag)) {
//onTriggerStayEvent.Invoke();
enableSpawn = true;
}
}
void Start() {
area = GetComponent<BoxCollider2D>();
area.enabled = true;
// ์ ์คํฐ ๊ด๋ จ ๊ฐ ์ด๊ธฐํ
enemyVisibleLimit = 2;
enemySpawnLimit = 10;
InvokeRepeating("Spawn", 0, 2);
}
private Vector3 GetRandomPosition()
{
Vector3 basePosition = transform.position;
Vector3 size = area.size;
float posX = basePosition.x + Random.Range(-size.x/2f, size.x/2f);
float posY = basePosition.y + Random.Range(-size.y/2f, size.y/2f);
float posZ = basePosition.z + Random.Range(-size.z/2f, size.z/2f);
Vector3 spawnPos = new Vector3(posX, posY, posZ);
return spawnPos;
}
private void Spawn()
{
if (enableSpawn)
{
// Prefub์ ํ๊ทธ๋ฅผ ์ด์ฉํด์ ์ ๊ฐฏ์ ์ฐพ์์ค๊ธฐ
enemyclonelist = GameObject.FindGameObjectsWithTag("Enemy");
if(enemyclonelist.Length < 5)
{
int selection = Random.Range(0, enemiesprefabs.Length);
GameObject selectedPrefab = enemiesprefabs[selection];
Vector3 spawnPos = GetRandomPosition();//๋๋ค์์นํจ์
GameObject instance = Instantiate(selectedPrefab, spawnPos, Quaternion.identity);
gameObject.Add(instance);
}
// else if(enemyclonelist.Length >= 5) { enableSpawn = false;}
}
}
}
์ ์ฝ๋๋๋ก ํ๋ฉด ๋ฆฌ์คํฐ ๋ฐ์ค ์ฝ๋ผ์ด๋ ์์ญ ์์์ ๋ชฌ์คํฐ๋ค์ด ๋๋คํ๊ฒ ์ ๋๋๋ฐ
๋ฌธ์ ๋ "enemy"ํ๊ทธ๋ฅผ ๊ฐ์ง ๋ชฌ์คํฐ 5๋ง๋ฆฌ๊ฐ ๋ฆฌ์คํฐ ๋๊ณ ๋๋ฉด
๊ฐ์ ์ฌ ์์ ๋ค๋ฅธ ์์น์๋ ๋ฐ๋ก ๋ชฌ์คํฐ 5๋ง๋ฆฌ๊ฐ ๋ฆฌ์คํฐ ๋๋๋ก ํ๊ณ ์ถ์๋ฐ
๋ฆฌ์คํฐ๋ฐ์ค๋ฅผ ๋ณต์ฌํด์ ๋ค๋ฅธ๊ณณ์ ๋๋ฉด ๋ชฌ์คํฐ๋ ์ ์ฒด ๋งต๊ธฐ์ค enemy๊ฐ ์ด๋ฏธ 5๋ง๋ฆฌ๊ฐ ์ฐจ์
๋์ด์ ๋ฆฌ์คํฐ๋์ง ์์ต๋๋ค.
๋ฆฌ์คํฐ ๋ฐ์ค๋ง๋ค ๋ชฌ์คํฐ ํ๊ทธ๋ฅผ enemy2,enemy3 ์ด๋ฐ์์ผ๋ก ํ๋ฉด ํด๊ฒฐ์ ๋๋๋ฐ ๊ทธ๋ฌ๋ฉด ํ๊ทธ๊ฐฏ์ซ๊ฐ ๋๋ฌด ๋์ด๋ ๊ฒ ๊ฐ์๋ฐ
๊ฐ์ enemyํ๊ทธ์ฌ๋ ๋ฆฌ์คํฐ ๋ฐ์ค๋ง๋ค ๋ฐ๋ก ์ธ์์ด ๋๊ฒ ํ ๋ฐฉ๋ฒ์ด ์์๊น์?
ํ์ด๋ผํค์์ ๋ชจ๋ ์ค๋ธ์ ํธ์์ ์๋๋ฏธ ํ๊ทธ๋ก ์ฐพ์ง๋ง๊ณ physics2d๋ก ํน์ ๊ตฌ๊ฐ์ ์ฝ๋ฆฌ๋๋ฅผ ๊ฐ์ง ์ค๋ธ์ ํธ ์ค์์๋ง ์๋๋ฏธํ๊ทธ๊ฐ ์๋์ง ๊ฑธ๋ฌ๋ด๋ฉด ๋ ๋ฏ
https://docs.unity3d.com/ScriptReference/Physics2D.BoxCastAll.html
physics2d.size = ์ค๋ธ์ ํธ์ ๋ถ์ฌ๋ ์ฝ๋ผ์ด๋ ์ฌ์ด์ฆ ์ด๋ฐ์์ผ๋ก์? ์ ๊ฐ ์จ์ต ์ง์์ด ์งง์์ ์๋ฅผ ๋ค์ด ์ข ์จ์ฃผ์๋ฉด ์๋ ๊น์
https://gall.dcinside.com/mgallery/board/view/?id=game_dev&no=120702&page=1