TIL
[Unity] Fooooox - Refactoring1 (모바일용 이동 조작 & 체력 UI 변경)
habbn
2024. 12. 13. 21:19
728x90
1년전 처음 유니티를 배우고 스스로 만든 게임이었던 2D 플랫포머 게임을 리팩토링/수정하려고 한다.
우선 키보드 입력 플레이어 조작을 모바일 버튼 터치 조작으로 변경하였다.
//PlayerCtrl.cs
private void HandleInput()
{
dirX = Input.GetAxis("Horizontal");
transform.Translate(dirX * Time.deltaTime * moveSpeed, 0, 0);
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
{
rb.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
}
if (Input.GetKeyDown(KeyCode.Z))
{
ShootBullet();
}
}
기존에는 좌우 키(-1, 1) 에 맞는 값에 따라 플레이어를 이동시키고, 스페이스바를 누를 시 점프, Z키를 누를 시 총을 발사하는 식으로 구현했었다.
모바일용으로 변경하기 위해 우선 버튼 UI를 배치해주고, 해당 버튼에 Event Trigger - Point Down과 Point Up 이벤트를 추가해주고 각 상황에 맞는 함수들을 연결시켜주었다.
public void MoveLeft()
{
inputX = -1f;
}
public void MoveRight()
{
inputX = 1f;
}
public void StopMove()
{
inputX = 0f;
}
public void Jump()
{
if (IsGrounded())
{
isJumping = true;
}
}
public void Fire()
{
ShootBullet();
}
inputX 값에 따라 이동시켜주고 AddForce를 활용하여 점프를 구현했다. (기존 코드와 동일)
private void MoveUpdateAnim()
{
transform.Translate(inputX * Time.deltaTime * moveSpeed, 0, 0);
if (isJumping)
{
rb.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
isJumping = false;
}
if (inputX != 0) // walk
{
anim.SetInteger("state", 1);
transform.localScale = new Vector3(Mathf.Sign(inputX), 1, 1);
}
else // idle
{
anim.SetInteger("state", 0);
}
if (rb.velocity.y > 0.1f) // jump
{
anim.SetInteger("state", 2);
}
else if (rb.velocity.y < -0.1f) // land
{
anim.SetInteger("state", 3);
}
}
728x90