개발일지/Unity 6 [미제]

[Unity 6 - 프로젝트] 3D 캐릭터 이동 및 애니메이션 구현

서니션 2024. 10. 23. 15:03

1. 캐릭터 에셋 가져오기

자신이 캐릭터로 사용하고 싶은 3D 에셋을 프로젝트에 임포트 한다.

에셋에 애니메이션이 이미 있다면 기본 프리팹에 애니메이터와 리지드바디 컴포넌트가 이미 있을 것이다.

 

 


2. 이동 및 애니메이션 구현

내 캐릭터는 3D이기 때문에, 상하좌우는 물론이고 대각선으로도 움직여야 한다.

이를 위한 스크립트를 작성하고, 애니메이터를 설정해보고자 한다.

 

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

public class PlayerMovement : MonoBehaviour
{
    private float speed = 2.0f; // 속도 변수
    private float h, v;

    private Animator anim;
    private Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent<Animator>();
        rb = GetComponent<Rigidbody>(); // Rigidbody 컴포넌트 가져오기
        anim.SetTrigger("Idle"); // 초기 상태 설정
    }

    // Update is called once per frame
    void Update()
    {
        // 키보드 입력을 실시간으로 처리
        h = Input.GetAxis("Horizontal");
        v = Input.GetAxis("Vertical");
    }

    private void FixedUpdate()
    {
        // 이동 방향 및 속도 계산 (단일 계산 후 재사용)
        Vector3 movement = new Vector3(h, 0, v).normalized;
        float movementSpeed = movement.magnitude;

        // 애니메이션 속도 업데이트
        anim.SetFloat("Speed", movementSpeed);

        // 캐릭터 회전 및 이동 처리
        if (movementSpeed > 0.1f) // 이동 시에만 회전 및 이동 처리
        {
            // 회전 처리 (Slerp 사용해 부드럽게)
            Quaternion newRotation = Quaternion.LookRotation(movement);
            rb.MoveRotation(Quaternion.Slerp(transform.rotation, newRotation, 0.2f));

            // Rigidbody를 사용한 이동 처리
            rb.MovePosition(transform.position + movement * speed * Time.fixedDeltaTime);
        }
        else
        {
            // 멈출 때 Idle 애니메이션 상태 유지
            anim.SetTrigger("Idle");
        }
    }
}

 

하나의 애니메이션이 다 진행된 후 실행하는 것은 걷는 모션에서는 어색하다. 

(나는 멈췄는데 아직 제자리 걸음..~)

그래서 Has Exit Time을 체크 해제하고,

Conditions에 애니메이션이 발동되는 조건 Speed 파라미터를 추가하여 설정해주었다.

 


3. 결과

잘 돌아다닌다 ㅎㅎ