- Home /
How do I have multiple controls for the same function? (Controller and Keyboard)
I am working on a simple platformer game and so far the controls are working, but will only work for one set of controls at a time, either the Xbox One controller or the keyboard. I want the player to have the option to use either for moving left or right with the character.
But how do I set 2 different inputs to the same float?
With this current code, it still recognizes the controller input, but will only flip the sprite, while the keyboard will flip the sprite and move the character.
float move = Input.GetAxis ("LeftJoystickX");
GetComponent<Rigidbody2D>().velocity = new Vector2 (move * movementSpeed, GetComponent<Rigidbody2D>().velocity.y);
if (move > 0 && !facingRight)
Flip ();
else if (move < 0 && facingRight)
Flip ();
float moveK = Input.GetAxis ("Horizontal");
GetComponent<Rigidbody2D>().velocity = new Vector2 (moveK * movementSpeed2, GetComponent<Rigidbody2D>().velocity.y);
if (moveK > 0 && !facingRight)
Flip ();
else if (moveK < 0 && facingRight)
Flip ();
Answer by Shark-Boy · Jun 19, 2015 at 12:57 AM
You could use a if to check if you are getting input from the keyboard and if not then check the gamepad. It would look something like this.
float move = 0f;
float inputKeyboard = Input.GetAxis ("Horizontal");
float inputGamepad = Input.GetAxis("LeftJoystickX");
if (inputKeyboard > 0.1 && inputKeyboard < -0.1)
{
move = inputKeyboard;
}
else if (inputGamepad > 0.1 && inputGamepad < -0.1)
{
move = inputGamepad;
}
Then use move for fliping the sprite and the rigidbody2d.velocity.
Also using GetComponent() every frame is hard on you computer so the standard practice is to create a variable called something like rigidbody2d (no caps) and in the start function set it to GetComponent like this.
using System;
// and all the other using stuff
public class myClass : MonoBehaviour {
Rigidbody2D rigidbody2d;
void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
}
}
Then you can use that variable to set the velocity like this.
rigidbody2d.velocity = // something
Hope this helps!
Your answer
Follow this Question
Related Questions
Gradual Speed Increase with Variable Input 0 Answers
Code for - Rigidbody vs Character Controller 0 Answers
Player inversed inputs 0 Answers
How to get a character to stay on a moving platform? 3 Answers