주녘공부일지

[Unity3D] Vector3 본문

GameEngine/UnityEngine - Class

[Unity3D] Vector3

주녘 2022. 2. 21. 18:08
728x90

Vector3

3차원 벡터와 각 x, y, z 축에 따른 위치를 표현 가능한 구조체

 

namespace UnityEngine에 선언되어 있는 구조체로, 안에 선언되어 있는 함수들을 활용할 수 있음

Vector3와 일부 같은 역할을 하는 구조체를 만든 예제

struct MyVector
{
    public float x;
    public float y;
    public float z;

    
    public float magitude {  get { return Mathf.Sqrt(x * x + y * y + z * z); } } 
    public MyVector normalized { get { return new MyVector(x / magitude, y / magitude, z / magitude); } }

    public MyVector(float x, float y, float z) { this.x = x; this.y = y; this.z = z; }

    public static MyVector operator +(MyVector a, MyVector b)
    {
        return new MyVector(a.x + b.x, a.y+b.y, a.z+b.z);
    }

    public static MyVector operator -(MyVector a, MyVector b)
    {
        return new MyVector(a.x - b.x, a.y - b.y, a.z - b.z);
    }
}

void Start()
{
    MyVector to = new MyVector(10f, 0f, 0f);
    MyVector from = new MyVector(5f, 0f, 0f);
    MyVector dir = to - from; // (5f, 0f, 0f)
    
    dir = dir.normalized; // (1f, 0f, 0f)
}

magitude : 벡터의 방향의 크기 // 피타고라스 정리

normalized : 벡터의 방향 (크기가 1인 단위벡터)

728x90