Player Movement Not Always Responding
Hello,
I am working on a 2D game that currently moves the player object up and down. My goal is to have the object move for only a specific time after the up or down arrow is pressed (it will continue moving for the specified time, regardless of whether the key is held down or not). After it stops, the player will be able to press either key again.
The script I made works most of the time, but sometimes when a key is pressed the object does not move. Sometimes it will work on the next press, sometimes it will take a few more presses, but it will always eventually resume its movement.
public float speed; //set to 5
public float moveSeconds; //set to 0.1
void FixedUpdate()
{
if (Input.anyKeyDown == true) {
StartCoroutine (MovePlayer ());
}
}
IEnumerator MovePlayer() {
Vector2 movement = new Vector2 (0.0f, speed);
Vector2 negMovement = new Vector2 (0.0f, -speed);
if (Input.GetKeyDown (KeyCode.UpArrow)) {
GetComponent<Rigidbody2D> ().velocity = movement;
} else if (Input.GetKeyDown (KeyCode.DownArrow)) {
GetComponent<Rigidbody2D> ().velocity = negMovement;
}
yield return new WaitForSeconds (moveSeconds);
GetComponent<Rigidbody2D> ().velocity = movement * 0;
}
Note: The reason movement and negMovement are in MovePlayer() is because speed is eventually going to change.
I also noticed that changing all of the Input statements from ...KeyDown to ...Key fixed the movement problem, but I don't want continuous movement. I only want one press of the key and a fixed movement time.
Answer by Cuttlas-U · Oct 22, 2017 at 05:02 PM
hi; the problem is about the corutine; each time u press the key a corutine created this is while maybe your last corutine is not finished yet;
so u have to check if its finished or not or stop the last corutine first;