Search Unity

MovePosition Bug

Discussion in '2D' started by crystalfire7, Sep 9, 2019.

  1. crystalfire7

    crystalfire7

    Joined:
    Jan 27, 2018
    Posts:
    2
    Hello everyone!

    I was coding a basic movement system in 2D, using MovePosition. However, calling MovePosition appears to repeatedly reset the y velocity to zero, preventing the character's fall from accelerating.

    Anyone know of the possible solution?
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    1,908
    Are you constantly calling MovePosition? If so, how can gravity affect it?
     
  3. Helladah

    Helladah

    Joined:
    May 5, 2018
    Posts:
    228
    it would be a lot easier to us if you put the code so we can helps you to debug it ^^
     
  4. crystalfire7

    crystalfire7

    Joined:
    Jan 27, 2018
    Posts:
    2
    Right, sorry!

    It's pretty simple:
    Code (CSharp):
    1. var moveDir = GetMoveDirection();
    2.   if (moveDir == 0) {
    3.     return;
    4.   }
    5.    
    6. transform.right = new Vector2(moveDir, 0);
    7. rb.MovePosition(rb.position + new Vector2(moveDir * walkSpeed * Time.fixedDeltaTime, 0));
    moveDir is -1 if moving left, 1 if moving right, and 0 if no input.

    This bit of code is part of FixedUpdate. I assumed that if I didn't make any changes to the Y position, gravity would still be able to take effect.
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    1,908
    Setting the Transform pose is the responsibility of the Rigidbody2D so do not ever manipulate the Transform when you have a physics component on it. You are stomping over what it's try to do and it'll have to then try to stabilize things during the next simulation. Even worse if you're doing this continuously.

    MovePosition does its best to ensure you're at the specified position at the end of the next simulation step. It has no way to know that you want to move to that position but also add gravity. If you want to move to a position including gravity (or any other positional modification) then you need to add it yourself.

    For gravity you simply need to do something like (I've not checked this for syntax):
    Code (CSharp):
    1.     var moveDir = GetMoveDirection();
    2.       if (moveDir == 0) {
    3.         return;
    4.       }
    5.    
    6.     //transform.right = new Vector2(moveDir, 0);
    7.     var relativeMove = new Vector2(moveDir * walkSpeed, 0) + (Physics2D.gravity * rb.gravityScale);
    8.     rb.MovePosition(rb.position + relativeMove * Time.fixedDeltaTime);
    9.  
    Note: Here's the line of code in the Box2D source that calculates gravity if you're interested: https://github.com/erincatto/Box2D/...00c2617d6ae1/Box2D/Dynamics/b2Island.cpp#L206
     
    Helladah likes this.