Search Unity

MovePosition not exact inside FixedUpdate()

Discussion in 'Physics' started by gogocook25, Dec 28, 2018.

  1. gogocook25

    gogocook25

    Joined:
    Sep 30, 2018
    Posts:
    36
    Hi, I'm using MovePosition to make my 2D sprite "fly" toward the mouse position. I call MovePosition inside FixedUpdate, and it works to some extent, moving the sprite to the approximate location of the mouse. However, I noticed by logging the position of the sprite that it never quite reaches the destination, usually stopping .2 units short on the y axis.

    I call this function from FixedUpdate:


    Code (CSharp):
    1.     protected bool moveToMouse(Vector3 mousePos)
    2.     {
    3.         float sqrRemainingDistance = (mousePos - transform.position).sqrMagnitude;
    4.         Debug.Log("mouse position: " + mousePos + " duck position: " + transform.position);
    5.         if (sqrRemainingDistance > .1f)
    6.         {
    7.             Vector3 destVector = mousePos - transform.position;
    8.             Debug.Log(destVector.normalized);
    9.             rb2d.MovePosition(transform.position + destVector.normalized * Time.fixedDeltaTime); //completes 1 unit movement per second
    10.             return false;
    11.         }
    12.         Debug.Log("movement over");
    13.         return true;
    14.     }
    But it never returns true. It gets stuck short of the destination:

    mouse position: (-5.8, -2.7, -1.1) duck position: (-5.9, -2.9, 0.0)