개발/유니티(UNITY)

5-2 유니티로 화살 피하기 게임 만들기

새벽감성개발자 2023. 10. 26. 15:00
반응형

5.4 키를 조작해 플레이어 움직이기

5.4.1 플레이어 스크립트 작성하기

PlayerController

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

public class PlayerController : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Application.targetFrameRate = 60;
    }

    // Update is called once per frame
    void Update()
    {
        // 왼쪽 화살표가 눌린 경우
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            transform.Translate(-3, 0, 0); // 왼쪽으로 3 움직인다.
        }
        if (Input.GetKeyDown(KeyCode.RightArrow)) {
            transform.Translate(3, 0, 0); // 오른쪽으로 3 움직인다.
        }
    }
}

 

5.5 Physics를 사용하지 않고 화살 떨어뜨리기

5.5.1 화살 떨어뜨리기

  • 유니티에 내장된 Physics 기능을 사용하면 유니티가 중력을 계산해주기 때문에, 스크립트를 사용하지 않고 화살을 떨어뜨리는게 가능하다.
  • Physics를 사용하면 직접적인 움직임(정밀한 표현)을 처리하기 어려움

화살표 position 0 3.2 0 / OrderLayer 1

5.5.2 화살 스크립트 작성하기

ArrowController

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

public class ArrowController : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        // 프레임 마다 등속으로 낙하시킨다.
        transform.Translate(0, -0.1f, 0);

        // 화면 밖으로 나오면 오브젝트를 소멸시킨다.
        if (transform.position.y < -5.0f)
        {
            Destroy(gameObject);
        }
    }
}

 

  • 화살이 보이지 않는 곳에서 계속 떨어지면, 메모리가 낭비됨
  • 화살이 화면 밖으로 나가면 오브젝트를 소멸시키는 스크립트를 작성해준다.

 

 

5.6 충돌 판정하기

5.6.1 충돌 판정

  • 오브젝트끼리 충돌하는지 항상 감시하고 충돌하면 특정한 처리를 한다.
  • 충돌 판정 : 충돌을 감지하는 부분
  • 충돌 반응 : 충돌을 감지한 다음의 움직임을 정하는 부분

 

5.6.2 간단한 충돌 판정

  • 오브젝트의 형상을 단순하게 원형이라 가정하면, 원의 중심 좌표와 반경을 알면 충돌 판정을 간단히 할 수 있다.

ArrowController에서 수정을 한다.

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

public class ArrowController : MonoBehaviour
{

    GameObject player;

    // Start is called before the first frame update
    void Start()
    {
        this.player = GameObject.Find("player");
    }

    // Update is called once per frame
    void Update()
    {
        // 프레임 마다 등속으로 낙하시킨다.
        transform.Translate(0, -0.1f, 0);

        // 화면 밖으로 나오면 오브젝트를 소멸시킨다.
        if (transform.position.y < -5.0f)
        {
            Destroy(gameObject);
        }

        // 충돌 판정
        Vector2 dir = transform.position - this.player.transform.position;
        float d = dir.magnitude;
        float arrowRange = 0.5f;
        float playerRange = 1.0f;

        if (d < arrowRange + playerRange)
        {
            // 충돌한 경우는 화살을 지운다.
            Destroy(gameObject);
        }
    }
}

 

반응형