Reputation: 1
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.
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?
Upvotes: 0
Views: 1659
Reputation: 4591
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.
Upvotes: 1