Search Unity

Bug Rigidbody2D.MovePosition behaving differently between editor and build (PC)

Discussion in '2D' started by NisioX, Mar 25, 2023.

  1. NisioX

    NisioX

    Joined:
    Aug 10, 2021
    Posts:
    1
    (I apologize if my english is a bit broken)
    Hello!
    I need help for a problem with RigidBody2D: I have a script called Entity that contains the following FixedUpdateMethod:
    Code (CSharp):
    1. public virtual void FixedUpdate()
    2.     {
    3.         velocity.x = Mathf.Clamp(velocity.x, -maxVelocity.x, maxVelocity.x);
    4.         velocity.y = Mathf.Clamp(velocity.y, -maxVelocity.y, maxVelocity.y);
    5.  
    6.         rb.MovePosition(velocity * Time.fixedDeltaTime + (Vector2)transform.position);
    7.     }
    and a PlayerController script that override FixedUpdate:
    Code (CSharp):
    1. public override void FixedUpdate()
    2.     {
    3.         velocity.x = Input.GetAxisRaw("Horizontal") * speed;
    4.         base.FixedUpdate();
    5.     }
    The problem is that the player doesn't go at the same speed between the editor and build version. In the editor, velocity.x * Time.fixedDeltaTime as a value of 0.2 and the difference between transform.position.x and the transform.position.x of the last frame is always equal to velocity.x * Time.fixedDeltaTime. But in the build, velocity.x * Time.fixedDeltaTime as the correct value of 0.2, but the difference in x position between two frames switches back and forth between 0.2 and 0.1.

    I also checked others variables that could cause a problem like this (like Time.fixedDeltaTime, speed, rb.drag etc.) but they all are equal between the two versions.

    I searched for a good hour on google and by experimenting but couldn't find anything so i don't know if i just haven't seen an evident error or if it's a bug in unity...

    If you need more informations don't hesitate to ask them (it will surely be the case because i'm not very good to provide them ^^)
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,497
    It doesn't behave differently. Physics is not broken. ;)

    Did you look at the docs here? Is this a Kinematic or Dynamic body?

    One obsevation is that you should NEVER use the Transform as the authority on the current position of the body as the Transform won't be the same as the body if Interpolation is being used.

    Use Rigidbody2D.position instead.

    Remember, the Rigidbody2D is the authority here for reading position and getting it to change.

    You should also not be reading input during the FixedUpdate; that's a per-frame thing.