Client/Unity

Unity) Input system - 이동

Juzdalua 2024. 5. 4. 20:48

 

Package Manager에서 Input System을 설치하고 새로 만든다.

 

기본으로 만들어진 Vector2 액션을 사용한다.

 

스크립트도 주입한다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerInputManager : MonoBehaviour
{
    public Vector2 move;
    public Vector2 look;
    
    void OnMove(InputValue value){
        move = value.Get<Vector2>();
    }

    void OnLook(InputValue value){
        look = value.Get<Vector2>();
    }
}

 

이제 플레이어와 연동한다.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed = 2f;
    
    CharacterController _controller;
    PlayerInputManager _input;

    // Start is called before the first frame update
    void Start()
    {
        _controller = GetComponent<CharacterController>();
        _input = GetComponent<PlayerInputManager>();        
    }

    // Update is called once per frame
    void Update()
    {
        direction = new Vector3(_input.move.x, 0, _input.move.y);
        _controller.Move(direction * speed * Time.deltaTime);
    }
}

훨씬 간편해졌다.

위 코드는 기존 아래 코드와 동일하게 동작한다.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed = 2f;
    
    CharacterController _controller;    

    // Start is called before the first frame update
    void Start()
    {
        _controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
    	float hAxis = Input.GetAxisRaw("Horizontal");
        float vAxis = Input.GetAxisRaw("Vertical");
        
        direction = new Vector3(hAxis, 0, vAxis);
        _controller.Move(direction * speed * Time.deltaTime);
    }
}