[유니티 입문 강좌] part9 애니메이터

kkily·2021년 11월 21일
0

애니메이터

sphere를 이용해 cube의 움직이는 방향을 보여줌 (사진은 큐브가 점프하는는 상태)

Animation들을 다 만든 후에 Animator 탭을 열어줌

디폴트 상태로 원하는 것을 우클릭해서 default로 만듦

  • Exit time은 애니메이션이 얼만큼 끝나고 난 뒤에 상태 전이 할지(0=Has Exit Time 체크해제)
  • Transition Duration은 두개의 효과간에 얼마나 자연스럽게 연출하는지(상태 전이하는에 얼마나 걸리게 할지)
  • Transition Offset은 늘리면 그만큼 뒤에서 애니메이션이 실행됨
  • Interruption source는 언제 중단 시킬 것인지

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

public class Test_chap9 : MonoBehaviour
{

    private Animator anim;
    [SerializeField] private float moveSpeed;

    // Start is called before the first frame update
    void Start()
    {
        anim=GetComponent<Animator>();

    }

    // Update is called once per frame
    void Update()
    {
        float _dirX=Input.GetAxisRaw("Horizintal"); 
        //A,D키 혹은 방향키(오,왼)을 뜻함 오른쪽 키가 눌리면 1이 리턴되고 왼쪽키가 눌리면 -1이 리턴 안눌리면 0리턴
        float _dirZ=Input.GetAxisRaw("Vertical"); 
        //w,s키 혹은 방향키(위,아래)을 뜻함 위키가 눌리면 1 아래키 눌리면 -1 안눌리면 0리턴

        Vector3 direction = new Vector3(_dirX,0,_dirZ);
        anim.SetBool("Right",false);
        anim.SetBool("Left",false);
        anim.SetBool("Up",false);
        anim.SetBool("Down",false);
   
        if(direction!=Vector3.zero){
            this.transform.Translate(direction.normalized *moveSpeed * Time.deltaTime);
            //대각선 움직임도 수평 수직 움직임과 똑같이 만들기 위해 normalized를 함. 하지 않으면 대각선 속도만 유독 빨라짐.

            if(direction.x>0){
                anim.SetBool("Right",true);
            }
            else if(direction.x<0){
                anim.SetBool("Left",true);
            }
            else if(direction.z>0){
                anim.SetBool("Up",true);
            }
            else if(direction.z<0){
                anim.SetBool("Down",true);
            }


        }
    }
}

위는 복잡함 -> 간단하게 구현

Any State는 어떤 상태에서든 스페이스바를 누르면 점프하게 만들기 위해 연결한 것

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

public class Test_chap9 : MonoBehaviour
{

    private Animator anim;
    [SerializeField] private float moveSpeed;
    private bool isMove;

    // Start is called before the first frame update
    void Start()
    {
        anim=GetComponent<Animator>();

    }

    // Update is called once per frame
    void Update()
    {
        float _dirX=Input.GetAxisRaw("Horizintal"); 
        //A,D키 혹은 방향키(오,왼)을 뜻함 오른쪽 키가 눌리면 1이 리턴되고 왼쪽키가 눌리면 -1이 리턴 안눌리면 0리턴
        float _dirZ=Input.GetAxisRaw("Vertical"); 
        //w,s키 혹은 방향키(위,아래)을 뜻함 위키가 눌리면 1 아래키 눌리면 -1 안눌리면 0리턴

        Vector3 direction = new Vector3(_dirX,0,_dirZ);
        isMove=false;
        
        if(direction!=Vector3.zero){

             isMove=true;
            this.transform.Translate(direction.normalized *moveSpeed * Time.deltaTime);
            //대각선 움직임도 수평 수직 움직임과 똑같이 만들기 위해 normalized를 함. 하지 않으면 대각선 속도만 유독 빨라짐.
        }
        anim.SetBool("Move",isMove);
        anim.SetFloat("DirX",direction.x);
        anim.SetFloat("DirZ",direction.z);
    }
}

Parameter 만들 때 Trigger는 실행시키는 것
substatemachine(여기선 Jump)은 state를 넣을 수 있는 폴더같은 것, 보기에 깔끔해보이려고 씀

점프까지 한 완성 코드

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

public class Test_chap9 : MonoBehaviour
{

    private Animator anim;
    private Rigidbody rigid;
    private BoxCollider col;

    [SerializeField] private float moveSpeed;
    [SerializeField] private float jumpForce; //점프 스피드
    [SerializeField] private LayerMask layerMask;

    private bool isMove;
    private bool isJump;
    private bool isFall;

    // Start is called before the first frame update
    void Start()
    {
        anim=GetComponent<Animator>();
        rigid=GetComponent<Rigidbody>();
        col=GetComponent<BoxCollider>();

    }

    // Update is called once per frame
    void Update()
    {
        TryWalk();
        TryJump();
    }

    private void TryJump(){

        if(isJump){
            if(rigid.velocity.y<=-0.1f&&!isFall){
                isFall=true;
                anim.SetTrigger("Fall");
            }

            RaycastHit hitInfo;
            if(Physics.Raycast(transform.position,-transform.up,out hitInfo,col.bounds.extents.y + 0.1f,layerMask)) 
            //자기 자신의 방향에서 아래 방향으로 레이저를 (박스콜라이더 y값*1/2)+0.1f 만큼 특정 레이어만 반응하게 레이저를 쏨
            {
                anim.SetTrigger("Land");
                isJump=false;
                isFall=false;
            }
        }

        if(Input.GetKeyDown(KeyCode.Space)&&!isJump){
            isJump=true; //한번만 실행되게
            rigid.AddForce(Vector3.up * jumpForce);
            anim.SetTrigger("Jump");
        }
    }

    private void TryWalk(){
        float _dirX=Input.GetAxisRaw("Horizontal"); 
        //A,D키 혹은 방향키(오,왼)을 뜻함 오른쪽 키가 눌리면 1이 리턴되고 왼쪽키가 눌리면 -1이 리턴 안눌리면 0리턴
        float _dirZ=Input.GetAxisRaw("Vertical"); 
        //w,s키 혹은 방향키(위,아래)을 뜻함 위키가 눌리면 1 아래키 눌리면 -1 안눌리면 0리턴

        Vector3 direction = new Vector3(_dirX,0,_dirZ);
        isMove=false;
        
        if(direction!=Vector3.zero){

             isMove=true;
            this.transform.Translate(direction.normalized *moveSpeed * Time.deltaTime);
            //대각선 움직임도 수평 수직 움직임과 똑같이 만들기 위해 normalized를 함. 하지 않으면 대각선 속도만 유독 빨라짐.
        }
        anim.SetBool("Move",isMove);
        anim.SetFloat("DirX",direction.x);
        anim.SetFloat("DirZ",direction.z);
    }
}

Blend와 Substate Machine를 이용하면 깔끔하게 만들 수 있음!

Jump 더블클릭시

profile
낄리의 개발 블로그╰(*°▽°*)╯

1개의 댓글

comment-user-thumbnail
2021년 12월 19일

잘 읽었어요~ 김현수교수

답글 달기