Home > OS >  Unity Engine: 2D Rigid body is falling slowly after adding movement?
Unity Engine: 2D Rigid body is falling slowly after adding movement?

Time:12-19

I was attempting to put simple movement into a project and for some reason this has caused the object its applied to to fall extremely slow. I am using the newer input system and I haven't really been using it previously so I'm unsure if it's an error regarding that.

The movement is working as intended so far. Gravity is at default in settings.

public class Movement : MonoBehaviour
{
    public Rigidbody2D rb;

    public float moveSpeed = 4f;
    public InputAction playerControl;

    Vector2 moveDirection = Vector2.zero;

    private void OnEnable()
    {
        playerControl.Enable();
    }
    private void OnDisable()
    {
        playerControl.Disable();
    }

    // Update is called once per frame
    void Update()
    {
        

        moveDirection = playerControl.ReadValue<Vector2>();
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
    }
}

This is what I have applied to the player object so far. When actually moving there is no issue, but falling doesn't work as intended

CodePudding user response:

In FixedUpdate, you set the velocity of the RigidBody, including the y component. This does not interact well with gravity.

Gravity decreases the vertical speed of the RigidBody2D to make the object fall. Meanwhile, your code erases these changes each frame, which means that it cannot accelerate downwards, leading to it falling very slowly and at a constant speed (rather than accelerating downwards as expected).

If you have complete control over your vertical movement, how would gravity work? If the player is not meant to be able to control their vertical movement, change the line to:

rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.velocity.y);

This will fix the issue but will remove your vertical control. Is this what you want?

If you want to keep vertical movement but not overwrite gravity, you have to make some kind of compromise. If you want gravity to act whenever you are not controlling your character's vertical movement, you can do something like this:

if (moveDirection.y > 0.001)
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
else
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.velocity.y);
}

You can also add the vertical movement to your vertical speed. This will mean that the player does not have complete control over their vertical speed like their horizontal speed, but rather being able to apply a force against it.

rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.y   moveDirection.y * verticalMoveSpeed);
  • Related