Unity 2D deceleration function not working

36 Views Asked by At

I have written a C# file for 2D sidescroller player movement. To add some flair, I have attempted to add acceleration and deceleration to the movement, by dynamically calculating the speed of the player based on the previous speed and current direction of movement. While the acceleration works fine, the player automatically snaps back to zero speed as soon as the input is ceased, essentially ignoring the deceleration.

Attached is my code for the movement. Note that Unity's InputSystem plugin is being used.

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

public class PlayerController : MonoBehaviour
{
    private float horizontalController;
    private float horizontal = 1f;
    public float currentSpeed = 0f;
    public float acceleration = 0.03f;
    public float deceleration = 0.1f;
    public float maxSpeed = 50f;
    public float jumpPower = 10f;

    private Rigidbody2D rb;
    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask groundLayer;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        rb.velocity = new Vector2 (currentSpeed, rb.velocity.y); 
        CalculateSpeed();
        Debug.Log(currentSpeed);
    }

    private void Update()
    {
       
    }

    private bool IsGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    }

    public void Jump(InputAction.CallbackContext cc)
    {
        if (cc.performed && IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpPower);
        }

        if (cc.canceled && rb.velocity.y > 0f)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpPower * 0.5f);
        }
    }

    public void Move(InputAction.CallbackContext cc)
    {
        horizontalController = cc.ReadValue<Vector2>().x;
        
    }

    private void CalculateSpeed()
    {
        if(horizontalController > 0.1f)
        {
            currentSpeed += acceleration;
        } else if (horizontalController < 0.1f)
        {
            currentSpeed -= acceleration;
        } else
        {
            if(currentSpeed > 0f)
            {
                currentSpeed -= deceleration;
            } else if(currentSpeed < 0f)
            {
                currentSpeed += deceleration;
            }
        }
        currentSpeed = Mathf.Clamp(currentSpeed, -Mathf.Abs(maxSpeed * horizontalController), Mathf.Abs(maxSpeed * horizontalController));
    }

}

Some assistance would be greatly appreciated; I am going crazy lol.

0

There are 0 best solutions below