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);
}
}