하참이의 아이디어노트

Unity 강의 3일차 (1) - 피자 날리기 게임 1 본문

Unity/Unity 기초

Unity 강의 3일차 (1) - 피자 날리기 게임 1

하참이 2025. 1. 17. 00:39

본 강의는 다음 문서를 참고하여 제작하였습니다. 자세한 내용은 하단 링크를 참조하시거나 댓글로 질문 남겨주시면 성심성의껏 답변 드리겠습니다.

 

https://learn.unity.com/tutorial/2-1gang-peulreieo-wici-jijeong?uv=2021.3&pathwayId=63ca4663edbc2a7be103183f&missionId=62ceb5c2edbc2a08dbf5f531&projectId=63c74056edbc2a4df1bc02f7#

 

2.1강 - 플레이어 위치 지정 - Unity Learn

개요: 이 단원에서는 먼저 두 번째 프로토타입이 될 새 프로젝트를 생성하고 기본 플레이어 동작을 구현합니다. 우선 원하는 캐릭터, 상호 작용할 동물 유형, 해당 동물에게 줄 먹이를 선택합니

learn.unity.com

 


 

 

상단 링크에서 제공하는 프로토타입 패키지를 다운 받고 임포트 후에 진행합니다.

 

 

 

 

window layout을 2 by 3로 설정해두는 것을 추천합니다.

 

Scenes 폴더에 들어가 Prototype2 씬을 실행합니다. SampleScene을 삭제해두는 것을 추천드립니다.

 

 

 

 

사람 1명과 동물 3마리를 배치해봅시다.

 

사람 에셋은 Assets > Course Library > Humans에 있습니다. 원하는 사람을 하나 배치해봅시다.

 

 

 

 

동물은 Assets > Course Library > Animals에 있습니다. 저는 Farm 에 있는 동물들로 하겠습니다.

 

 

 

 

 

 

너무 쉽네요. 사람을 움직이게 만들어볼까요?

 

 

Assets 폴더에 Scripts 폴더를 생성하고 Scripts 폴더에 PlayerController 스크립트를 생성합니다.

 

 

 

 

 

 

코드를 다음과 같이 수정하겠습니다.

 

 

 

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

public class PlayerController : MonoBehaviour
{
    public float horizontalInput;
    public float speed = 10.0f;

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

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);
    }
}

 

 

 

 

이제 캐릭터를 움직이는 것에 대해선 도가 텄다구요! 안보고도 만들 수 있어요!

 

 

 

좋습니다! 그럼 약간의 디테일만 추가해보도록 하죠.

 

플레이어가 화면을 이탈하는 문제가 있으니 그것을 막아보도록 합시다.

 

다음과 같이 코드를 입력하여 좌우 이탈을 방지해봅니다.

 

 

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

public class PlayerController : MonoBehaviour
{
    public float horizontalInput;
    public float speed = 10.0f;
    public float xRange = 10;

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

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);

        if (transform.position.x < -xRange)
        {
            transform.position = new Vector3(-xRange, transform.position.y, transform.position.z);
        }
        if (transform.position.x > xRange)
        {
            transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
        }
    }
}

 

 

마지막으로 해당 스크립트 컴포넌트를 플레이어에게 부착합니다.

 

캐릭터가 좌우로 움직이는 것을 확인하실 수 있습니다.

 

 

 

이제 저희는 동물들에게 피자를 날라가게 할 것 입니다. 피자는 플레이어의 입력을 받아 생성되면 앞으로 날라가고, 동물에게 닿으면 사라지게 만들어야 합니다.

 

 

벌써 해야할 것들이 많아보이지만 대부분이 배웠던 것들 입니다. 우선 생성되면 날라가는것 부터 해볼까요?

 

 

피자 에셋을 씬 뷰로 드래그 해 가져옵니다. 피자는 Course Library의 Food에 있습니다.

 

 

 

 새 스크립트 MoveForward를 생성하고 다음과 같이 작성합니다.

 

 

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

public class MoveForward : MonoBehaviour
{
    public float speed = 40.0f;

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

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Vector3.forward * Time.deltaTime * speed);
    }
}

 

 

 

기존에 만들던 것과 너무 유사합니다. 키 입력을 받지 않고, 생성되면 그저 앞으로 날라가는 것에 유의합니다.

 

 

다음으로는, 피자가 게임에서 생성되게 만들어야합니다. 누를때마다 똑같은 피자가 여러개 생성되어야 합니다. 뭔가가 떠오르십니까?

 

저희는 오랜만에 '프리팹'이란 것을 사용할 것 입니다! 피자를 프리팹으로 만들어놓으면 매번 똑같은 피자를 찍어내듯이 생성해낼 수 있을 것 입니다.

 

 

우선 스크립트 컴포넌트를 피자에 붙이고, 프리팹 폴더를 만든 뒤, 드래그 해서 프리팹을 생성합시다.

 

 

 

기존에 프리팹으로 만들어 두었던 에셋이기에 이런 창이 드네요. 파일을 바꿀 일은 없을 것 같으니 Original Prefab으로 생성합니다.

 

 

생성이 완료되었으면 씬에 있던 Food_Pizza를 지웁니다.

 

 

 

이제 키보드 입력을 받으면 피자가 날아가게 해봅시다.

 

 

 Playercontroller를 다음과 같이 수정합니다.

 

 

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

public class PlayerController : MonoBehaviour
{
    public float horizontalInput;
    public float speed = 10.0f;
    public float xRange = 10;

    public GameObject projectilePrefab;

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

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);

        if (transform.position.x < -xRange)
        {
            transform.position = new Vector3(-xRange, transform.position.y, transform.position.z);
        }
        if (transform.position.x > xRange)
        {
            transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
        }
    }
}

 

 

이번엔 새로운 것들이 생겼네요.

 

Input에서 저희는 GetAxis를 받았던 기억이 있습니다. 이번엔 GetKeyDown이네요. GetKeyDown 함수는 KeyCode 열거형을 받아 원하는 키 입력 이벤트를 확인할 수 있습니다.

 

Instantiate 함수는 게임 오브젝트를 씬에 생성하는 유니티 함수입니다. 첫번째 인자로는 생성할 게임 오브젝트를 받습니다. 두번째 인자로는 생성할 위치를 받습니다. 세번째 인자로는 생성시 방향을 받습니다. 각각 피자, 플레이어의 위치, 피자프리팹의 방향을 인자로 사용할 것 입니다.

 

 

 

 

이제 플레이어 프리팹에 projectilePrefab 프로퍼티가 생긴 것을 확인할 수 있습니다.

 

 

 

 

 

 

ProjectilePrefab에 피자 프리팹을 드래그합니다.

 

게임을 실행하고 스페이스바를 누르면 플레이어의 위치에서 피자가 날라가는 것을 확인할 수 있습니다.

 

 

 


 

 

 

벌써 슈팅게임의 기초가 끝났습니다! 총을 날리는 것보다 피자를 날리니 좀 더 게임이 귀엽고 상상력이 자극되는 느낌이 듭니다.

 

3일차도 화이팅입니다.