Unity使用新输入系统控制物体移动

介绍

Unity 的 新输入系统(Input System) 是一个强大且灵活的输入管理工具,支持多种输入设备(如键盘、鼠标、手柄、触摸屏等),并且比旧版输入系统(UnityEngine.Input)更现代化和可扩展

使用

1. 安装 Input System 包

打开 Unity 编辑器。

进入 Window > Package Manager。

在 Package Manager 中搜索 Input System。

点击 Install 安装 Input System 包。

2. 启用 Input System

打开 Edit > Project Settings > Player。

在 Other Settings 下找到 Active Input Handling。

将其设置为 Input System (New) 或 Both(如果需要同时支持旧版和新版输入系统)。

重启 Unity 编辑器以应用更改。

3. 创建 Input Actions

在物体上添加组件"Player Input",点击"Create Actions",保存到"Setting/InputControl"文件夹下,并生成对应脚本


4. 在代码中使用 Input System

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerControl : MonoBehaviour
{
    private PlayerInputControl inputControl;
    private Vector2 inputDirection;
    private Rigidbody2D rb;
    private float speed = 20;

    private void Awake()
    {
        inputControl = new PlayerInputControl();
        rb = GetComponent<Rigidbody2D>();
    }

    private void OnEnable()
    {
        inputControl.Enable();
    }

    private void OnDisable()
    {
        inputControl.Disable();
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        inputDirection = inputControl.Player.Move.ReadValue<Vector2>();
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(speed * inputDirection.x * Time.deltaTime, rb.velocity.y);
    }
}
相关推荐
温玉琳琅39 分钟前
【UE5】虚幻引擎小百科
ue5·游戏引擎·虚幻
两水先木示4 小时前
【Unity3D】微信小游戏适配安全区域或胶囊控件(圆圈按钮)水平高度一致方案
unity·微信小游戏·安全区域·ui适配·胶囊控件·safearea
枯萎穿心攻击5 小时前
ECS由浅入深第三节:进阶?System 的行为与复杂交互模式
开发语言·unity·c#·游戏引擎
不绝1915 小时前
怪物机制分析(有限状态机、编辑器可视化、巡逻机制)
网络·游戏·unity·游戏引擎
unicrom_深圳市由你创科技6 小时前
Unity开发如何解决iOS闪退问题
unity·ios·蓝桥杯
Yasin Chen11 小时前
C# Dictionary源码分析
算法·unity·哈希算法
深海潜水员19 小时前
【Behavior Tree】-- 行为树AI逻辑实现- Unity 游戏引擎实现
游戏·unity·c#
Thomas_YXQ1 天前
Unity3D游戏内存优化指南
游戏·unity·职场和发展·性能优化·蓝桥杯·游戏引擎·unity3d
chillxiaohan1 天前
Unity接入Steamworks.NET实现通信功能
unity
枯萎穿心攻击2 天前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