본문 바로가기
Development/C#

[멋쟁이사자처럼 부트캠프 TIL 회고] Unity 게임 개발 3기 6일차

by Mobics 2024. 11. 26.

 

목차


    Rotation (회전)

    오일러 회전 (Euler Rotation)

    : 순서대로 하나의 축씩 회전 --> 0 ~ 360도로 표시하여 사람이 알아보기 쉬움

     

    ※ 오일러 회전의 문제점 --> 짐벌락 : 축이 회전하다가 다른 축과 겹치면 두 축이 합쳐졌다고 생각하여 어떤 축이 회전 중인지 구분할 수 없게 되는 현상, 축이 잠겨서 계산을 멈추게 된다.

    출처 : https://hub1234.tistory.com/21

    쿼터니언 회전 (Quaternion Rotation)

    : 가상의 축을 기반으로 세 축이 동시에 회전 --> 사람이 알아보기 힘든 회전값을 사용

     

    ※ Unity에서 보는 법

     

    Code로 Rotation값 넣기

    : 오일러 회전 방식으로 작성한 다음 쿼터니언 회전 방식으로 변환하여 입력

    오일러 <-> 쿼터니언 변환

    public float rot = 30f;
    
    void Start()
    {
    	Vector3 newRotation = new Vector3(0, rot, 0);
     
    	// 원하는 각도로 회전을 바꾸는 코드
    	transform.rotation = Quaternion.Euler(newRotation); // 오일러 --> 쿼터니언 변환
     
    	Debug.Log(transform.rotation.eulerAngles); // 쿼터니언 --> 오일러 변환
    }

     

    Transform의 위치, 회전, 크기를 Reset하는 코드

    // 자기 자신의 위치를 0, 0, 0으로 이동하는 코드
    transform.position = Vector3.zero;
    
    // 자기 자신의 회전을 0, 0, 0으로 바꾸는 코드
    transform.rotation = Quaternion.identity;
    
    // 자기 자신의 크기를 1, 1, 1로 바꾸는 코드
    transform.localScale = Vector3.one;

     

    Rotate

    : 특정 축으로 회전 (자전)

    RotateAround

    : 대상을 기준으로 회전 (공전)

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class RotationTarget : MonoBehaviour
    {
        public Transform target;
    
        public float rotSpeed, rotAroundSpeed = 0f; // 동시에 선언 가능
    
        void Update()
        {
            // Rotate --> 자전
            transform.Rotate(Vector3.up, rotSpeed * Time.deltaTime);
    
            // RotateAround --> 공전
            transform.RotateAround(target.position, Vector3.up, rotAroundSpeed * Time.deltaTime);
        }
    }

     

    ※ 축을 Unity에서 만들 때, 모양이나 형체가 없는 빈 게임 오브젝트를 Scene 상에 아이콘을 달아서 보이게 하기

     

    ※ 아이콘 크기 조절

     

    [예제] 3차원에서 태양계 회전

    : 태양계 리소스

    https://assetstore.unity.com/packages/3d/environments/planets-of-the-solar-system-3d-90219

     

    Planets of the Solar System 3D | 3D 주변환경 | Unity Asset Store

    Elevate your workflow with the Planets of the Solar System 3D asset from Evgenii Nikolskii. Find this & other 주변환경 options on the Unity Asset Store.

    assetstore.unity.com

     

    ※ Asset으로 받은 파일이 깨졌을 때 --> URP형식이 아니라 Built-in 방식을 사용하기 때문에 깨짐

     

    ※ 태양 색상 변경

     

    ※ 팔로우 포커스 : 움직이는 물체를 카메라가 따라가는 기능 --> 단축키 : Shift + F

    LookAt

    : 특정 방향을 바라보는 기능

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class CharacterMovement : MonoBehaviour
    {
        public float moveSpeed = 5f;
    
        public Transform target;
    
        void Update()
        {
            float h = Input.GetAxis("Horizontal");
            float v = Input.GetAxis("Vertical");
    
            Vector3 dir = new Vector3(h, 0, v).normalized;
    
            transform.position += moveSpeed * Time.deltaTime * dir;
    
            if (h != 0 || v != 0) // h나 v나 아무 키나 하나는 누른 상태
            {
                // 캐릭터가 이동하려는 방향을 바라보게 하는 코드
                Vector3 targetPos = transform.position + dir; // 목표 위치
                transform.LookAt(targetPos); // 목표 위치를 바라보는 코드
            }
        }
    }

    Collider

    : 충돌이나 감지를 선택적으로 하는 Component --> 충돌과 감지를 위해서는 Collider + Rigidbody가 필요

    : 충돌하든 감지하든 Collision은 두 물체가 전부 가지고 있어야 함

    Collider의 종류

     

    Game Object에 있는 Collider 보기 --> 연두색 선이 Collider

    Collider 크기 바꾸기 (Reset 가능)

    Code로 Collision Event, Trigger Event 확인하기

    충돌과 감지

    • 충돌 : Collision Event
    • 감지 : Trigger Event

     

    ※ Event의 3단계

     

    OnCollision

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class CollisionEvent : MonoBehaviour
    {
        public void OnCollisionEnter(Collision collision)
        {
            Debug.Log("Collision Enter");
        }
    
        public void OnCollisionStay(Collision collision)
        {
            Debug.Log("Collision Stay");
        }
    
        public void OnCollisionExit(Collision collision)
        {
            Debug.Log("Collision Exit");
        }
    
    }

    OnTrigger

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class TriggerEvent : MonoBehaviour
    {
        public void OnTriggerEnter(Collider other)
        {
            Debug.Log("Trigger Enter");
        }
    
        public void OnTriggerStay(Collider other)
        {
            Debug.Log("Trigger Stay");
        }
    
        public void OnTriggerExit(Collider other)
        {
            Debug.Log("Trigger Exit");
        }
    
    }

    Rigidbody

    : 물리 계산을 하는 Component (중력, 속도, 가속도, 저항 등등)

    >> 충돌하든 감지하든 두 물체 중 하나는 Rigidbody를 가지고 있어야 함 --> 보통 움직이는 동적 물체나 일시적이지 않고 오래 유지하는 존재가 갖고 있으며, 둘다 갖고 있어도 상관 없다. 그러나 정적 물체가 Rigidbody를 갖고 있으면 연산이 한번 더 작용된다.

    ※ Collider는 영역 / Rigidbody는 계산 --> 둘은 뗄레야 뗄 수 없는 관계

     

    Rigidbody 추가하기

    중력 추가