K-digital traning/유니티 기초
애니메이션 전환 연습
내꺼블로그
2023. 8. 3. 17:40
구현한 거 : Idle, Run, Jump, Fall
(1) HeroController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeroController : MonoBehaviour
{
private Animator anim;
Rigidbody2D rBody2D;
public float jumpSpeed=300f;
public float moveSpeed=1.5f;
bool isJump = false;
int state;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
this.rBody2D = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxisRaw("Horizontal"); //방향키 상태(-1:왼쪽, 0:키누름X, 1:오른쪽)
Debug.LogFormat("=>{0}", h);
//좌우 방향키 누른 상태
if (h != 0)
{
this.transform.localScale = new Vector3(h, 1, 1); //캐릭터 방향전환(외향)
if (state == 0) state = 1; //만약 캐릭터의 상태가 Idle라면 Run으로 transition
}
else
{
if (state == 1) state = 0; //좌우 방향키를 누르지 않은 상태에서 캐릭터 상태가 Run이라면 Idle로 transition
}
//x좌표 velocity 부여.(왼쪽->마이너스 방향으로 이동, 오른쪽->플러스 방향으로 이동, 가만히->값이 0)
float velocityX = moveSpeed * h;
this.rBody2D.velocity = new Vector2(velocityX, rBody2D.velocity.y);
//스페이스 바를 누른다면
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.LogFormat("isJump: {0}", isJump);
if (!isJump) //점프 상황이 아닌 경우
{
state = 2; //Jump로 transition
isJump = true;
this.rBody2D.AddForce(new Vector2(0, jumpSpeed)); //addforce로 힘을 부여.
}
}
//떨어져서 땅에 도착한 경우 Idle로 transition
else if (this.rBody2D.velocity.y == 0)
{
if (state == 3) {
state = 0;
isJump = false;
}
}
//velocity y값 0이하일 때 => 캐릭터가 땅으로 떨어질 때
if (this.rBody2D.velocity.y < 0)
state = 3;
//애니메이터로 캐릭터의 상태 전달.
this.anim.SetInteger("State", state);
}
}
2.Animator Layer
Transition에 각자 도달할 state값을 condition에 부여
ex) Run에서 Idle로 트랜지션이 일어나야 될 때의 condition
결과아ㅏㅏㅏㅏㅏㅏㅏㅏㅏㅏㅏㅏ
+)장애물 설치