유니티

[Unity] 직선의 거리 구하기

simstealer 2022. 7. 7. 09:59
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloCode : MonoBehaviour
{
    // 유니티 이벤트 메서드(상황에 맞게 자동으로 실행되는 메서드) 중 하나
    // 프로그램 시작에 자동으로 한 번 실행된다.
    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)
    { // x1, x2 = 밑변 / y1, y2 = 높이
        float width = x2 - x1;
        float height = y2 - y1;

        float distance = width * width + height * height; // 밑변과 높이에 제곱를 해주고
        distance = Mathf.Sqrt(distance); // Mathf.Sqrt() 함수로 제곱근을 구하면 끝.

        return distance;
    }
}