Search Unity

Question about rigidbody2d movement calculations

Discussion in '2D' started by DoronD, Apr 4, 2021.

  1. DoronD

    DoronD

    Joined:
    Aug 12, 2018
    Posts:
    3
    Hi there,

    So I'm making a simple 2D space game, and I have an orthographic camera (the main camera) that moves by the following:

    FixedUpdate - Camera Movement()
    Code (CSharp):
    1. theCamera.position = new Vector3(theCamera.position.x + 0.02f, theCamera.position.y, theCamera.position.z);
    For my ship movement, because of the camera moving (used for parallax stuff), I had to move the ship to keep up with the camera movement.

    Start()
    Code (CSharp):
    1. prevPosX = theCamera.transform.position.x;
    FixedUpdate Ship Movement()
    Code (CSharp):
    1. var cameraPos = theCamera.transform.position.x;
    2. float translationX = Input.GetAxis("Horizontal");
    3. float translationY = Input.GetAxis("Vertical");
    4. float calculatedKeepUp = (cameraPos - prevPosX) * 7f;
    5. Vector3 movement = new Vector3(translationX + calculatedKeepUp, translationY, 0.0f);
    6. prevPosX = cameraPos;
    7. rigidBody2D.velocity = movement * speed;
    So basically the calculatedKeepUp is 0.02f * 7, which is 0.14f

    The problem is, the ship still drifts with that value.
    If I set the calculatedKeepUp to 0.1430f the ship is moving perfectly with the camera movement.

    So, my question is...where in all that's holy is the extra 0.003f coming from??
     
  2. DoronD

    DoronD

    Joined:
    Aug 12, 2018
    Posts:
    3
    I think it's a floating point precision problem...

    I added some logs to my camera position and the ship position, and saw the following:

    Fixed update 1:
    Camera Pos: 3.14
    Ship Pos: 0

    Fixed update 2:
    Camera Pos: 3.16
    Ship Pos: 0.01959997

    So, I was expecting the pos to move by 0.02f, but it did not.
    Maybe due to it being set by rigidbody velocity maybe.

    0.01959997, let's say 0.0196 x 7(ship speed) = 0.1372
    0.14 (what I was expecting) - 0.1372 = 0.0028 or 0.003...Mystery somewhat solved!

    This probably won't bug the player as they wont keep the ship still long enough to notice such a minor drift, but I don't like leaving things unknown (even though the velocity calculation is still a mystery)
     
  3. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Yup, it's exactly that.
    Precision loss is an inevitability in any floating-point number calculations.
     
    DoronD likes this.
  4. DoronD

    DoronD

    Joined:
    Aug 12, 2018
    Posts:
    3
    Yeah, I'll stop being so picky about decimal places unless it's absolutely necessary :D

    I just checked, and the line:
    float calculatedKeepUp = (cameraPos - prevPosX) * 7f;

    actually returns 0.1399999...I really thought it would have been 0.14!

    So there we go...Thanks floats !