- Home /
How to take only one key input at a time
Hello I am making a 2.5D Mario type game. Below is a part of my player script. In that script when my player is moving in the right direction, if I press a 'left arrow' key or 'a' key my player rotates in that direction and moves. The issue is while my player is moving in the right direction and if I press left arrow key my player rotates in the left direction but moves in right direction. The same happens when my player is going in the left direction. How do I make sure that it takes only one key input. Can you please help me.
Answer by Ossi101 · Aug 18, 2021 at 04:53 PM
When you check to see what arrow you pressed in FixedUpdate() the if statements corresponding to what direction you pressed have to set the same direction to false after your rotation. There's no need to toggle the other direction in Update().
public class Example: MonoBehaviour
{
bool isLeftPressed = false;
bool isRightPressed = false;
private void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
isLeftPressed = true;
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
isRightPressed = true;
}
}
private void FixedUpdate()
{
// Gets called once depending on what arrow was pressed.
if (isLeftPressed)
{
Debug.Log("Rotate Left");
isLeftPressed = false;
}
else if (isRightPressed)
{
Debug.Log("Rotate Right");
isRightPressed = false;
}
}
}
I hope this helps!
Your answer

Follow this Question
Related Questions
Rotation troubles 2 Answers
Sprites always face the camera, Camera freely rotates 3 Answers
Rotate player to aim on one axis (Z-axis) towards mouse position/joystick - 2.5D (3D) 0 Answers
Point an arrow at the mouse position, 2.5D 1 Answer
How to achieve Luftrauser like airplane gameplay in 2.5D 1 Answer