◼ IT Etc./Unity

[유니티 기초] #1. 트랜스폼(transform) 컴포넌트 기본 메소드 코드 정리 (C#)

SangYoonLee (SYL) 2021. 3. 16. 13:59
반응형

유니티에서 대표적으로 많이 쓰이는 트랜스폼의 컴포넌트를 정리해 보았습니다.

 

이 글은 케이티 님의 '유니티 입문 강좌 part 2 - 트랜스폼' 강의를 바탕으로 작성한 글입니다.

 

강의 영상은 글 제일 하단에 참고용으로 올려놨습니다.

 

 

 

 

오브젝트 이동 (값 직접 수정, Translate)

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

public class Test : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        if(Input.GetKey(KeyCode.W))
        {
            // Transform의 포지션 값 직접 수정
            this.transform.position = this.transform.position + new Vector3(0, 0, 2) * Time.deltaTime; //60분의 1
            
            // transform.Translate 이용
            this.transform.Translate(new Vector3(0, 0, 1) * Time.deltaTime);
        }
    }
}

 

  • Input.GetKey(KeyCode.W) : 키보드에서 W키를 누르면 True가 반환
  • Time.deltaTime : 한 프레임을 실행하는데 걸리는 시간 (60프레임이면 1/60초)

 

포지션 값을 직접 수정해서 오브젝트를 이동할 수도 있고 Translate 메소드로 오브젝트를 이동할 수도 있다.

 

 

 

 

 

 

오브젝트 회전 (값 직접 수정, Rotate, rotation - Quaternion이용)

오브젝트를 회전시키는 메소드

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

public class Test : MonoBehaviour
{
    Vector3 rotation;

    // 처음 1회 실행하는 내재 함수
    void Start()
    {
        rotation = this.transform.eulerAngles;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            // 오브젝트의 로테이션 값을 증가서켜 회전
            rotation = rotation + new Vector3(90, 0, 0) * Time.deltaTime;
            this.transform.eulerAngles = rotation;
            Debug.Log(transform.eulerAngles); // 오브젝트의 로테이션 값 출력

            // Rotate 매소드 이용 회전
            this.transform.Rotate(new Vector3(90, 0, 0) * Time.deltaTime);
			
            // rotation 매소드 이용 회전
            rotation = rotation + new Vector3(90, 0, 0) * Time.deltaTime;
            this.transform.rotation = Quaternion.Euler(rotation);
        }

    }
}

 

오브젝트.transform.eulerAngles : 오브젝트의 Transform의 Rotation값을 Vector3로 반환

 

 

(1) 값을 직접 수정하여 회전할 때 주의할 점

 

오브젝트의 로테이션 값을 증가시켜 회전시킬 때

 

오브젝트의 Transform의 Rotation값이 외부적인 값과 내부적인 값이 다르므로

 

새 변수(여기서는 rotation)에 현재 Rotation값을 받아서 증가시켜야 한다.

 

 

그렇지 않고 직접 this.transform.eulerAngles의 값을 직접 증가시키면 오브젝트가 90도 이상 돌지 않고 부들부들 떤다.

 

(정확한 원리는 아직 잘 모르겠다.)

 

 

유니티에서는 이런 예기치 않은 현상 떄문에 가급적 값을 직접 수정하는 것을 주의하고

 

가급적 Rotate같은 매소드를 이용하라고 한다.

 

 

 

 

(2) Quaternion을 이용하는 이유

 

오브젝트의 Transform의 Rotation값을 한 축을 90도로 고정하면 다른 두 축이 같은 방향으로 움직인다(고장난다).

 

이를 짐벌락 현상이라고 하는데 Quaternion에서는 이런 현상이 없다고 한다.

 

 

 

 

 

오브젝트 크기 조절 (localScale)

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

public class Test : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
       	    // 1초에 2배씩 오브젝트가 커지도록 설정
            this.transform.localScale = this.transform.localScale + new Vector3(2, 2, 2) * Time.deltaTime;
        }
    }
}

new Vector3(n, n, n) : 각 축의 n배만큼 오브젝트 크기를 조절한다

 

 

 

 

 

 

정규화 벡터 (forward, up, right)

수학, 물리에서의 기저 벡터 개념과 같다.

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

public class Test : MonoBehaviour
{

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            // 정규화 벡터 : 방향만을 알려주는 벡터
            // new Vector3(0, 0, 1)
            moveSpeed * this.transform.forward * Time.deltaTime;

            // new Vector3(0, 1, 0)
            moveSpeed * this.transform.up * Time.deltaTime;

            // new Vector3(1, 0, 0)
            moveSpeed * this.transform.right * Time.deltaTime;
        }

    }
}
  • moveSpeed: 해당 방향으로 얼만큼 이동할지 결정
  • forward : z축 방향
  • up : y축 방향
  • right : x축 방향

 

 

 

 

 

오브젝트가 특정 대상을 바라봄 (LookAt)

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

public class Test : MonoBehaviour
{
    [SerializeField]
    private GameObject go_camera;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            // 바라보는 대상을 카메라로 설정
            this.transform.LookAt(go_camera.transform.position);
        }
    }
}

 

go_camera 게임 오브젝트는 코드 안에선 아직 빈껍데기 이므로

유니티의 Inspector창에서 직접 바라보는 대상을 카메라로 넣어 주어야 한다.

 

Test 클래스 안에서만 go_camera 게임 오브젝트를 사용하기 위해 접근 범위를 private로 했으나

이렇게 설정하면 Inspector창에 뜨지 않으므로

[SerializeField]로 강제로 Inspector 창에 뜨도록 한다.

 

 

 

 

 

 

 

오브젝트가 특정 대상을 중심으로 회전 (RotateAround)

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

public class Test : MonoBehaviour
{
    [SerializeField]
    private GameObject go_camera;

    // Update is called once per frame
    void Update()
    {
        transform.RotateAround(go_camera.transform.position, Vector3.up, 100 * Time.deltaTime);
    }
}

transform.RotateAround(회전 중심의 좌표, 회전 방향, 회전 속도)

 

 

 

케이티 님의 ' 유니티 입문 강좌 part 2 - 트랜스폼' 강의 영상

 

반응형