본문 바로가기
Unity/수업과제

[Unity 2D] Mecanim (애니메이션 상태 시스템) 연습

by 왹져박사 2023. 2. 1.
728x90

처음에 SetInteger를 호출할수 없어 이유를 한참 찾았는데, 

Animator 타입을 Animation으로 자꾸 잘못 적었다. 항상 자세히 보기!!

 

Animator.SetInteger(Parameter이름, Transition에 설정한 상태);

 

Transition은 Has Exit Time, Fixed Duration 해제, 0으로 설정  :  키를 눌렀을 경우에만 transition이 일어나도록

Idle, Walk가 아닌 한번만 재생할 애니메이션은 Inspector의 Loop Time 해제

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

public class CucumberController : MonoBehaviour
{
    private Rigidbody2D rbody2D;
    private Animator anim;
    public float moveSpeed = 1f;
    public float jumpForce;
    private bool isJumping = false;
    private bool isFalling = false;

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

    // Update is called once per frame
    void Update()
    {
        int dir = 0;
        if (Input.GetKey(KeyCode.LeftArrow))
            dir = -1;
        else if (Input.GetKey(KeyCode.RightArrow))
            dir = 1;

        if(dir == 0)
            this.anim.SetInteger("State", 0);
        else
            this.anim.SetInteger("State", 1);


        //방향*속도*시간
        this.transform.Translate(new Vector3(dir, 0f, 0f) * this.moveSpeed * Time.deltaTime);

        if(dir!=0)
            this.transform.localScale = new Vector3(-dir, 1, 1);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            this.rbody2D.bodyType = RigidbodyType2D.Dynamic;
            this.rbody2D.AddForce(this.transform.up * this.jumpForce);
            this.anim.SetInteger("State", 2);
            this.isJumping = true;
        }

        if (this.isJumping)
        {
            if (this.rbody2D.velocity.y < 0 && isFalling == false)
            {
                this.isFalling = true;
                Debug.Log("Fall");
                this.anim.SetInteger("State", 3);
            }

        }
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        //if (this.rbody2D.velocity.y == 0) this.anim.SetInteger("State", 0);
        if (collision.gameObject.name == "ground") this.anim.SetInteger("State", 0);
    }
}

 

 

728x90