본문 바로가기
Unity/3D 비행기 게임

[유니티] 3D 비행기 게임(소리, 효과 넣기)

by Skull Crusher 2021. 5. 7.
728x90

Audio.zip
2.83MB
Effects.zip
0.28MB

 

새로운 폴더를 추가 할 때 배포된 이름으로 추가되는지 꼭 확인!

이름이 변경되면 경로가 깨질 수 있음.

 

1. 레이저 발포 주기 조정(Time.time)

PlayerShip Fire DelayTime 1초 입력

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

public class ShipFire : MonoBehaviour
{
    //레이저 프리팹
    public GameObject laserPrefab;

    //발포 위치 참조
    public Transform spawnTransform;

    public float fireDelayTime; // 발포 지연 시간

    private float fireTime; // 발포 시간

   
    // Update is called once per frame
    void Update()
    {
        //Debug.Log("Time.time : " + Time.time);
        //Time.time : 실행 후 경과된 시간값

        //왼쪽 컨트롤 키를 누르고 다음 발포시간을 경과시간이 넘겼다면
        if (Input.GetKeyDown(KeyCode.LeftControl) && (Time.time > fireTime))
        {
            //현재 경과된 시간에 지연시간을 가산하여 다음 발포 시간을 설정
            fireTime = Time.time + fireDelayTime;

            Instantiate(laserPrefab, spawnTransform.position, Quaternion.identity);
        }
    }
}

 

2. 레이저 파괴

Space -> Box Collider -> Is Trigger 

C# Script -> 이름 바꾸기 DestroySpaceBox 

발포된 레이저가 파괴되는 것을 볼 수 있음

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

public class DestroySpaceBox : MonoBehaviour
{
    //충돌 이벤트 함수
    // void OnTriggerEnter() : 충돌 시작될 때 호출되는 이벤트 메소드 (충돌 영역에 들어올때)
    // void OnTriggerStay() : 충돌 진행될 때 호출되는 이벤트 메소드
    // void OnTriggerExit() : 충돌 종료될 때 호출되는 이벤트 메소드 (충돌 영역에 나갈때)

    private void OnTriggerExit(Collider collision)
    {
        //화면 영역(우주공간)을 벗어난 오브젝트는 파괴함
        Destroy(collision.gameObject);
    }
}

 

 

3. 피격대상 만들기

운석 드래그 -> 프리팹으로 만들기 -> collider 삭제 -> Add Component Rigidbody, Sphere Collider

Add Tag -> PlayerLaser

C# Script -> 운석에 붙이기 -> 폭발 효과 넣기

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

public class EnemyCollsion : MonoBehaviour
{
    //폭발 이펙트 참조
    public GameObject explosionPrefab;

    private void OnTriggerEnter(Collider collision)
    {
        if (collision.tag == "PlayerLaser")
        {
            //폭발 이펙트 생성
            GameObject effect = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
            Destroy(effect, 1f);

            Destroy(collision.gameObject);
            Destroy(gameObject);
        }
    }
}

 

4. 운석 떨어지기

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

public class DirectionMove : MonoBehaviour
{
    public Vector3 direction; //이동 방향

    public float moveSpeed; //이동 속도

    public Rigidbody rigidbody3d; //물리 엔진 참조

    public bool isRandomRotate; //랜덤 회전 처리 여부

    public float rotSpeed; //랜덤 회전 속도 

    // Start is called before the first frame update
    void Start()
    {
        rigidbody3d.velocity = direction * moveSpeed; //지정된 방향으로 이동

        //운석을 랜덤한 방향으로 회전 시킴
        if (isRandomRotate)
        {
            rigidbody3d.angularVelocity = Random.insideUnitSphere * rotSpeed;
        }
    }
   
}

 

5.  운석 추가

크기조절 0.3 0.2 0.3-> 프리팹으로 ->Add Component

 

6. 소리 넣기

배경음악

Create Empty -> Add Component Audio Source -> 오디오클립 참조 ->Loop

Main Camera 에 Audio Lishener 기본적으로 탑재!! 체크 확인

 

7. 소리 재생기 만들기

폭발음 효과 넣기 

C# Script -> 운석에 사운드매니저 참조 -> 사운드매니저 참조

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

