# Move Player until Endpoint

I tried to make a script that moves my player until it reaches the end point. This is what I have so far:

``````void Moving()
{
Debug.Log ("My Pos: " + transform.position);
Debug.Log ("Target Pos: " + EndPos);
Debug.Log ("-----------------");
switch (direction) {
case 1:
rigidbody2D.velocity = new Vector2 (0, -moveSpeed);
break;
case 2:
rigidbody2D.velocity = new Vector2 (0, moveSpeed);
break;
case 3:
rigidbody2D.velocity = new Vector2 (-moveSpeed, 0);
break;
case 4:
rigidbody2D.velocity = new Vector2 (moveSpeed, 0);
break;
case 5:
rigidbody2D.velocity = new Vector2 (moveSpeed, moveSpeed);
break;
case 6:
rigidbody2D.velocity = new Vector2 (moveSpeed, -moveSpeed);
break;
case 7:
rigidbody2D.velocity = new Vector2 (-moveSpeed, -moveSpeed);
break;
case 8:
rigidbody2D.velocity = new Vector2 (-moveSpeed, moveSpeed);
break;
}
if ((Mathf.Approximately(transform.position.x,rollEndPos.x))&&(Mathf.Approximately(transform.position.y,rollEndPos.y))&&(Mathf.Approximately(transform.position.z,rollEndPos.z)))
{
Debug.Log ("Reached Point!");
rigidbody2D.velocity = new Vector2 (0, 0);
}
}
``````

The Player moves like I wish. Thanks to Jeff Kesselman I now know that the problem is a “roundoff error”. So I added the Mathf.Approximately. But I still have sometimes the problem that my player don’t stop at the Endpoint. It work in 50% of the cases.
This is my Debug.Log:

`````` My Pos: (-11.5, -8.3, 0.0)
Target Pos: (-11.6, -8.3, 0.0)
-----------------
My Pos: (-11.6, -8.3, 0.0)
Target Pos: (-11.6, -8.3, 0.0)
-----------------
My Pos: (-11.7, -8.3, 0.0)
Target Pos: (-11.6, -8.3, 0.0)
``````

By the way: The set of my endposition and my Speed works correctly. In another version of this script it works perfectly, but in that version I change the transform.position but I want to use the 2D physics.

Thank you very much for your help!^^

Since you’re using physics you could check, if the distance to the endpoint times Time.fixedDeltaTime is shorter than your velocity times Time.deltaTime. if it is, set velocity to distance. Since FixedDeltaTime always stays the same, you should end at your endpoint on the spot the next FixedUpdate.

``````void FixedUpdate(){
Vector3 distance = (endposition - transform.position);
if (distance.magnitude * Time.fixedDeltaTime < rigidbody2D.velocity.magnitude)
rigidbody2D.velocity = distance;
}
``````