AddForce90 Jump while moving Rigidbody with MovePosition
Hi, all!
Inside of fixedUpdate, I move my character every frame with Rigidbody2D.MovePosition() and I have a speed variable that is -1 with LeftArrow, 1 with RightArrow, and 0 with no input.
This works great. I'm trying to do an AddForce Jump with Impulse, however, and although the jump function executes, the player doesn't jump. I'm assuming this is because MovePosition is overwriting the Jump. Is there a way around this?
void FixedUpdate(){
if (Input.GetKeyDown (KeyCode.UpArrow) && IsGrounded ()) {
myBody.isKinematic = false;
myBody.AddForce (new Vector2 (0, jumpForce), ForceMode2D.Impulse);
}
//TODO: Player can't jump unless movement is commented out
myBody.MovePosition (transform.position + (Vector3.right * currentSpeed * Time.fixedDeltaTime));
}
Thanks! - YA
Answer by MelvMay · Dec 06, 2015 at 02:35 PM
MovePosition doesn't overwrite anything. It simply calculates the velocity required to move the body to the specified position in the next update. It stores the current velocity first and restores it immediately afterwards.
By applying your force as an impulse, you immediately update the velocity. When you call MovePosition, that velocity will be stored but not used in the next update (the MovePosition velocity will). In the subsequent update, the velocity you modified via the impulse would be used but, from what I can see, you are continually updating the position so any velocity the body has will never, ever be used.
You can't constantly tell a body to move to a position each fixed update and then expect the body velocity to move it somewhere else.
Stop using MovePosition like this. Instead, use AddForce to move the body.
I found my own solution by manually setting the velocity. Using AddForce to move the player would cause the player to gain speed quickly and shoot around.