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?
Right, sorry! It's pretty simple: Code (CSharp): var moveDir = GetMoveDirection(); if (moveDir == 0) { return; } transform.right = new Vector2(moveDir, 0); 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.
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): var moveDir = GetMoveDirection(); if (moveDir == 0) { return; } //transform.right = new Vector2(moveDir, 0); var relativeMove = new Vector2(moveDir * walkSpeed, 0) + (Physics2D.gravity * rb.gravityScale); rb.MovePosition(rb.position + relativeMove * Time.fixedDeltaTime); 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