2D Player 조작

Jihyun·2023년 12월 5일
0

Unity 2D

목록 보기
1/10

키 입력 받기

Input

GetKey

사용자가 name에 의해 식별된 키를 누를 때 true 반환

bool Input.GetKeyDonw(KeyCode key);
bool Input.GetKey(KeyCode key);
bool Input.GetKeyUp(KeyCode key);

 void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("스페이스 키 누름");
        }

        if (Input.GetKey(KeyCode.Space))
        {
            Debug.Log("스페이스 키 누르는 중");
        }
        
        if (Input.GetKeyUp(KeyCode.Space))
        {
            Debug.Log("스페이스 키 눌렀다 뗌");
        }
    }

GetButton

"Button Name"에 의해 식별된 가상 버튼을 누르고 있는 동안 true 반환
[Eidt]-[Project Settings]-[Input]에서 확인 가능

void Update()
    {
        if (Input.GetButtonDown("Jump"))
        {
            Debug.Log("Jump");
        }

        Debug.Log(Input.GetAxisRaw("Horizontal"));
       
    }

플레이어 움직이기

플레이어 이동

2차원 벡터에서 Y축은 수직 방향, X축은 수평 방향을 나타낸다. 여기서 오브젝트를 오른쪽으로 움직이기 위해 X축의 속도나 위치를 증가 시킨다. 반대로 왼쪽으로 움직이기 위해서는 X축의 위치나 속도를 감소 시킨다.

 void Update()
 {      
        //수평 방향의 사용자 입력을 저장
        xInput = Input.GetAxisRaw("Horizontal");

        //Rigidbody의 velocity 속성을 통해 플레이어의 속도를 설정
        //수평으로 이동 시키는데 사용
            //새로운 Vector2 생성
            //수평방향 : xInput * moveSpeed
            //수직방향 : 현재 수직 속도 유지
        rb.velocity = new Vector2(xInput * moveSpeed, rb.velocity.y);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        }

 }

2D 플레이어를 이동하려 할 때 앞 뒤로 넘어지는 경우가 있는데 이 때 Rigidbosy2D의 Z축 Rotation을 고정시켜주면 된다.

무한점프 방지

[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask whatIsGround;
private bool isGrounded;

private void CollisionChecks()
{
        isGrounded = Physics2D.Raycast(transform.position, Vector2.down, groundCheckDistance, whatIsGround);
}

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

애니메이션 재생하기

Finite State Machine(FSM)

유한상태머신이란 유한한 수의 상태(State)가 존재하며, 한 번에 한 상태만 현재 상태가 되도록 프로그램을 설계하는 모델
유한상태머신에서는 전이(Transition)을 통해 현재 상태에서 다른 상태로 이동할 수 있다. 전이에는 전이가 발동될 조건(Condition)을 추가할 수 있다.

  • Animator Controller : 유한상태머신을 사용해 재생할 애니메이션을 결정하는 상태도를 표현하는 에셋
  • Animator : 애니메이터 컨트롤러를 이용해 애니메이션을 재생하는 컴포넌트
if(rb.velocity.x != 0)
{
            isMoving = true;
}
else
{
            isMoving = false;
}
        
animator.SetBool("isMoving", isMoving);

Sprite Flip

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

private void FlipController()
{
        
        if(rb.velocity.x > 0 && !facingRihgt)
        {
            Flip();
            
        }
        else if(rb.velocity.x < 0 && facingRihgt)
        {
            Flip();
        }
}
profile
잊어버려도 다시 리마인드 할 수 있도록 공부한 것을 기록합니다

0개의 댓글