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

2021. 3. 16. 13:59·◼ IT Etc./Unity
반응형

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

 

이 글은 케이티 님의 '유니티 입문 강좌 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 - 트랜스폼' 강의 영상

 

반응형

'◼ IT Etc. > Unity' 카테고리의 다른 글

[Unity] 유니티 (Unity) 소개 및 설치  (0) 2023.01.23
[유니티 기초] #3. 간단한 2D UI 구현 - 텍스트 추가 및 버튼으로 화면 전환(이동)하기 (SceneManager.LoadScene)  (0) 2021.03.26
[유니티 기초] #2. 리지드 바디 (RigidBody) 기능 정리  (0) 2021.03.22
'◼ IT Etc./Unity' 카테고리의 다른 글
  • [Unity] 유니티 (Unity) 소개 및 설치
  • [유니티 기초] #3. 간단한 2D UI 구현 - 텍스트 추가 및 버튼으로 화면 전환(이동)하기 (SceneManager.LoadScene)
  • [유니티 기초] #2. 리지드 바디 (RigidBody) 기능 정리
SangYoonLee (SYL)
SangYoonLee (SYL)
Slow, But Steady Wins The Race 😎
    반응형
  • SangYoonLee (SYL)
    ◆ Slow, But Steady ◆
    SangYoonLee (SYL)
  • 전체
    오늘
    어제
    • ◻ 전체 글 수 : (132) N
      • ✪ 취미, 경험 회고 및 일상 (26)
        • [취미] Room Escape (2)
        • [회고] IT 관련 경험 회고 (18)
        • [일상] 일상 생각 (4)
        • [일상] 독후감 (1)
      • ◼ FrontEnd (30) N
        • Web & HTML, CSS (9) N
        • JavaScript (4)
        • TypeScript (1)
        • ReactJS (16)
      • ◼ CS (3)
        • 자료구조 & 알고리즘 (1)
        • 컴퓨터 구조 (1)
        • 운영체제 (1)
      • ◼ PS Note (40)
        • 백준 (38)
        • 프로그래머스 (2)
      • ◼ IT Etc. (33)
        • (Until 2021) (21)
        • Python (6)
        • C | C# | C++ (1)
        • Git (1)
        • Unity (4)
        • Game Dev. (0)
  • 블로그 메뉴

    • 홈
    • 💻 GitHub
    • 🟢 Velog
    • 🧩 온라인 방탈출 출시 작품 모음
  • 링크

    • GitHub
  • 공지사항

  • 인기 글

  • 태그

    소수 구하기
    리엑트
    JavaScript
    Component
    React
    C++
    unity
    wecode
    프로그래머스
    주간 회고
    유니티
    코딩 일기
    Cpp
    pygame
    코드숨
    개인 프로젝트
    위코드
    더라비린스
    미궁 게임
    백준
    관심사의 분리
    1929
    알고리즘
    회고
    Python
    파이썬
    프로젝트
    방탈출고사
    후기
    CodeSoom
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
SangYoonLee (SYL)
[유니티 기초] #1. 트랜스폼(transform) 컴포넌트 기본 메소드 코드 정리 (C#)
상단으로

티스토리툴바