와와

[ Unity 슈팅게임 ] 2. 적 오브젝트/ 랜덤생성/ 충돌 설정 본문

개발/Unity 3D

[ Unity 슈팅게임 ] 2. 적 오브젝트/ 랜덤생성/ 충돌 설정

정으주 2022. 8. 19. 15:20

 

< Enemy.cs >

 

- 적 오브젝트 생성 시 아래로 움직임 > transform.Translate()

- 화면 아래로 사라지면 게임 오버 > 스크린 좌표계로 오브젝트 위치가 y축으로 -5 미만일 때 게임 오버

- 물체 충돌 시 오브젝트 삭제, 플레이어와 충돌 시 게임 오버 > OnCollisionEnter

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    
    public float enemySpeed = 7f; //속도
    public GameObject Explosion;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Vector3.down * Time.deltaTime * enemySpeed);  // 생성 시 밑으로 움직임


        Vector3 view = Camera.main.WorldToScreenPoint(transform.position); // 월드 좌표계에서 스크린 좌표계로 변환
        if (view.y < -5 )  // 화면 아래로 사라지면 게임 오버
        {
            Debug.Log("Game Over");
            gameManager.instance.GameOver();
            Destroy(gameObject);
        }
    }

    void OnCollisionEnter(Collision collision) // 충돌 설정
    {
        
        //Debug.Log()
        Instantiate(Explosion, transform.position, transform.rotation);  // 충돌 파티클 생성
        if(collision.collider.CompareTag("PLAYER") )  // 플레이어와 충돌 시 게임 오버
        {
            gameManager.instance.GameOver();
        }
        else
        {
            gameManager.instance.AddScore(1);  // 충돌한다면(=적을 총알로 맞추면) 점수 +1
        }
        Destroy(collision.gameObject); 
        Destroy(this.gameObject); // 충돌한 오브젝트들 삭제
        
    }

}

 

적 오브젝트를 프리펩으로 두어 Enemy.cs 스크립트를 적용해주었다.

Collision 충돌이 적용되려면 rigidbody 컴포넌트 추가를 해줘야함.

또 적끼리 충돌해서 사라지는 현상을 막기 위해 Enemy 레이어를 추가하고 다음과 같이 설정했다.

 

 

플레이어와 충돌했을 경우 점수가 변동 없이 게임이 끝나야 하기 때문에

플레이어 오브젝트에 PLAYER 태그를 추가하고 CompareTag를 이용해 충돌을 분류해주었다.

 

위의 코드에서

gameManager.instance.어쩌구저쩌구 하는 부분들은

gameManager.cs에서 정의한 함수를 사용하는 부분이다. ( 나중에 설명 )

 

 

 

< EnemyManager.cs >

 

- 게임 경과 시간(curTime)이 정해둔 일정 시간(createTime)을 초과하면 적 오브젝트 랜덤 위치에 생성

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyManager : MonoBehaviour
{
    private float curTime = 0f;
    public float createTime = 1f;
    public GameObject Enemy;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        curTime += Time.deltaTime;
        if (curTime > createTime)
        {
            Instantiate(Enemy,new Vector3(Random.Range(-2.8f,2.8f),0,0) + transform.position  ,transform.rotation );
            curTime = 0f;
        }
    }
}

 

 

 

EnemyManager라는 빈 오브젝트를 게임 상단 중앙 부분에 위와 같이 두었다.

게임 상에서 저 조르디 만큼의 길이가 2.8f 이다.

그래서 일정 시간이 되었을 때

적 오브젝트 생성 위치를 EnemyManager 오브젝트 기준으로 (-2.8f, 2.8f) 만큼의 범위에서 랜덤으로 설정하여

다양한 위치에서 적 오브젝트가 등장할 수 있도록 하였다.