본문 바로가기
Software/Unity

[Unity] 9. 키보드, 마우스로 이동시키기

by yunaoh2 2021. 8. 31.

1. input 클래스 : 게임 내 입력(키보드 / 마우스 등)을 관리하는 클래스

  • anyKeyDown : 아무 입력을 최초로 받을 때 true
  • anyKey : 아무 입력을 누르고 있을 때 true

2. 키보드

  • Down 할 때  GetKeyDown
  • Stay 할 때    GetKey
  • Up 할 때      GetKeyUp

   <KeyCode>

  • Return : Enter
  • Escape : ESC
  • LeftArrow
  • RightArrow

3. 마우스 (0 / 1) : 0-왼쪽버튼, 1-오른쪽버튼

  • GetMouseButtonDown(0 / 1) : 누를 때
  • GetMouseButton(0 / 1) : 누르고 있을 때
  • GetMouseButtonUp(0 / 1) : 뗄 때

4. 키버튼방식

    Edit > project settings > input

 

    input manager > inspector 에 지정되어있음. 변경 가능 

    Horizontal : 수평이동

    Vertical : 수직 이동 

 

**size 숫자 올리면 새로운 키버튼을 생성할 수 있음

 

public class LifeCycle : MonoBehaviour
{
    void Updata()
    {
        ###아무키보드###
        if(Input.anyKeyDown)
            Debug.Log("플레이어가 아무 키를 눌렀습니다.");
        if(Input.anyKey)
            Debug.Log("플레이어가 아무 키를 누르고 있습니다.");

        ###해당키보드###
        if(Input.GetKey(KeyCode.Return))      #Return = Enter
            Debug.Log("아이템을 구입하였습니다.")';
        if(Input.GetKey(KeyCode.LeftArrow))
            Debug.Log("왼쪽으로 이동 중");
        if(Input.GetKeyUp(KeyCode.RightArrow))
            Debug.Log("오른쪽 이동을 멈추었습니다.");

        ###마우스 왼쪽 / 오른쪽###
        if(Input.GetMouseButtonDown(0))
            Debug.Log("미사일 발사!")';
        if(Input.GetMouseButton(0))
            Debug.Log("미사일 모으는 중");
        if(Input.GetMouseButtonUp(0))
            Debug.Log("슈퍼 미사일 발사!!");

        ###키버튼###
        if(Input.GetButtonDown(Jump))       #input manager에 있는 키버튼 사용
            Debug.Log("점프!")';
        if(Input.GetButton(Jump))
            Debug.Log("점프 모으는 중");
        if(Input.GetButtonUp(Jump))
            Debug.Log("슈퍼 점프!!");


        ###키버튼 - Axis(값) 출력###
        if(Input.GetButton("Horizontal"))   {
            Debug.Log("횡 이동 중..." + Input.GetAxis("Horizontal")
        }

        if(Input.GetButton("Horizontal"))   {
            Debug.Log("횡 이동 중..." + Input.GetAxisRaw("Horizontal")   #끝 값 출력 (-1 (왼쪽) / 1 (오른쪽)/ 0 (중간))
         }

    }

 

예제1) 시작하면 위치 이동

public class LifeCycle : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Vector3 vec = new Vector3(5,5,5);    //Vector3: 3차원 
        transform.Translate(vec);     //(5,5,5)만큼 이동
    }
}

 

예제2) 시작하면 계속 위로 올라가기

public class LifeCycle : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
       
    }
    void Update()    //1초당 60회 실행
    {
        Vector3 vec = new Vector3(0,0.1f,0);
        transform.Translate(vec);     // y축으로 0.1만큼 이동  -> 계속 위로 올라감
    }

}

 

예제3) 키보드 이동으로 움직이기

public class LifeCycle : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
       
    }
    void Update()    //1초당 60회 실행
    {
        Vector3 vec = new Vector3(
            Input.GetAxis("Horizontal"),    //x축 키보드 이동만큼
            Input.GetAxis("Vertical"),      //y축 키보드 이동만큼
            0);                             //z축은 그냥 계속 0으로
        transform.Translate(vec);
    }

}

 

예제4) 1씩 움직이기

public class LifeCycle : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
       
    }
    void Update()    //1초당 60회 실행
    {
        Vector3 vec = new Vector3(
            Input.GetAxisRaw("Horizontal"),    //x축 키보드 이동만큼
            Input.GetAxisRaw("Vertical"),      //y축 키보드 이동만큼
            0);                             //z축은 그냥 계속 0으로
        transform.Translate(vec);
    }
}

 

참고영상

https://www.youtube.com/watch?v=wqRwsW03JR4&list=PLO-mt5Iu5TeYI4dbYwWP8JqZMC9iuUIW2&index=7 

 

 

<Time.deltaTime>

deltaTime 값은 프레임이 적으면 크고, 프레임이 많으면 작음.

Time.deltaTime : 프레임 값이 크든 적든 사양이 좋든 안좋든 결과값이 동일하게 나오게 하는 것

  • Translate : 벡터에 곱하기

      transform.Translagte(Vec * Time.deltaTime);

 

  • Vector함수 : 시간 매개변수에 곱하기

       Vector3.Lerp(Vec1, Vec2, T*Time.deltaTime);

'Software > Unity' 카테고리의 다른 글

[Unity] 10. 목표지점으로 이동시키기  (0) 2021.08.31
[Unity] 8. 게임오브젝트의 흐름  (0) 2021.08.31
[Unity] 7. 함수  (0) 2021.08.31
[Unity] 6. 반복문  (0) 2021.08.25
[Unity] 5. 조건문  (0) 2021.08.25