//사운드 매니저
public class SoundManager : MonoBehaviour
{
    //사운드 재생기 (오디오 소스) 참조
    public AudioSource audioSource;

    //재생 사운드 리스트
    public AudioClip[] audioClips;

    public void PlaySound(int type)
    {
        //오디오 재생기에 사운드를 설정하고
        audioSource.clip = audioClips[type];
        //사운드를 재생함
        audioSource.Play();
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyCollsion : MonoBehaviour
{
    //폭발 이펙트 참조
    public GameObject explosionPrefab;

    //오디오 소스 참조 (소리 재생기 참조)
    public SoundManager soundManager;

    //오디오 클립 (소리 파일 참조)
    // public AudioClip audioClip;

    private void OnTriggerEnter(Collider collision)
    {
        if (collision.tag == "PlayerLaser")
        {
            //현재 오디오 소스에 설정된 클립을 재생 중이 아니라면
            //오디오 소스에 설정된 오디오 클립을 재생함
            soundManager.PlaySound(0);
            
            //폭발 이펙트 생성
            GameObject effect = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
            Destroy(effect, 1f);

            Destroy(collision.gameObject); //레이저 파괴
            Destroy(gameObject);
        }
    }
}

주의!! 

드래그&드롭 vs 코드참조

프리팹 상태에서는 게임오브젝트를 참조할 수 없음 !! (코드로 연결)

프리뱁을 게임오브젝트로 생성된 뒤에 코드로 참조해야 함!!

 

8.  운석이 게임오브젝트가 아니라 프리팹일 때 코드로 동적참조

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

public class EnemyCollsion : MonoBehaviour
{
    //폭발 이펙트 참조
    public GameObject explosionPrefab;

    //오디오 소스 참조 (소리 재생기 참조) -> 미리 접근이 안되기 때문에 인스펙터에 노출 안되게 함
    private SoundManager soundManager;

    private void Start()
    {
        //프리팹은 게임 오브젝트를 참조할 수 없기 때문에 GetComponent 써서 코드로 참조
        //게임 오브젝트를 동적으로 검색함
        // -> GameObject.Find("게임오브젝트이름");
        GameObject soundGameObject = GameObject.Find("SoundManager");
        soundManager = soundGameObject.GetComponent<SoundManager>();

    }

    //오디오 클립 (소리 파일 참조)
    // public AudioClip audioClip;

    private void OnTriggerEnter(Collider collision)
    {
        if (collision.tag == "PlayerLaser")
        {
            //현재 오디오 소스에 설정된 클립을 재생 중이 아니라면
            //오디오 소스에 설정된 오디오 클립을 재생함
            soundManager.PlaySound(0);
            
            //폭발 이펙트 생성
            GameObject effect = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
            Destroy(effect, 1f);

            Destroy(collision.gameObject); //레이저 파괴
            Destroy(gameObject);
        }
    }
}

 

사운드매니저 스크립트 수정

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

//사운드 매니저
public class SoundManager : MonoBehaviour
{
    //사운드 재생기 (오디오 소스) 참조
    public AudioSource audioSource;

    //재생 사운드 리스트
    public AudioClip[] audioClips;

    public void PlaySound(int type)
    {
        //오디오 재생기에 사운드를 설정하고
        audioSource.clip = audioClips[type];
        //사운드를 재생함
        audioSource.Play();
    }
}

 

9. 비행기 하나 더 추가

Create Empty -> 비행기 자식으로 넣기 -> Collider 삭제 -> 프리팹으로 만들기

 

10. 발포위치

Create Empty -> FireSpawnPos Position 0,0,-1-> 효과 자식 Position 0,0,0.8 으로 넣기

11. 사운드매니저에 효과 추가

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

public class EnemyCollsion : MonoBehaviour
{
    //폭발 이펙트 참조
    public GameObject explosionPrefab;

    //오디오 소스 참조 (소리 재생기 참조) -> 미리 접근이 안되기 때문에 인스펙터에 노출 안되게 함
    private SoundManager soundManager;

    //재생할 사운드 번호
    public int soundNum;

    private void Start()
    {
        //프리팹은 게임 오브젝트를 참조할 수 없기 때문에 GetComponent 써서 코드로 참조
        //게임 오브젝트를 동적으로 검색함
        // -> GameObject.Find("게임오브젝트이름");
        GameObject soundGameObject = GameObject.Find("SoundManager");
        soundManager = soundGameObject.GetComponent<SoundManager>();

    }

    //오디오 클립 (소리 파일 참조)
    // public AudioClip audioClip;

    private void OnTriggerEnter(Collider collision)
    {
        if (collision.tag == "PlayerLaser")
        {
            //현재 오디오 소스에 설정된 클립을 재생 중이 아니라면
            //오디오 소스에 설정된 오디오 클립을 재생함
            soundManager.PlaySound(soundNum);
            
            //폭발 이펙트 생성
            GameObject effect = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
            Destroy(effect, 1f);

            Destroy(collision.gameObject); //레이저 파괴
            Destroy(gameObject);
        }
    }
}

 

사운드매니저에 1 설정

 

12. 이동하기

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

public class SideMove : MonoBehaviour
{
    public Vector4 boundBox; // 이동 제한 영역

    public float rotSpeed; //회전속도
    public float sideMoveSpeed; //옆으로 이동 속도
    public float sideMaxMoveSpeed; //옆으로 이동 최대 속도
    public float smoothValue; //보간 수치

    public Vector3 direction; //이동 방향
    public float directionMoveSpeed; //직성 이동 속도

    public Vector2 startDelayTime; //시작 지연 시간(x:최소, y:최대)
    public Vector2 sideMoveTime; // 사이드 이동 시간(x:최소, y:최대)
    public Vector2 directMoveTime; //직선 이동 시간(x:최소, y:최대)

    public Rigidbody rigidbody3d; //물리 엔지 컴포넌트 참조

    // Start is called before the first frame update
    void Start()
    {
        //기본 하강 속도
        rigidbody3d.velocity = direction * directionMoveSpeed;
        directionMoveSpeed = rigidbody3d.velocity.z;

        StartCoroutine("TimeMoveCoroutine");
    }


    //코루틴 사용
    IEnumerator TimeMoveCoroutine()
    {
        //시작 시 일정 시간동안을 수직 하강하도록 지연함
        yield return new WaitForSeconds(Random.Range(startDelayTime.x, startDelayTime.y));

        while (true)
        {
            //수평 이동 랜덤 속도를 설정 (좌 -> 우, 우 -> 좌)
            sideMoveSpeed = Random.Range(1, sideMaxMoveSpeed) * -Mathf.Sign(transform.position.x);

            // 속도도 잘 적용되네요

            //수평 이동을 수행하는 동안 지연함
            yield return new WaitForSeconds(Random.Range(sideMoveTime.x, sideMoveTime.y));

            sideMoveSpeed = 0;

            //수직 하강하도록 일정 시간 지연함
            yield return new WaitForSeconds(Random.Range(directMoveTime.x, directMoveTime.y));
        }
    }

    
    void FixedUpdate()
    {
        float newSideSpeed = Mathf.MoveTowards(rigidbody3d.velocity.x, sideMoveSpeed, smoothValue * Time.fixedDeltaTime);

        //보간된 수평 이동 속도와 설정된 수직 이동 속도를 물리엔진 컴포넌트에 속도에 적용함 
        rigidbody3d.velocity = new Vector3(newSideSpeed, 0f, directionMoveSpeed);

        transform.position = new Vector3(
            Mathf.Clamp(transform.position.x, boundBox.x, boundBox.y),
            0f,
            Mathf.Clamp(transform.position.z, boundBox.z, boundBox.w)
        );

        //수평 이동 시 기체 회전 처리
        transform.rotation = Quaternion.Euler(0f, 0f, rigidbody3d.velocity.x * -rotSpeed);
    }
}

 

13. 적기 생성기 

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

public class EnemyGenerator : MonoBehaviour
{
    //적기(운석, 적비행기) 프리팹 참조
    public GameObject[] enemyPrefabs;

    public float genDelayTime;

    public Vector3 genSetPosition;

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine("EnemyGenCoroutine");
    }

    IEnumerator EnemyGenCoroutine()
    {
        while (true)
        {
            GameObject enemyPrefab = enemyPrefabs[Random.Range(0, enemyPrefabs.Length)];

            Vector3 genPos = new Vector3(
                Random.Range(-genSetPosition.x, genSetPosition.x),
                genSetPosition.y, genSetPosition.z
            );

            Instantiate(enemyPrefab, genPos, Quaternion.identity);

            yield return new WaitForSeconds(genDelayTime);
        }
    }
}

Add Tag -> Enemy 

 

14. 비행기 충돌 효과

Box Collider 2개 생성

C# Script -> 이름 바꾸기 PlayerShipCollider -> ExplosionPlayer 효과 프리팹 드래그&드롭 -> 사운드 번호 2

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

public class PlayerShipCollsion : MonoBehaviour
{
    // 폭발 이펙트 참조
    public GameObject explosionPrefab;

