Unity - 2D 종스크롤 슈팅 : 적 전투와 피격 이벤트 만들기

TXMAY·2023년 9월 21일
0

Unity 튜토리얼

목록 보기
24/33
post-thumbnail

이번 강좌는 적 전투와 피격 이벤트에 관한 강좌다.


적 생성 추가

저번 강좌에서 위에서 아래로만 적이 생성되었는데, 옆에서도 적이 생성되도록 추가하겠다.
스폰 포인트 오브젝트를 복사해서 좌우로 배치한다. (하위 오브젝트를 말하는 것이다)
그리고 게임매니저에게 새로운 스폰 포인트를 추가한 후, 다음과 같이 수정하고, 추가한다.

...

int ranPoint = Random.Range(0, 9);
GameObject enemy = Instantiate(enemyObjs[ranEnemy], spawnPoints[ranPoint].position, spawnPoints[ranPoint].rotation);
Rigidbody2D rigid = enemy.GetComponent<Rigidbody2D>();
Enemy enemyLogic = enemy.GetComponent<Enemy>();

if (ranPoint == 5 || ranPoint == 6)
{
	enemy.transform.Rotate(Vector3.back * 90);
    rigid.velocity = new Vector2(enemyLogic.speed * (-1), -1);
}
else if (ranPoint == 7 || ranPoint == 8)
{
	enemy.transform.Rotate(Vector3.forward * 90);
    rigid.velocity = new Vector2(enemyLogic.speed, -1);
}
else
{
    rigid.velocity = new Vector2(0, enemyLogic.speed * (-1));
}
...

그리고 'Enemy.cs'에 rigid와 관련된 코드는 전부 제거한다. (이동을 게임매니저로 옮김)
그런 다음 'BorderBullet'의 크기를 조절한다.

적 공격

이미 만들어 둔 총알 프리펩을 복사한 후, Open 버튼을 눌러 수정한다.
스프라이트와 이름을 수정하고 'EnemyBullet' 태그를 생성한 후, 추가한다.
그리고 다음과 같이 코드를 수정하고, 추가한다.

// Enemy.cs
...

public float maxShotDelay;
public float curShotDelay;

public GameObject bulletObjA;
public GameObject bulletObjB;
public GameObject player;
...

void Update()
{
    Fire();
    Reload();
}

void Fire()
{
    if (curShotDelay < maxShotDelay)
    {
        return;
    }
    if (enemyName == "S")
    {
        GameObject bullet = Instantiate(bulletObjA, transform.position, transform.rotation);
        Rigidbody2D rigid = bullet.GetComponent<Rigidbody2D>();
        Vector3 dirVec = player.transform.position - transform.position;
        rigid.AddForce(dirVec.normalized * 3, ForceMode2D.Impulse);
    }
    else if (enemyName == "L")
    {
        GameObject bulletR = Instantiate(bulletObjB, transform.position + Vector3.right * 0.3f, transform.rotation);
        GameObject bulletL = Instantiate(bulletObjB, transform.position + Vector3.left * 0.3f, transform.rotation);

        Rigidbody2D rigidR = bulletR.GetComponent<Rigidbody2D>();
        Rigidbody2D rigidL = bulletL.GetComponent<Rigidbody2D>();

        Vector3 dirVecR = player.transform.position - (transform.position + Vector3.right * 0.3f);
        Vector3 dirVecL = player.transform.position - (transform.position + Vector3.left * 0.3f);

        rigidR.AddForce(dirVecR * 10, ForceMode2D.Impulse);
        rigidL.AddForce(dirVecL * 10, ForceMode2D.Impulse);
    }
    curShotDelay = 0;
}

void Reload()
{
    curShotDelay += Time.deltaTime;
}
...

// GameManager.cs
...

public GameObject player;
...

void SpawnEnemy()
{
    ...
    
    enemyLogic.player = player;
    ...
    
}
...

normalized : 벡터가 단윗값(1)으로 변환된 변수
실행하면 적이 공격하게 된다.

피격 이벤트

다음과 같이 코드를 추가한다.

// Player.cs
...

public GameManager manager;
...

void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "Border")
    {
        ...
        
    }
    else if (collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "EnemyBullet")
    {
        manager.RespawnPlayer();
        gameObject.SetActive(false);
    }
}
...

// GameManager.cs
...

public void RespawnPlayer()
{
    Invoke("RespawnPlayerExe", 2f);
    player.transform.position = Vector3.down * 4f;
    player.SetActive(true);
}

void RespawnPlayerExe()
{
    player.transform.position = Vector3.down * 4f;
    player.SetActive(true);
}

플레이어가 총알이나 적에게 피격당하면 사라졌다가 2초 후, 다시 나타난다.


유니티는 변수(속도, 딜레이)를 Inspector 창에서 바꿀 수 있는 게 참 편한 것 같다.

profile
게임 개발 공부하는 고양이

0개의 댓글