Hello guys! I want to slow down the player's speed when i let up my left mouse button. I tried everything but nothing work. Please help! Thanks.

Here is my code so far

private Rigidbody2D rB;
private Vector2 mousePos;
private float speed = -10.0f;
private bool canSlow;

// Start is called before the first frame update
void Start()
{
    rB = GetComponent<Rigidbody2D>();
    canSlow = false;
}

// Update is called once per frame
void Update()
{
    if (canSlow)
    {
        speed += 0.1f;
    }
      
    mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    if (Input.GetMouseButton(0)) // If pressing the mouse
    {
        Vector2 lookDir = mousePos - rB.position;
        float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
        rB.rotation = angle;
    }

    if (Input.GetMouseButtonUp(0)) // If let up the mouse
    {
        canSlow = true;
        rB.AddForce(transform.up * speed * Time.deltaTime, ForceMode2D.Impulse);
    }
}

You start with a speed of -10, which is fair enough. When you “canSLow”, you reduce that number - again fair enough. The problem is that you are still adding a force in the rB.AddForce line since speed is still negative. That means that for 100 frames, you are adding a force in the same direction as before, which will accelerate your player.

If you want to start slowing down immediately, you need to add a force that is positive so set speed to zero and then increment it. However you need to make sure you don’t overshoot. You might do better to start reducing rb.velocity and stop at the appropriate time.

Thanks it worked!