    // 오디오 소스 참조 (소리 재생기 참조)
    private SoundManager soundManager;

    // 재생할 사운드 번호
    public int soundNum;

    private void Start()
    {
        // * 프리팹에서는 미리 생성 설정된 게임오브젝트를 참조 할 수 없음
        // 이럴 경우 프리팹이 생성될때 동적 참조를 수행해야 함
        
        // 게임 오브젝트를 동적으로 검색함
        // -> GameObject 게임오브젝트참조 = GameObject.Find("게임오브젝트이름");
        // -> 참조할컴포넌트타입 컴포넌트 참조변수 = 게임오브젝트참조.GetComponent<참조할컴포넌트타입>()
        GameObject soundGameObject = GameObject.Find("SoundManager");
        soundManager =soundGameObject.GetComponent<SoundManager>();
    }

    private void OnTriggerEnter(Collider collision)
    {
        if (collision.tag == "Enemy")
        {
            // 현재 오디오 소스에 설정된 클립을 재생 중이 아니라면
            // 오디오 소스에 설정된 오디오 클립을 재생함
            soundManager.PlaySound(soundNum);

            // 폭발 이펙트 생성
            GameObject effect = Instantiate(explosionPrefab, transform.position, Quaternion.identity);
            Destroy(effect, 1f);

            Destroy(collision.gameObject); // 레이저 파괴
            Destroy(gameObject);
        }
    }
}

 

15. 사운드 효과 추가

SoundManager -> Size 3 -> Element2 에 explosion_player 음향 추가

16. 총알 3발 나가기

PlayerShip 클릭 -> Create Empty -> 이름 바꾸기 SpawnPos -> 위치 조절

정면

측면

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

public class ShipFire : MonoBehaviour
{
    //레이저 프리팹
    public GameObject laserPrefab;

