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);
    }
}
相关推荐
霸王•吕布2 小时前
游戏引擎中顶点着色&像素着色
游戏引擎·顶点着色器·像素着色器·顶点颜色·顶点uv·顶点法向
Thomas_YXQ5 小时前
Unity URP法线贴图实现教程
开发语言·unity·性能优化·游戏引擎·unity3d·贴图·单一职责原则
徐子竣12 小时前
[学习记录]Unity-Shader-几何着色器
unity·游戏引擎·着色器
EQ-雪梨蛋花汤18 小时前
【Part 3 Unity VR眼镜端播放器开发与优化】第四节|高分辨率VR全景视频播放性能优化
unity·音视频·vr
与火星的孩子对话1 天前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
幻世界1 天前
【Unity智能模型系列】Unity + MediaPipe + Sentis + ArcFace模型:构建高效人脸识别比对系统
unity·游戏引擎
漫游者Nova1 天前
虚幻引擎Unreal Engine5恐怖游戏设计制作教程,从入门到精通从零开始完整项目开发实战详细讲解中英字幕
ue5·游戏引擎·虚幻·游戏开发完整教程·恐怖游戏开发
死也不注释2 天前
【Unity 编辑器工具开发:GUILayout 与 EditorGUILayout 对比分析】
unity·编辑器·游戏引擎
小赖同学啊2 天前
物联网中的Unity/Unreal引擎集成:数字孪生与可视化控制
物联网·unity·游戏引擎
Zlzxzw2 天前
使用unity创建项目,进行动画制作
unity·游戏引擎