본문 바로가기
TIL

[멋쟁이사자처럼 부트캠프 TIL 회고] 유니티 게임개발 3기 5일차 Component, 캐릭터 이동

by HYttt 2024. 11. 25.

Component

  • component : 게임 오브젝트에 붙이는 기능

Cube의 컴포넌트 : Transform, Mesh Filter, Mesh Renderer, Box Collider

  • Transform : 게임 오브젝트의 위치, 회전, 크기정보. 모든 게임 오브젝트가 가지고 있는 컴포넌트
  • Mesh Filter : 게임 오브젝트의 모양 형태 데이터
  • Mesh Renderer : 게임 오브젝트의 메쉬를 그리는 컴포넌트

Component 접근, 추가

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class ComponentStudy : MonoBehaviour
{
    public GameObject targetObj;    //GameObject 타입의 변수 생성
    public Transform destination;   //  == GameObject.Transform
    void Start()
    {
        /*
        this.gameObject -> 자기 자신 접근
        this 생략 가능
        */
        gameObject.name = "empty object";   //자기 자신의 이름을 empty object로 변경

        this.GetComponent<MeshRenderer>().enabled = false;  //자기 자신의 MeshRender 비활성화
        gameObject.AddComponent<BoxCollider>();	//BoxCollider 컴포넌트 추가
        transform.position = destination.position;

        /*
        어떤 오브젝트가 갖고있는 컴포넌트 접근하는 방법 -> GetComponent 사용
        어떤 대상. GetComponet<컴포넌트 이름>().함수 or 변수
        */

        targetObj.name = "TargetObj";
        targetObj.GetComponent<MeshRenderer>().enabled = false;
        targetObj.GetComponent<CapsuleCollider>().enabled = false;

    }
    void OnEnable() //활성화 될 때마다 실행
    {
        transform.position += transform.forward;    // 활성화 될 때 마다 앞으로 1씩 이동
    }
}

 

캐릭터 이동

  • GetKey, GetMouseButton
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InputStudy : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W)) // W 키 누른 순간
        {
            Debug.Log("W");
        }
        
        if (Input.GetKey(KeyCode.W)) // W 키 누르는 동안
        {
            Debug.Log("W");
        }
        
        if (Input.GetKeyUp(KeyCode.W)) // W 키를 떼는 순간
        {
            Debug.Log("W");
        }

        if (Input.GetKeyDown(KeyCode.Space)) // 스페이스키
        {
            Debug.Log("Space");
        }

        if (Input.GetKeyDown(KeyCode.Return)) // 엔터키
        {
            Debug.Log("Return");
        }

        if (Input.GetMouseButtonDown(0)) // 마우스 왼쪽 버튼을 누르기 시작
        {
            Debug.Log("마우스 왼쪽 버튼을 누르기 시작");
        }

        if (Input.GetMouseButton(0))  // 마우스 왼쪽 버튼을 누르는 중
        {
            Debug.Log("마우스 왼쪽 버튼을 누르는 중");
        }
    }
}

 

  • InputManager에서 미리 만들어진 입력을 활용한 이동
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class Movement : MonoBehaviour
{
    private Transform myTransform;

    public float moveSpeed = 1f;
    void Start()
    {
        myTransform = this.transform;
    }


    void Update()
    {
        float h = Input.GetAxis("Horizontal");  //좌,우 이동
        float v = Input.GetAxis("Vertical");    //앞,뒤 이동

        Vector3 dir = new Vector3(h, 0, v).normalized;  //대각선 이동 시 크기가 1보다 커지기 때문에 normalized로 정규화
        Debug.Log(dir);

        transform.position += dir * moveSpeed * Time.deltaTime;

    }
}