본문 바로가기
유니티

[유니티] 2D 플레이어 애니메이션

by SUGI_ 2023. 8. 8.
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Windows.Speech;

public class Player : MonoBehaviour
{
    [Header("Player Info")]
    [SerializeField] private float moveSpeed;
    [SerializeField] private float jumpForce;

    [Header("Dash Info")] //시간동안 스피드가 빨라진다.
    [SerializeField] private float dashSpeed;
    [SerializeField] private float dashDuration;
    private float dashTime;
    [SerializeField] private float dashCooldown;
    private float dashCooldownTimer;

    private Rigidbody2D rb;
    private Animator anim;
    private SpriteRenderer sp;

    private float xInput;
    private int facingDir = 1;
    private bool facingRight = true;
    private bool isGrounded;

    [Header("Collision Info")] 
    [SerializeField] private float groundCheckDistance;
    [SerializeField] private LayerMask whatIsGround;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();

        //자식 컴포넌트 불러오는 방법
        //anim = transform.GetChild(0).GetComponent<Animator>(); //인덱스로 찾기
        anim = GetComponentInChildren<Animator>(); //첫번째

        //이 방법으로 하지 않을 것임.
        //sp = GetComponentInChildren<SpriteRenderer>();
    }

    void Update()
    {
        //움직임
        Movement();
        //키 체크
        CheckInput();
        //땅 체크
        CollisionChecks();

        //대시 시간 흐름
        dashTime -= Time.deltaTime;
        dashCooldownTimer -= Time.deltaTime;

        //반대
        FlipController();

        //애니메이션
        AnimatorControllers();
    }

    //땅에 닿는지 체크
    private void CollisionChecks()
    {
        isGrounded = Physics2D.Raycast(transform.position, Vector2.down, groundCheckDistance, whatIsGround);
        Debug.Log(isGrounded);
    }

    //키 누름
    private void CheckInput()
    {
        xInput = Input.GetAxisRaw("Horizontal");

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }

        if (Input.GetKeyDown(KeyCode.LeftShift))
        {
            DashAbility();
        }
    }

    private void DashAbility()
    {
        //대쉬 시간이 다 되면
        if(dashCooldownTimer < 0)
        {
            //대시 쿨타임
            dashCooldownTimer = dashCooldown;
            //대시 시간
            dashTime = dashDuration;
        }
    }

    private void Movement()
    {
        if(dashTime > 0)
        {
            //대시상태일때는 y값만 0으로 놓으면
            rb.velocity = new Vector2(xInput * dashSpeed, 0);
        }
        
        else
        {
            rb.velocity = new Vector2(xInput * moveSpeed, rb.velocity.y);
        }
    }

    private void Jump()
    {
        if (isGrounded)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        }
    }

    private void AnimatorControllers()
    {
        bool isMoving = rb.velocity.x != 0;
        //sp.flipX = rb.velocity.x < 0;

        anim.SetBool("isMove", isMoving);
        anim.SetBool("isGrounded", isGrounded);
        anim.SetBool("isDashing", dashTime > 0);
        anim.SetFloat("yVelocity", rb.velocity.y);
    }

    private void Flip()
    {
        facingDir = facingDir * -1;
        facingRight = !facingRight;
        transform.Rotate(0, 180, 0);
    }

    private void FlipController()
    {
        if (rb.velocity.x > 0 && !facingRight)
        {
            Flip();
        }
        else if (rb.velocity.x < 0 && facingRight)
        {
            Flip();
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawLine(transform.position, new Vector3(transform.position.x, transform.position.y - groundCheckDistance));
    }
}

 

레이어 체크를 위한 변수

[SerializeField] private LayerMask whatIsGround;

 

Any State 애니메이션 안될 때 

체크 해제해야함

Blend Tree

 

구현할 내용

공격 애니메이션 구현

https://hoil2.tistory.com/12

 

[유니티 강좌] 2D RPG 게임 만들기 - 3 / 공격 애니메이션

소드맨의 공격을 구현해볼 건데 그전에 한 가지 수정해야 할 것이 있습니다. GetAxis함수로 방향 전환할 때 애니메이션이 끊기는 현상이 있습니다. [2021/04/13 추가내용 : GetAxis함수로 방향 전환해도

hoil2.tistory.com

공격 3개 콤보

https://blog.naver.com/PostView.naver?blogId=pa_yu&logNo=222283948395&categoryNo=17&parentCategoryNo=0 

 

[MyFirstWorld] 27. 콤보공격 : 화려하게 4단 콤보!

1. "공격이 너무 밋밋하진 않은가?" "그러하다면 콤보 공격을 구현하는 것이 좋겠소."...

blog.naver.com

상속해보기 몬스터 Entry

https://ansohxxn.github.io/unity%20lesson%201/chapter7-2/

 

Unity Chapter 7-2. C# 프로그래밍 [중급] (2/2) : 상속

인프런에 있는 이제민님의 레트로의 유니티 C# 게임 프로그래밍 에센스 강의를 듣고 정리한 필기입니다. 😀 🌜 [레트로의 유니티 C# 게임 프로그래밍 에센스] 강의 들으러 가기!

ansohxxn.github.io

 

728x90

'유니티' 카테고리의 다른 글

[유니티] 시네머신  (0) 2023.08.16
[유니티] 타겟  (0) 2023.08.08
[유니티] 디버깅 방법  (0) 2023.08.08
[유니티] Resources.Load  (0) 2023.08.07
[유니티] 페이드 인 아웃  (0) 2023.07.31