本文主要是介绍Unity的InputSystem使用实践,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
如何使用
首先得有一个PlayerInput在场景中,每一个PlayerInput表示一个玩家
在Actions里面选择自己的Actions,可以新建:
比如在PlayerMaps中的MoveActions就是一个2D向量组合器
比如新建一个
然后把键盘数字键8绑定成到UP,勾选下面的Keyboard&Mouse,这样就成了键盘的8键是我们的UP,同理绑定其他几个
然后在inspector面板中生成一下CS文件:
绑定事件
手动绑定
Send Messages或者Broadcast Messages
您可以通过定义组件,像这样的方法您的应用程序设置来响应行动:
public class MyPlayerScript : MonoBehaviour
{// "fire" action becomes "OnFire" method. If you're not interested in the// value from the control that triggers the action, use a method// without arguments.public void OnFire(){}// If you are interested in the value from the control that triggers an action,// you can declare a parameter of type InputValue.public void OnMove(InputValue value){// Read value from control. The type depends on what type of controls.// the action is bound to.var v = value.Get<Vector2>();// IMPORTANT: The given InputValue is only valid for the duration of the callback.// Storing the InputValue references somewhere and calling Get<T>()// later does not work correctly.}
}
UnityEvent Actions
Invoke Unity Events,每个动作必须被路由到目标方法。该方法与InputAction的started,performed和canceled回调具有相同的格式。
比如下面的方法形式
CSharp Events
事件为普通的CS事件(event),然后可以接收下面的事件通知
以下事件可用:
- onActionTriggered (针对玩家的所有动作的集体事件);
- onDeviceLost;
- onDeviceRegained;
用来检视设备变化
代码里面绑定回调
假如要实现2D物体的移动
代码注册回调:
public InputManager inputActions;private Vector2 direction;private void Awake(){inputActions = new InputManager();}private void OnEnable(){inputActions.Enable();inputActions.Player.Move.performed += ctx => Move(ctx);inputActions.Player.Move.canceled += ctx => Move(ctx);}private void OnDisable(){inputActions.Player.Move.performed -= ctx => Move(ctx); ;inputActions.Player.Move.canceled -= ctx => Move(ctx);inputActions.Disable();}public void Move(InputAction.CallbackContext context){var moveValue = context.ReadValue<Vector2>();Debug.Log(moveValue);direction = moveValue;}void Update(){if (direction != Vector2.zero){Vector3 delta = new Vector3(direction.x, direction.y, 0) * Time.deltaTime * 5f;transform.position = transform.position + delta;}}
还有直接获取设备按键
Keyboard keyboard;keyboard = InputSystem.GetDevice<Keyboard>(); if (keyboard.wKey.isPressed)
{direction = new Vector2(0, 1);Vector3 delta = new Vector3(direction.x, direction.y, 0) * Time.deltaTime * 5f;transform.position = transform.position + delta;
}
按键是被按下还是被按住
Keyboard.current.spaceKey.isPressed
Keyboard.current.spaceKey.wasPressedThisFrame
额,最后发现按小键盘的数字键不会动,但是按主区域的数字键就可以,原因是绑定错了:
应该是Numpad8
修改过后保存
参考:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Components.html
https://www.youtube.com/watch?v=HwbbvjzT3qE
https://github.com/sniffle6/Input-System-Strategy-Pattern
这篇关于Unity的InputSystem使用实践的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!