Unity使用input system制作一个摇杆控制物体移动
1:首先使用UI做个摇杆的模型 两个图片嵌套,外侧是边界,中间图片是摇杆
2:使用inputSYSTEM创建事件
3:玩家物体上绑定脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float speek = 5; MyInputAction inputActions; Rigidbody rg; private Vector2 move; void Awake() { inputActions = new MyInputAction(); rg = this.GetComponent<Rigidbody>(); } // Update is called once per frame void Update() { rg.velocity = new Vector3(move.x * speek, 0,move.y * speek); } private void OnEnable() { inputActions.Enable(); inputActions.PlayerMove.move.performed += Move_performed; inputActions.PlayerMove.move.canceled += Move_canceled; } private void Move_canceled(UnityEngine.InputSystem.InputAction.CallbackContext obj) { move = Vector2.zero; } private void Move_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj) { move = obj.ReadValue<Vector2>(); } private void OnDisable() { inputActions.Disable(); inputActions.PlayerMove.move.performed -= Move_performed; } }
4:UI控件上也绑定相关脚本设置参数如下
通过监听摇杆的选择变化的坐标控制物体进行跟随