레트로의 유니티 게임 프로그래밍 에센스 - 4.6

Cosmos·2023년 3월 30일
0

학습 매체 : 책

책이름 : 레트로의 유니티 게임 프로그래밍 에센스

저자 : 이제민


본 내용은 해당 강의 내용을 공부하면서 정리한 글입니다.


4.6 메서드 연습하기


  • 두 점 사이의 거리를 계산하는 메서드 만들어보기

4.6.1 두 점 사이의 거리

  • 평면의 두 점 ( x1 , y1 )과 ( x2, y2 ) 사이의 거리 distance를 구하는 방법을 알아보자.

  • 두 점 사이의 거리를 구할 때, 두 점이 포함된 직각삼각형을 만든다.

  • 밑변 : width = x2 - x1

  • 높이 : height = y2 - y1

  • 빗변(거리) : distance =

  • 계산된 빗변 사이의 거리가 두 점 사이의 거리가 된다. 이를 코드로 구현하자.


4.6.2 GetDistance( ) 메서드 만들기

  • HelloCode 스크립트의 Start( ) 메서드에서 이전까지의 내용을 지우고, 다음과 같이 두 점 사이의 거리를 계산하는 코드를 작성한다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloCode : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        float distance = GetDistance(2, 2, 5, 6);
        Debug.Log("(2,2)에서 (5,6)까지의 거리 : " + distance);
    }

    float GetDistance(float x1, float y1, float x2, float y2)
    {
        float width = x2 - x1;
        float height = y2 - y1;

        float distance = width * width + height * height;
        distance= Mathf.Sqrt(distance);

        return distance;
    }
}
  • 플레이 버튼을 눌러서 콘솔 창을 확인하면 점 (2,2)에서 점 (5,6)까지의 거리가 출력된다. 확인했다면 플레이 버튼을 다시 눌러 해제하자.


4.6.3 GetDistance( ) 메서드 만드는 과정

  • 먼저 기존 Start( ) 메서드의 내용을 전부 지우고, 새로운 메서드 GetDistance( )를 선언한다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

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

    }

    float GetDistance(float x1, float y1, float x2, float y2)
    {

    }
}
  • GetDistance( ) 메서드는 입력으로 두 점의 위치 (x1, y1)과 (x2, y2)를 받고 출력으로 두 점 사이의 거리를 반환한다.

  • GetDistance( ) 메서드는 입력받은 두 점으로 만든 직각삼각형의 밑변과 높이를 저장할 변수 width와 height를 필요로 한다.

  • 밑변 width는 x2 - x1, 높이 height는 y2 - y1으로 계산한다.

    float GetDistance(float x1, float y1, float x2, float y2)
    {
		float width = x2 - x1;
        float height = y2 - y1;
    }
  • 계산된 거리를 저장할 변수 distance를 선언한다. distance의 값은 밑변의 제곱과 높이의 제곱을 더한 값에 제곱근을 취한 값이다.
    float GetDistance(float x1, float y1, float x2, float y2)
    {
		float width = x2 - x1;
        float height = y2 - y1;
        
        float distance = width * width + height * height;
    }
  • C#에서 곱셈은 * 연산자를 사용한다. 일단 distance에 밑변의 제곱과 높이의 제곱을 더한 값을 저장했다. 아직 제곱근을 구하기 전이다.

  • 이제 width width + height height의 제곱근을 구한다. 그런데 제곱근을 구하는 절차는 코드 몇 줄로는 표현하기 힘들다.

  • 그러므로 미리 만들어진 수학 메서드를 사용한다. 유니티는 수학 관련 라이브러리인 Mathf 클래스를 제공한다. Mathf에서 제공하는 Sqrt( ) 메서드는 입력값의 제곱근을 계산한다.

    float GetDistance(float x1, float y1, float x2, float y2)
    {
		float width = x2 - x1;
        float height = y2 - y1;
        
        float distance = width * width + height * height;
        distance= Mathf.Sqrt(distance);
    }
  • GetDistance( ) 메서드 내부에서 계산된 결과를 return으로 전달할 수 있게 한다.
	float GetDistance(float x1, float y1, float x2, float y2)
    {
        float width = x2 - x1;
        float height = y2 - y1;

        float distance = width * width + height * height;
        distance= Mathf.Sqrt(distance);

        return distance;
    }
  • GetDistance( ) 메서드를 완성했다.

  • 마지막으로 Start( ) 메서드에서 GetDistance( ) 메서드를 사용하여 점 (2,2)와 점 (5,6) 사이의 거리를 계산하고 콘솔에 출력한다.

	void Start()
    {
        float distance = GetDistance(2, 2, 5, 6);
        Debug.Log("(2,2)에서 (5,6)까지의 거리 : " + distance);
    }

4.6.4 스코프

  • 같은 이름의 변수를 두 개 이상 선언하면 에러가 발생한다. 나중에 distance를 사용힐 때, 두 distance 중 어떤 것을 사용하려는 건지 컴퓨터가 알 수 없기 때문이다.
	void Start()
    {
        float distance = 5;
        float distance = 15; // 에러(같은 이름의 변수 중복 선언)
    }
  • 하지만, HelloCode 스크립트 코드에서는 다음과 같이 Start( ) 메서드와 GetDistance( ) 메서드에 같은 이름의 변수 distance를 중복 선언했지만 에러가 발생하지 않았다.
public class HelloCode : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        float distance = GetDistance(2, 2, 5, 6);
        Debug.Log("(2,2)에서 (5,6)까지의 거리 : " + distance);
    }

    float GetDistance(float x1, float y1, float x2, float y2)
    {
        float width = x2 - x1;
        float height = y2 - y1;

        float distance = width * width + height * height;
        distance= Mathf.Sqrt(distance);

        return distance;
    }
}
  • 변수 distance가 서로 다른 중괄호 안에 선언되어 있기 때문이다. 코드에서 중괄호 { }는 밖에서 내부가 보이지 않게 감추는 껍데기이다. 즉, 메서드 내부에서 선언한 변수는 해당 메서드 내부에서만 유효하다.

  • 이러한 유효 범위를 스코프라고 한다. 스코프는 선언된 변수나 메서드 등이 관측되는 유효 범위이다.

  • GetDistance( ) 메서드에서 선언한 distance 변수의 스코프는 GetDistance( ) 메서드 내부에서 끝난다. 따라서 Start( ) 메서드는 GetDistance( ) 메서드 내부에 선언된 distance를 모른다.

  • 서로 스코프가 겹치지 않으므로 Start( ) 메서드에 선언된 distance와 GetDistance( ) 메서드에 선언된 distance를 구별해서 사용할 수 있다.


다음 강의에서 계속~

profile
게임 개발을 목적으로 공부하고 있는 대학생입니다.

0개의 댓글