Input System的简单应用

通过前面两篇我们简单的了解了一下Input System,接着就是要学以致用,这样才能了解的更加透彻。

首先先搭一个简单的场景,随便摆放点东西,然后用个Cube来模拟角色,如图。

利用键盘控制

一般的游戏角色会有例如,移动、旋转、释放技能这类的操作,根据需求我们创建一个Input Actions,如图,通过WASD来触发移动,按键1和2来触发技能,然后将其导出为C#脚本。

      

然后我们创建一个类来管理它(InputManager),后续可以将其写作单例。

using System;
using UnityEngine;

public class InputManager : MonoBehaviour
{
	private PlayerInputAction m_action;

	public Action<Vector2> moveAction;
	public Action skill1, skill2;
	
	void Awake()
	{
		m_action = new PlayerInputAction();

		m_action.Player.Skill1.performed += ctx => { skill1?.Invoke();};
		m_action.Player.Skill2.performed += ctx => { skill2?.Invoke();};
	}
	
	public void OnEnable()
	{
		m_action.Enable();
	}

	public void OnDisable()
	{
		m_action.Disable();
	}

	void Update()
	{
		moveAction?.Invoke(m_action.Player.Move.ReadValue<Vector2>());
	}
}

接下来,我们用一个类(Player)来实现玩家的行为。

using UnityEngine;

public class Player : MonoBehaviour
{
	private float m_moveSpeed = 10;
	private Transform m_transform;
	private InputManager m_inputManager;
	
	void Start()
	{
		m_transform = transform;
		m_inputManager = GetComponent<InputManager>();

		m_inputManager.moveAction = Move;
		m_inputManager.skill1 = Skill1;
		m_inputManager.skill2 = Skill2;
	}

	void Move(Vector2 v)
	{
		var scaledMoveSpeed = m_moveSpeed * Time.deltaTime;
		var move = Quaternion.Euler(0, m_transform.eulerAngles.y, 0) * new Vector3(v.x, 0, v.y);
		m_transform.position += move * scaledMoveSpeed;
	}


	void Skill1()
	{
		Debug.Log("skill1111111111");
	}
	void Skill2()
	{
		Debug.Log("skill22222222222");
	}
}

只需要将这两个组件挂载到Player上即可利用键盘来控制角色行为了。

使用UI控制

手游而言,所有的操作基本都是由UI来解决的,那么用Input System对UI会有啥影响呢。

我们先简单的添加一些按钮,用于控制角色,如图:

注意要将EventSystem中的Standalone Input Module变更为新的Input System UI Input Module组件。

按照以前的做法,我们可以使用Button的onClick.AddListener()来添加事件,方向键的话可以使用UnityEngine.EventSystems.IDragHandler接口来实现拖动。

不过Input System提供了两个组件,分别是OnScreenStick和OnScreenButton,可以用来模拟输入设备。使用起来非常简单,我们只需要给Stick挂上OnScreenStick组件,给Skill1和Skill2分别挂上OnScreenButton,然后设置如下即可

 

Movement Range即拖动范围,Control Path即要模拟的输入设备输入。

例如,Skill1 Button添加了OnScreenButton组件,然后Control Path设置为Keyboard的 1 。那么当我们点击Skill1的时候,等同于键盘的1键按下,会触发相应的Action。

由于OnScreenStick我们绑定的是Gamepad的LeftStick,所以在之前的.inputactions文件中,我们给Move添加一个新的Binding来关联Gamepad的LeftStick。

这样搞好之后就不需要在添加别的代码,运行即可实现UI控制。

思考

由于刚接触Input System,有些还是不是很清楚。例如我想实现滑动屏幕实现角色旋转,我可以通过Hold,在按下和松开的时候纪录鼠标偏移的值来处理。但是在我拖动UI上的移动按钮的时候,同时也会导致上述操作的触发,引起冲突。所以现在想的就是依旧使用UnityEngine.EventSystems.IDragHandler接口来实现拖动。

还有对于OnScreenButton的使用,例如商城背包等界面有一堆的按钮,而手游又不会想PC端网游那样有一堆的快捷键,需要去设置。所以个人感觉依旧还是使用Button.onClick.AddListener()来为按钮添加事件。

猜你喜欢

转载自blog.csdn.net/wangjiangrong/article/details/104502826
今日推荐