본문 바로가기
KDT/유니티 기초

23/08/03 애니메이션 방향 전환 및 점프 연습

by 잰쟁 2023. 8. 3.
728x90
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HeroController : MonoBehaviour
{
    private Animator anim;
    public Rigidbody2D rBody2D;

    public float jumpForce;

    public float moveSpeed;

    private float moveForce = 1f;

    private bool isJump = 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()
    {
        //방향 전환
        //키보드 좌우 인풋을 받아 -1,0,1 출력
        float h = Input.GetAxisRaw("Horizontal");  //-1,0,1
        //h: 방향 의미하는 값
        //Debug.LogFormat("===>{0}", (int)h);

        //좌우반전 스케일의 X값을 -1로 한다. 이때 y,z의 값은 1이어야 함
        //즉, 좌: (-1,1,1)
        //우: (1,1,1)
        if (h != 0)
        {
            //누른상태 좌(-1) 우(1) : 이동상태
            this.transform.localScale = new Vector3(h, 1, 1);

            //리지드바디가 없을 경우 이동?
            //h : x축 방향
            Vector3 dir = new Vector3(h, 0, 0);
            //속도 : moveSpeed
            //this.transform.Translate(방향 * 속도 * 시간);
            this.transform.Translate(dir * moveSpeed * Time.deltaTime);

            //애니메이션 전환
            //멈춤 : 기본동작  h값이 0 즉, dir 값이 (0,0,0)벡터 = Vector3.zero
            //이동 : 뛰는동작  h값이 0이 아니다. -1 또는 1일 경우
            //Animator의 매개변수에 값을 할당하면
            //Animator Controller의 transition에 설정된 condition에 의해 전환됨
            this.anim.SetInteger("h", (int)h);
        }
        else
        {
            this.anim.SetBool("Idel", true);
        }

         //점프
         if (Input.GetKeyUp(KeyCode.Space))
         {
            
            if (this.isJump == false)
            {
                Debug.Log("jump");
                this.rBody2D.AddForce(Vector2.up * this.jumpForce, ForceMode2D.Impulse);
                this.isJump = true;
            }
         }
        if (this.isJump)
        {
            if (this.rBody2D.velocity.y > 0)
            {
                //점프하기
                this.anim.SetBool("Jump", true);
            }
            else if (this.rBody2D.velocity.y < 0)
            {
                //내려오기
                this.anim.SetBool("Fall", true);
            }
            else
            {
                this.anim.SetBool("Jump", false);
                this.anim.SetBool("Fall", false);
                this.anim.SetBool("Idle", true);            
            }
        } 
    }  
}