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!^^