I want to move object continously when I press button just once grid to grid. When I press button to make object move to another direction, it should wait until object is right on the grid and starts to move another direction. Those are my codes. It moves continously when I press once but doesn’t move grid to grid
void GridMove()
{
Debug.Log("ye");
if(Input.GetKeyDown(KeyCode.W))
{
forward = true;
back = false;
left = false;
right = false;
}
if (forward)
{
StartCoroutine(MoveCharacter(Vector3.forward * Time.deltaTime));
}
if (Input.GetKeyDown(KeyCode.S))
{
back = true;
forward = false;
left = false;
right = false;
}
if (back)
{
StartCoroutine(MoveCharacter(Vector3.back * Time.deltaTime));
}
if (Input.GetKeyDown(KeyCode.A))
{
left = true;
back = false;
forward = false;
right = false;
}
if (left)
{
StartCoroutine(MoveCharacter(Vector3.left * Time.deltaTime));
}
if (Input.GetKeyDown(KeyCode.D))
{
right = true;
back = false;
forward = false;
left = false;
}
if (right)
{
StartCoroutine(MoveCharacter(Vector3.right * Time.deltaTime));
}
}
private IEnumerator MoveCharacter(Vector3 direction)
{
float elapsedTime = 0f;
originPos = transform.position;
targetPos = originPos + direction;
while (elapsedTime < timeToMove)
{
transform.position = Vector3.Lerp(originPos, targetPos, (elapsedTime / timeToMove));
elapsedTime += Time.deltaTime;
yield return null;
}
transform.position = targetPos;
}