Hi all, this is my 1st answer, and yes I’m new in unity, I’m still make a game where the player move just in X and Z direction, with arrow keys, my problem is:
When I press up/down arrow and at same time I press left/right, nothing append, that’s ok I want it move up/down, but when I press left/right and I press up/down it change, why?
This is the code I put on fixedUpdate.
I try also to invert the code, put left/right up on the code and unity invert the situation, but the problem is not solve.
//Movement
if (Input.GetKey(KeyCode.UpArrow))
{
rigidbody.MovePosition(rigidbody.position + speedH * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.DownArrow))
{
rigidbody.MovePosition(rigidbody.position + -speedH * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
rigidbody.MovePosition(rigidbody.position + -speedV * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.RightArrow))
{
rigidbody.MovePosition(rigidbody.position + speedV * Time.deltaTime);
}
I want who play need to release the key to start to move in a different direction, it’s a puzzle game
Basically what happens is the fact that every update it checks if you press one of those buttons, because of the order and the else it will stop after the first if that returns true. up will go before down, before left, before right.
to solve this add
private KeyCode keyPressed;
Update()
{
if (Input.GetKey(KeyCode.UpArrow) && keyPressed == KeyCode.None || keyPressed == KeyCode.UpArrow && Input.GetKey(keyPressed))
{
rigidbody.MovePosition(rigidbody.position + speedH * Time.deltaTime);
keyPressed = KeyCode.UpArrow;
}
// and add those for the other arrowkeys as well
// then add
if(Input.GetKeyUp(keyPressed))
{
keyPressed = KeyCode.None;
}
}
Input shoudl be in Update to be checked every frame.
Long story short, FU happens at fixed rate, Update happens every frame and your input is generating by OS every frame. If your Update runs 100fps and your FU runs 60fps you have 405 chance your input may be missed.
It eliminates all the if checks. That’s a good place to start. I ended up putting acceleration into it so the changing of directions isn’t so instant but this method works just fine. You don’t have to pass in the Inputs as parameters, that’s just what I did. Hope it helps someone.