Unity - 2D 종스크롤 슈팅 : 적 비행기 만들기

TXMAY·2023년 9월 21일
0

Unity 튜토리얼

목록 보기
23/33
post-thumbnail

이번 강좌는 적 비행기에 관한 강좌다.


준비하기

'Enemys' 스프라이트를 플레이어 스프라이트처럼 준비한다.
세 종류를 드래그하여 배치하고 Collider와 Rigidbody를 추가하고, Gravity Scale을 0으로 설정한다.
그리고 'Enemy' 태그를 추가한다.

적 프리펩

'Enemy.cs' 파일을 생성한 후, 다음과 같이 코드를 작성한다. ('Bullet.cs'도 수정해야 한다)

// Enemy.cs
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float speed;
    public int health;
    public Sprite[] sprites;

    SpriteRenderer spriteRenderer;
    Rigidbody2D rigid;

    void Awake()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        rigid = GetComponent<Rigidbody2D>();
        rigid.velocity = Vector2.down * speed;
    }

    void OnHit(int dmg)
    {
        health -= dmg;
        spriteRenderer.sprite = sprites[1];
        Invoke("ReturnSprite", 0.1f);

        if (health <= 0)
        {
            Destroy(gameObject);
        }
    }
    void ReturnSprite()
    {
        spriteRenderer.sprite = sprites[0];
    }
    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "BorderBullet")
        {
            Destroy(gameObject);
        }
        else if (collision.gameObject.tag == "PlayerBullet")
        {
            Bullet bullet = collision.gameObject.GetComponent<Bullet>();
            OnHit(bullet.dmg);
            
            Destroy(collision.gameObject);
        }
    }
}

// Bullet.cs
...

public int dmg;
...

그리고 public 변수들의 값을 설정하고 Is Trigger를 활성화한다.
그런 다음 총알처럼 프리펩을 만든다.

적 생성

적을 생성하기 위한 게임매니저 오브젝트와 스크립트를 생성하고 다음과 같이 코드를 추가한다.

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public GameObject[] enemyObjs;
    public Transform[] spawnPoints;

    public float maxSpawnDelay;
    public float curSpawnDelay;

    void Update()
    {
        curSpawnDelay += Time.deltaTime;

        if (curSpawnDelay > maxSpawnDelay)
        {
            SpawnEnemy();
            maxSpawnDelay = Random.Range(0.5f, 3f);
            curSpawnDelay = 0;
        }
    }

    void SpawnEnemy()
    {
        int ranEnemy = Random.Range(0, 3);
        int ranPoint = Random.Range(0, 5);
        Instantiate(enemyObjs[ranEnemy], spawnPoints[ranPoint].position, spawnPoints[ranPoint].rotation);
    }
}

그리고 생성 위치를 정하기 위해 'SpawnPoint Group'이란 오브젝트에 하위 오브젝트로 위치 오브젝트 5개를 생성한 후, 각 오브젝트의 위치를 지정한다.
그런데 오브젝트에 스프라이트가 없어서 위치가 잘 보이지 않는다.
이럴 때는 태그 아이콘을 추가하면 위치를 확인할 수 있다. (Inspector 창에 있는 속이 빈 정육면체 아이콘)
그리고 public 변수들의 값을 정한다.
실행하면 랜덤한 종류의 적들이 랜덤하게 생성된다.


생성 위치를 오브젝트로 지정하는 방식은 꽤 참신했다.

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

0개의 댓글