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);
    }
}
相关推荐
caimouse5 小时前
Godot Engine 最新版官方文档(简体中文完整翻译 & 精简梳理)
游戏引擎·godot
huizhixue-IT7 小时前
Superpowers 游戏引擎从零开发实战指南
游戏引擎
做cv的小昊19 小时前
计算机图形学:【Games101】学习笔记08——光线追踪(辐射度量学、渲染方程与全局光照、蒙特卡洛积分与路径追踪)
图像处理·笔记·学习·计算机视觉·游戏引擎·图形渲染·概率论
玖玥拾20 小时前
Cocos学习笔记:序列化、配置文件与数据驱动
游戏引擎·cocos2d
RReality20 小时前
【Unity UGUI】血条 / 进度条(HP Bar)
ui·unity·游戏引擎·图形渲染
mxwin1 天前
Unity Shader URP:法线如何进行光照计算
unity·游戏引擎·shader
郝学胜-神的一滴1 天前
中级OpenGL教程 009:用环境光告别模型死黑
前端·c++·unity·godot·图形渲染·opengl·unreal
一锅炖出任易仙1 天前
创梦汤锅学习日记day30
学习·ai·ue5·游戏引擎
mxwin2 天前
Unity URP 中的法线生成完全指南
unity·游戏引擎
游乐码2 天前
Unity基础(十五)LineRender画线功能
unity·游戏引擎