# Movement Code Affected by Fps

My current player movement code provides 0.32 transform on each key click.
If it is clicked 2 times very quickly, it should be 0.64.
I provide this with coroutine, but it is affected by fps. How do I ensure that it is not affected by fps?

My current move code:

``````public float move = 0.32f; //movement limitation
public float repeat = 4;  // I perform 0.32 in 4 parts to be more smooth.

void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow) //Exapmle key. I have 4 ways to move
{
StartCoroutine("Left");
}
}

IEnumerator Left()
{
for (int i = 1; i <= repeat; i++)// as I said, I perform 0.32 in 4 parts to be more smooth.
{
transform.position = transform.position + new Vector3(-move / repeat, 0, 0);
yield return null;
}
}
``````

Whenever you are doing something once per frame you need to use Time.deltaTime to convert your quantities from â€śper frameâ€ť to â€śper secondâ€ť. in this case you would multiply the vector you are adding to your position by Time.deltaTime before adding it to the position.

1 Like

Yes, but how do I get exactly 0.32, if I multiply by Time.deltaTime? Time.deltaTime is a unstable variable (eg 0.00249487), how do I get exactly the number I want by multiplying it by that?

You donâ€™t. You keep moving until you have moved that far, then you stop. Vector3.MoveTowards is a nice convenient helper function to achieve this:

``````public float speed = .5f; // Move this many meters per second

IEnumerator Left()
{
// Establish our target position.
Vector3 targetPosition = transform.position + Vector3.left * move;

// Perform the movement
while (transform.position != targetPosition) {
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
// wait one frame
yield return null;
}

// After the loop, teleport exactly to stave off any rounding errors
transform.position = targetPosition;
}
``````
1 Like

Thank you very much!