简体   繁体   English

如何使用 UI 按钮模拟键盘按下?

[英]How do I simulate a keyboard press using an UI button?

I'm trying to port a runner game I made for PC onto Android, so I already have full player control set up using the Space bar, Up arrow, Down arrow, and s button so I wanted to be able to just create UI buttons that simulate a keyboard keypress.我正在尝试将我为 PC 制作的跑步游戏移植到 Android 上,所以我已经使用空格键、向上箭头、向下箭头和 s 按钮设置了完整的玩家控制,所以我希望能够只创建 UI 按钮模拟键盘按键。

Is there any way for me to, for instance, create a script that states that OnButtonPress trigger a keyboard key such as the Space key for jumping?例如,我有什么方法可以创建一个脚本,说明OnButtonPress触发键盘键,例如用于跳跃的空格键?

Instead of simulating inputs, you can split the work out into functions that can be called from either event.您可以将工作拆分为可以从任一事件调用的函数,而不是模拟输入。

Example for jump-跳跃示例——

private void DoJump()
{
    // Jump logic here
}

PC Input电脑输入

private void Update()
{
    if (Input.GetKeyUp(KeyCode.Space))
    {
        DoJump();
    }
}

Mobile Input移动输入

[SerializeField]
private Button jumpButton; // <- assign this in inspector

private void Awake()
{
    jumpButton.onClick.AddListener(() => DoJump());
}

Another alternative to this setup is using the new input system.此设置的另一种替代方法是使用新的输入系统。 The new input system allows you to map inputs from different sources to the same action.新的输入系统允许您将来自不同来源的输入映射到相同的操作。 New Input System . 新的输入系统

This is my preferred way of handling inputs now when controller, mouse/keyboard, and joystick support are required.当需要控制器、鼠标/键盘和操纵杆支持时,这是我现在处理输入的首选方式。

For an existing project where you have everything working as expected, it is often easier and less work to use the first example above.对于一个现有项目,您的一切都按预期工作,使用上面的第一个示例通常更容易且工作量更少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM