쫑가 과정

2d 탑 다운 시점 캐릭터 8방향 움직임, 애니메이션 설정. 본문

Unity 따라 배우기/Topdown 2D RPG In Unity

2d 탑 다운 시점 캐릭터 8방향 움직임, 애니메이션 설정.

쫑가 2022. 2. 18. 20:33

https://www.youtube.com/watch?v=gKauseRHFRg&list=PLLtCXwcEVtulmgxqM_cA8hjIWkSNMWuie&index=3 

플레이어 움직임 설정.


코드

using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class Movement : MonoBehaviour
{
    private Rigidbody2D playerRb;
    private Animator myAnim;
    public float playerMoveSpeed;
    private void Awake()
    {
        playerRb = GetComponent<Rigidbody2D>();
        myAnim = GetComponent<Animator>();
    }

    private void FixedUpdate()
    {
        playerRb.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * playerMoveSpeed * Time.deltaTime;

        myAnim.SetFloat("MoveX", playerRb.velocity.x);
        myAnim.SetFloat("MoveY", playerRb.velocity.y);
    }
}

움직임에 Rigidbody2D.velocity를 사용했다.

https://docs.unity3d.com/kr/530/ScriptReference/Rigidbody2D-velocity.html

 

Unity - 스크립팅 API: Rigidbody2D.velocity

The velocity is specified as a vector with components in the X and Y directions (there is no Z direction in 2D physics). The value is not usually set directly but rather by using forces. The velocity can also gradually decay due to the effect of drag if th

docs.unity3d.com

 

애니메이션 설정.


1. 8방향 애니메이션 만들기.

8개 생성

2. blend Tree 만들기

행동이 많아서 하나로 묶음

3. Parameter 추가하기

X축을 감지할 float MoveX, Y축을 감지할 float MoveY 

4. blend tree Inspector 설정하기

Blend Type은 2D Simple Directional

결과

가만히 있는 모션 설정.


1. 8방향 Idle 애니메이션을 생성.

역시 8개 생성

 

2. Idle Blend Tree 생성

3. Blend Tree 세부 설정

Parameters에 마지막 방향을 저장할

float LastMoveX와 float LastMoveY를 생성

움직임 Blend Tree와 마찬가지로 설정 다른 점 Parameters는 LastMoveX와 LastMoveY로 설정.

Idle Blend Tree를 디폴트 상태로 만든다.

4. 진행 방향 생성, 설정.

1. Idle -> Move

설정.

딜레이 없이 바로 실행될 수 있도록.

Has Exit Time 체크 해제

Fixed Duration 체크 해제

Transition Duration과 Offset 0으로 설정.

Idle -> Move transition을 4개 생성한다.

아래 Conditions 인 조건에

MoveX, MoveY 가 0.1보다 크다면 -0.1보다 작다면 실행으로 설정.

 

2. Move -> Idle transition

MoveX, Move Y가 0일 때 Idle이 실행되게 설정.

 

코드.

if(Input.GetAxisRaw("Horizontal") == 1 || Input.GetAxisRaw("Horizontal") == -1 || Input.GetAxisRaw("Vertical") == 1 || Input.GetAxisRaw("Vertical") == -1)
        {
            myAnim.SetFloat("LastMoveX", Input.GetAxisRaw("Horizontal"));
            myAnim.SetFloat("LastMoveY", Input.GetAxisRaw("Vertical"));
        }

 

Input.GetAxisRaw로 입력된 값을 LastMoveX에 저장된다.'

 

내 생각: 파라미터에 bool 변수를 사용하면 좀 더 보기 쉽고 간단하게 할 수 있을 듯.

 

좀 더 세밀하게 움직임 설정하기

대각으로 움직일 시 4방향과 달리 벡터 크기가 1이 아니다. 

그래서 동일하게 1의 힘을 가지는 방향벡터만 받기 위해서 정규화해준다.

 playerRb.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * playerMoveSpeed * Time.deltaTime;

Blend Tree도 변경.

Idle, Move 둘 다 변경한다.

결과

Comments