[Unity] Vector 이해하고 구현해보기

Yerin·2023년 7월 6일
0

Vector의 기본 연산을 간단하게 코드로 구현해보는 실습을 가졌습니다.

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


//1. 위치 벡터
//2. 방향 벡터
struct Myvector
{
    public float x;
    public float y;
    public float z;

    //          +
    //     +    +
    // +--------+
    public float magnitude { get { return Mathf.Sqrt(x*x + y*y + z*z); } }
    public Myvector normalized { get { return new Myvector( x / magnitude, y / magnitude, z / magnitude); } }
    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);
    }

    public static Myvector operator *(Myvector a, float d)
    {
        return new Myvector(a.x * d, a.y * d, a.z * d);
    }
}
public class PlayerController : MonoBehaviour
{
    [SerializeField]
    float _speed = 10.0f;
    // Start is called before the first frame update
    void Start()
    {
        Myvector to = new Myvector(10.0f, 0.0f, 0.0f);
        Myvector from = new Myvector(5.0f, 0.0f, 0.0f);
        Myvector dir = to - from; // (5.0f, 0.0f, 0.0f);

        dir = dir.normalized; // (1.0f, 0.0f, 0.0f);


        Myvector newPos = from + dir * _speed;
        // 방향 벡터
        // 1. 거리(크기)      5 
        // 2. 실제 방향       ->
    }

    // Update is called once per frame
    void Update()
    {
        // Local -> World
        // TransformDirection

        // World -> Local
        // InverseTransformDirection

        if (Input.GetKey(KeyCode.W))
            //transform.position += transform.TransformDirection(Vector3.forward * Time.deltaTime * _speed);
            //바라보고 있는 로컬을 기준으로 연산을 해줌 (위 아래 코드 동일)
            transform.Translate(Vector3.forward * Time.deltaTime * _speed);
            if (Input.GetKey(KeyCode.S))
            transform.Translate(Vector3.back * Time.deltaTime * _speed);
        if (Input.GetKey(KeyCode.A))
            transform.Translate(Vector3.left * Time.deltaTime * _speed);
        if (Input.GetKey(KeyCode.D))
            transform.Translate(Vector3.right * Time.deltaTime * _speed);
    }
}
profile
재밌는 코딩 공부

0개의 댓글