Vector3.ProjectOnPlane

jkjkbk·2023년 4월 24일
0

Unity

목록 보기
4/16
post-thumbnail

Vector3.ProjectOnPlane

Declaration

public static Vector3 ProjectOnPlane(Vector3 vector, Vector3 planeNormal);

Parameters

Vector3 vector

사상시킬 벡터

Vector3 planeNormal

사상 기준이되는 평면의 normal

Returns

원점(0, 0, 0)을 지나고 방향이 planeNormal인 평면에 vector를 사상하여 이 평면에 존재하는 벡터를 반환

vector를 방향 벡터가 아닌 점(위치) 벡터로 사용하여 사상된 점(위치) 벡터를 구하려는 경우, A의 위치가 원점(0, 0, 0)이 아니라면 추가 연산이 필요함

Example

오브젝트 A, B가 있을 때,
A의 up 벡터를 normal로 하는 평면과 B의 수직거리는?

1. 방법

: Vector3.ProjectOnPlane를 이용하여 점 M을 구하고 길이 L만큼 normal 벡터 방향으로 M을 이동시킨 P를 구한다.
(L은 + 혹은 - 값이 될 수 있으므로 M이 -normal이나 +normal로 이동 가능함)

2. 코드

// 점에서 평면까지의 수직거리

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

public class GetDistancePointToPlaneTest : MonoBehaviour
{
    public Transform Target;
    private float distance;

    void Update()
    {
        distance =  GetDistancePointToPlane(transform.up, transform.position, Target.position);
        Debug.DrawRay(transform.position, transform.up * distance, Color.red);

    }

    /// <summary>
    /// 점에서 평면까지의 거리. 점이 평면의 normal 벡터를 기준으로 평면보다 위에 있으면 +, 평면 아래에 있으면 -
    /// </summary>
    float GetDistancePointToPlane(Vector3 planeNormal, Vector3 A, Vector3 B)
    {
        float L = Vector3.Dot(A, planeNormal);
        Vector3 M = Vector3.ProjectOnPlane(B, planeNormal);
        Vector3 P = M + planeNormal * L;
        // Debug.Log($"L : {L}, M : {M}, P : {P}");

        float LofPB = Vector3.Dot(B-P, planeNormal);

        return LofPB;
    }
}

0개의 댓글