How would I make an acceleration?

I’m making a 2D player controller and thought having acceleration and deceleration similar to celeste would make the game feel better, but everything I’ve tried doesn’t seem to work.

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public Rigidbody2D rigidBody;

    public float maxSpeed;
    public float jumpHeight;
    public float castDistance;
    public float accelerationRate;
    public Vector2 boxSize;
    public LayerMask groundLayer;

    private float horizontalInput;
    private float gravityScale;

    private void Start()
    {
        gravityScale = rigidBody.gravityScale;
    }

    private void Update()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");

        if (Input.GetKeyDown(KeyCode.Space) && Grounded())
        {
            rigidBody.linearVelocity = transform.up * jumpHeight;
        }
        else if (rigidBody.linearVelocityY < 0)
        {
            rigidBody.gravityScale = gravityScale * 1.5f;
            
        }
        else
        {
            rigidBody.gravityScale = gravityScale;
        }
    }

    private void FixedUpdate()
    {
        float acceleration = maxSpeed / accelerationRate;
        float speed = acceleration;
        speed = speed * accelerationRate;

        rigidBody.AddForce(new Vector2(horizontalInput * speed, 0));
    }

    private bool Grounded()
    {
        if (Physics2D.BoxCast(gameObject.transform.position, boxSize, 0f, -transform.up, castDistance, groundLayer))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireCube(transform.position - transform.up * castDistance, boxSize);
    }
}

Easiest is to just read the inputs directly into a desiredMovement variable, then smoothly change a currentMovement variable.

For the actual change to the Rigidbody, you would use the currentMovement

NOTE: this can apply to any type of movement: linear, 2D, 3D, whatever, and you can if you like handle each axis independently, so each axis has its own “snappiness.”

Here’s the details:

Smoothing the change between any two particular values:

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: SmoothMovement.cs · GitHub

1 Like