- Home /
How to detect two keys released simultaneously [Input System]
I want the player to turn to face the direction of input, and stay facing that direction even after the keys are released. The problem is that when two buttons are pressed and the player's facing a diagonal, letting go of both keys leaves the player facing in one of two directions (either forward/backward or left/right) but never diagonal.
Looking at the console it seems that when I release both keys, for a few frame it's registering one of the axes being pressed and not the other. No matter how exact I try to be, there's at least one frame where one keys pressed and not the other.
How would I be able to detect that both keys were released?
void Update()
{
movementDir = movement.ReadValue<Vector2>();
//if movementDir != (0,0)
if (movementDir.magnitude > 0.01f)
{
transform.forward = new Vector3(movementDir.x, 0, movementDir.y);
Debug.Log(movementDir.magnitude + " " + movementDir);
}
else
{
Debug.Log("pressing nothing: " + movementDir);
}
}
Answer by rh_galaxy · Sep 11, 2020 at 04:21 AM
You could make a delay for movement, so it must be the same for example for 4 frames to give a new movement, like this:
Vector2[] moveLastDir = new Vector2[4];
Vector2 moveNewDir = new Vector2(0, 0);
int curDir = 0;
moveLastDir[curDir] = movement.ReadValue<Vector2>();
if (moveLastDir[(curDir + 3) % 4] == moveLastDir[curDir]) moveNewDir = moveLastDir[curDir];
curDir++; curDir %= 4;
if (moveNewDir.magnitude > 0.01f) {
transform.forward = new Vector3(moveNewDir.x, 0, moveNewDir.y);
}
Debug.Log(moveNewDir.magnitude + " " + moveNewDir);
But if you have a fast framerate like 1000 you will still have problems with buttons not releasing at the same frame. So the best thing would be to implement some steering towards a direction. And either take the nearest direction of the 8 distinct 45 deg directions or have free steering angle.
Thank you that method works! I can see how at higher framerates there would still be problems. By steering do you mean that each frame the character rotates a bit towards the target direction instead of being set to exactly to the target direction?
Yes, so that you change the direction a little each frame towards a goal, and either have that as the direction or round it to the nearest 45 deg angle. But it depends on what type of game/program you are making.
Got it, that makes sense. Thanks for your help!
Your answer
Follow this Question
Related Questions
How to consume input when automatically switching control schemes through a Player Input Component 0 Answers
transforming player position on input.get button down 1 Answer
How to use PlayerInput In Conjunction with C# Events? 0 Answers
Have a character face their moving direction? 1 Answer
Trying to find what player inputed in Text Input field 1 Answer