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);
    }
}
相关推荐
心疼你的一切1 小时前
【Unity-MCP完全指南:从零开始构建AI游戏开发助手】
人工智能·unity·ai·游戏引擎·aigc·mcp
示申○言舌2 小时前
基于知识库(RAG)系统打造由大模型(LLM)驱动NPC游戏的技术设想
游戏·unity·大模型·知识库·rag·智能npc·npc记忆
前端不太难6 小时前
OpenClaw 如何运行 Claw 资源文件
c++·开源·游戏引擎
avi91117 小时前
UnReal-UE5虚幻蓝图如何修改
ue5·游戏引擎·虚幻·虚幻引擎·ue·蓝图·蓝图逻辑
国家一级摸鱼选手21 小时前
MCP(Model Context Protocol)学习笔记
unity·ai·mcp
会思考的猴子1 天前
Unity3D发布后软件界面右下角出现Trial Version
unity
ellis19701 天前
Unity资源管理框架Addressables[五] 构建
unity
派葛穆1 天前
Unity-鼠标悬停改变图像位置
unity·计算机外设·交互
avi91111 天前
图例设计软件:Focusky,VisualComponents,图片字风格化等试用和推荐,最终还是回到Unity 游戏代码
unity·ai·aigc·游戏开发·设计工具·信息图
张老师带你学1 天前
unity道具,健身房资源
科技·游戏·unity·游戏引擎·模型