유니티 심화

(수정중) 유니티 New Input System 사용하여 이동 구현

송현호 2023. 9. 1. 10:35

 

Send Messages를 통한 구현

 

Send Messages는 Player Input에 삽입한 액션을 SendMessage함수로 호출한다.

 

이때 Sendmessage로 호출되는 함수는 On + Action Name으로 지어야 한다.

 

이동기능의 액션이름을 Move로 정의했기 때문에 OnMove로 값을 전달받는다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
    [SerializeField]
    private float moveSpeed = 8f;
    [SerializeField]
    private float radius = 100f;
    [SerializeField]
    private GameObject bullet;
    [SerializeField]
    private Transform firePos;
    [SerializeField]
    private InputAction joystick2;

    private int bulletDamage = 40;

    private float targetDistance = Mathf.Infinity;
    private Collider currTarget;
    private Collider target;

    private Rigidbody rb;
    private Animator anim;

    private bool isAttack = false;
    private float coolDown = 0.5f;
    private bool isCoolDown = false;
    private bool isDie = false;

    private Vector2 dir;
    
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        anim = GetComponent<Animator>();
        
    }

    void OnMove(InputValue value)
    {
        dir = value.Get<Vector2>();
        Debug.Log($"Move = ({dir.x},{dir.y})");
    }
    // Update is called once per frame
    void Update() 
    {

        float h = dir.x;
        float v = dir.y;

        if(h == 0 && v == 0)
        {
            if(isAttack == true)
            {
                this.transform.LookAt(this.target.transform.position);
                
                if (this.isCoolDown == false)
                {
                    this.isCoolDown = true;
                    StartCoroutine(CoAttack());
                }
            }

            else if(isAttack == false)
            {
                this.anim.SetBool("Move", false);
            }
        }
        else
        {
            this.transform.forward = new Vector3(h, 0, v);
            this.anim.SetBool("Move", true);
            this.rb.MovePosition(this.transform.position + new Vector3(h, 0, v) * Time.deltaTime * moveSpeed);
        }
}

 

Invoke Unity Events

 

Invoke Unity Events를 사용하면 내가 정의한 액션에 직접 함수를 연결할 수 있다.

 

직접 연결할 수 있기 때문에 On + Action Name의 규칙을 지키지 않아도 무방하지만 일관성을 위해 같은 규칙으로 작성하였다.

 

public void OnMove(InputAction.CallbackContext context)
    {
        dir = context.ReadValue<Vector2>();
    }

Invoke Unity Events를 사용할 경우 파라미터 타입은 CallbackContext를 사용해야 한다. 

 

Invoke C Sharp Events

 

Invoke C Sharp Events는 스크립트에서 코드로 직접 이벤트를 연결하는 방식이다.

 

Player Input 스크립트의 Component 추출 -> ActionMap추출 -> 액션맵에서 Action추출 -> 추출한 액션에 이벤트를 연결하는 과정을 거친다.