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);
    }
}
相关推荐
Solange__9 小时前
在线3D预览器、Blender和游戏引擎怎么选?按5类任务比较格式、隐私与编辑性
人工智能·游戏·3d·游戏引擎·blender·1024程序员节·关卡设计
peter676812 小时前
unity2d游戏开发经验总结
unity
郝学胜-神的一滴12 小时前
游戏设计:原型与开发 19:U3D工位布置与性格说明书
人工智能·算法·unity·unreal engine·游戏策划·游戏设计
Aman19841 天前
Claude Code做Unity项目移植(二): 自动执行只读操作,告别频繁的
unity·游戏开发·vibe coding·claude code
暴走约伯1 天前
【VFX工具链源码拆解 02】告别机械劳动(上):一键统改百个子粒子颜色与批量重命名
3d·unity·c#·材质
郝学胜-神的一滴1 天前
游戏设计:原型与开发 18:Unity入门的第一课
人工智能·程序人生·游戏·ui·unity·游戏引擎
淡海水1 天前
09-01-内存-Unity资源生命周期全景
unity·c#·游戏引擎·.netcore·gc
Solange__2 天前
AI世界模型、3D场景生成和游戏引擎怎么选?按5类任务比较交互、物理与导出
开发语言·人工智能·游戏·平面·3d·自然语言处理·游戏引擎
LF男男2 天前
Flower Defense—UIFacade
unity
呆呆敲代码的小Y2 天前
【实战精选面试题】Unity精选面试题详细解答,按模块整理汇总
人工智能·游戏·unity·游戏引擎