    //발포 위치 참조
    public Transform[] spawnTransform;

    public float fireDelayTime; // 발포 지연 시간

    private float fireTime; // 발포 시간

   
    // Update is called once per frame
    void Update()
    {
        //Debug.Log("Time.time : " + Time.time);
        //Time.time : 실행 후 경과된 시간값

        //왼쪽 컨트롤 키를 누르고 다음 발포시간을 경과시간이 넘겼다면
        if (Input.GetKeyDown(KeyCode.LeftControl) && (Time.time > fireTime))
        {
            //현재 경과된 시간에 지연시간을 가산하여 다음 발포 시간을 설정
            fireTime = Time.time + fireDelayTime;

            for (int i=0; i<spawnTransform.Length; i++)
            {
                Instantiate(laserPrefab, spawnTransform[i].position, spawnTransform[i].rotation);
            }
            
        }
    }
}

SpawnPos 3개를 차례로 드래그&드롭

레이저 방향 스크립트 수정

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

public class DirectionMovement : MonoBehaviour
{
    public Vector3 direction; // 이동 방향

    public float moveSpeed; // 이동 속도

    public Rigidbody rigidbody3d; // 물리 엔진 컴포넌트 참조

    public bool isSelfDirection;

    // Start is called before the first frame update
    void Start()
    {
        if (isSelfDirection)
        {
            // 본인의 회전이 적용된 상태의 z+ 방향으로 이동함
            rigidbody3d.velocity = transform.forward * moveSpeed;
        }
        else
        {
            // 지정한 방향으로 이동속도를 설정함
            rigidbody3d.velocity = direction * moveSpeed;
        }
    }

}

Direction Movement Move Speed 20 설정 

게임 화면 ㅎㅎㅎ

 

'Unity > 3D 비행기 게임' 카테고리의 다른 글

[유니티] 아이템+점수판 추가  (0) 2021.05.13
[유니티] 3D 비행기 게임 만들기  (0) 2021.05.06

댓글