Problem with unity grid step movement
I am having problems with my player movement script. At the moment I am checking in the update method if the button has been pressed and then running this coroutine. The problem is if I press the button twice fast the player records the position between the positions and moves outside of grid, if I limit the movement with "canMove" for the duration of coroutine I have to wait for the player to reach the destination before giving another moving isntructions with makes the game a lot less dynamic. How would I go about making it so that the player can receive couple of movement instructions in advance. For example if I press right and right again while moving he would finish the first movement and then move again the same amount a fixed step over time.
Here's the script:
IEnumerator MoveFast(Transform objectToMove, Vector3 targetPosition, float jumpTime)
{
canMove = false;
float t = 0;
Vector3 originalPosition = objectToMove.position;
while (t < 1)
{
t += Time.deltaTime / jumpTime;
objectToMove.position = Vector3.Lerp(originalPosition, targetPosition, t);
yield return null;
}
canMove = true;
}
And in the update:
void Update()
{
if (canMove)
KeyboardMovement();
}
void KeyboardMovement() {
if (Input.GetKeyDown(KeyCode.DownArrow))
{
coroutine = MoveTo(transform.position, transform.position +
new Vector3(0, -4, 0), 0.5f);
StartCoroutine(coroutine);
}
}
You could declare a List that holds the movement commands (likely in the form of a custom class), and on input an element (=movement command) getrs added to it. When the coroutine that actually creates movement is finished, remove the first element from the list (which was just applied in the CR), and check if there is another movement waiting to be applied at the list's first position.