본문 바로가기

Unity

[Unity] 수평, 수직이동을 시켜보자

728x90

플레이어의 Horizontal과 Vertical 입력을 받아서 대각선으로 이동하지 않고, 수평으로만 이동하게 해 보겠다.

 

1
2
3
4
5
6
7
8
9
10
11
12
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Player : MonoBehaviour
{
    public float speed;
 
    Rigidbody2D rigid;
    bool isHorizontalMove;
    float hInput;
    float vInput;

 

 

  • speed - 플레이어의 속도를 저장할 변수이다.
  • rigid - 플레이어의 Rigidbody2D를 저장할 변수이다.
  • isHorizontalMove - 수평이동을 하고 있는지 확인할 변수이다.
  • hInput - 플레이어의 수평이동의 값을 저장할 변수이다.
  • vInput - 플레이어의 수직이동의 값을 저장할 변수이다.

 

1
2
3
4
 void Start()
    {
        rigid = GetComponent<Rigidbody2D>();
    }

 

플레이어의 Rigidbody2D를 rigid에 저장한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  void Update()
    {
        hInput = Input.GetAxisRaw("Horizontal");
        vInput = Input.GetAxisRaw("Vertical");
 
        if (hInput == 0 && vInput != 0)
        {
            isHorizontalMove = false;
        }    
        else
        {
            isHorizontalMove = true;
        }
    }

 

hInput의 값과 vInput의 값을 GetAxisRaw로 가져온다. 그리고 조건문 hInput == 0 && vInput != 0는 플레이어가 수직으로 이동하고 있다는 뜻이다. 그러므로 isHorizontalMove를 false로 바꿔준다. else는 반대의 경우이므로 플레이어가 수평으로 이동하고 있다는 뜻이다. 따라서 isHorizontalMove를 true로 바꿔준다.

 

1
2
3
4
5
6
void FixedUpdate()
    {
        Vector2 moveVec = isHorizontalMove ? new Vector2(hInput, 0) : new Vector2(0, vInput);
        rigid.velocity = moveVec speed;
    }
}

 

마지막으로 Update에서 받아온 정보를 FixedUpdate를 사용하여 플레이어에게 적용해준다. moveVec이란 Vector2 변수는 isHorizontalMove가 true면 new Vector2(hInput, 0)가 저장되고, false의 경우 new Vector2(0, vInput)이 저장된다.

 

이렇게 스크립트를 저장하고 public으로 선언된 speed를 Inspector창에서 설정만 해주면 플레이어가 수직, 수평으로만 이동하게 할 수 있다.

 

결과 화면은 다음과 같다.

 

결과 화면

728x90