UNITY/Unity Study

벡터 사이의 거리 구하기

GREEN나무 2023. 8. 19. 16:32
728x90

위치가 변할 떄

void Update(){
        // 위치 업데이트
        Vector3 pos = transform.position;
        Vector3 dis = prevPos - pos;
        playerSc.newHP -= hp * dis.magnitude;

        prevPos = pos;
    }

 

 

값이 주어질 때

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

public class Something : MonoBehaviour
{
    void Start()
    {
        float distance = GetDistence(2, 2, 5, 6);
        Debug.Log("(2,2)에서 (5,6)까지의 거리 : " + distance);
    }
    float GetDistence(float x1, float y1, float x2, float y2)
    {
        float width = x2 - x1;
        float height = y2 - y1;

        // 빗변^2 = 밑변^2 + 높이^2
        float distanceSquared = width * width + height * height;
        float distance = Mathf.Sqrt(distanceSquared);

        return distance;
    }
}

 

 

'UNITY > Unity Study' 카테고리의 다른 글

C#  (0) 2023.08.21
유니티 문법  (0) 2023.08.19
박스미는 만큼 HP 깎기  (0) 2023.08.19
Roulette  (0) 2023.08.14
플레이어 따라다니는 텍스트 만들기  (0) 2023.08.14