MovePosition Not Working With Sidescroller Platformer

I’m making a sidescrolling platformer game. I’ve never made one before, but I thought it would be simple enough. I wrote a script for the player that handles movement, you can walk left and right and you can jump. This all works fine, however if you try to move horizontally while airborne, the player suddenly stops in the air and starts descending very slowly at a linear rate. This stops when the player stops moving horizontally.

The problem lies within the MovePosition function, however I don’t know how to solve it. Does anyone have any advice?

Here’s the player control script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControl : MonoBehaviour
{
    [SerializeField] float movementSpeed;
    [SerializeField] float jumpForce;

    bool horizontalMovement;

    Vector3 speed;

    private void Update()
    {
        Rigidbody2D rb2D = GetComponent<Rigidbody2D>();

        if (Input.GetKey(KeyCode.A))
        {
            speed = new Vector3(-movementSpeed, 0, 0);
            horizontalMovement = true;
        }
        else if (Input.GetKey(KeyCode.D))
        {
            speed = new Vector3(movementSpeed, 0, 0);
            horizontalMovement = true;
        }
        else
        {
            horizontalMovement = false;
        }

        if (horizontalMovement)
        {
            rb2D.MovePosition(transform.position + speed);
        }

        if (Input.GetKeyDown(KeyCode.Space) && rb2D.velocity.y == 0)
        {
            rb2D.AddForce(transform.up * jumpForce);
        }
    }
}

So you’re asking it to move to a specific position using MovePosition but you’re then also adding forces so it has an inherent velocity so it’ll move. These two are opposite movement methods. If I ask you to move to position A AND move to position B because I give you a push, what will happen? This should be obvious if you step back and think about what it is you’re asking physics to do. You’re adding forces and velocity is increasing but that’s not used because you’re explicitly moving to a specific position when “horizontalMovement” is true. When that’s not true, it’ll have the ability to use the accumulated force you’ve been building up.

MovePosition is typically for Kinematic movement where you’re explicitly controlling the position to move to. You can use it in a Dynamic body but you need to know what you’re doing.

Okay, thanks for explaining. But I still don’t know how to accomplish what I need. I’m just trying to get horizontal movement to work while airborne. I did try to just change the y position of the player directly, but I feel that could lead to some major problems down the line so I decided against it.