How can i have a max speed for player movement but not for outside forces?

Hey guys,

I am currently trying to find a way to make a booster for my top-down 2D game. I’m expanding from the tutorial: Unity Connect

So currently, what i do have is:

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

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;

    public float thrust;
    public float vel;
    public float maxVel;

    public float boostPower = 5;

    // Must check that the booster is on, or true from it's script
    private BoostScript bs;
    public GameObject boost;

    void Start()
    {
        // For convenience
        rb = GetComponent<Rigidbody2D>();
        // To access other script
        bs = boost.GetComponent<BoostScript>();
    }

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector2 movement = new Vector2(moveHorizontal, moveVertical);
        rb.AddForce(movement * thrust);

        vel = rb.velocity.magnitude;

        // Make velocity equal to the max, if it goes above the given max speed
        if (vel > maxVel)
            rb.velocity = rb.velocity.normalized * maxVel;

    }

    void OnTriggerEnter2D(Collider2D trig)
    {
        if (trig.gameObject.tag == "Boost" && bs.boostOn == true)
            rb.velocity *= boostPower;
    }
}

I understand why my code doesn’t work for what i am trying to do. However, if I don’t have that max velocity if statement, then i can accelerate until i go to fast, but using a boost doesn’t really do anything if i go over it at max speed.

I just can’t think of a way to go around this.

Any suggestions or tips would be greatly appreciated!

You can change the maxVel when a boost is active. Or create a variable that when added to maxVel it increases it to a value that is the max Velocity with a boost. This allows you to increase the players speed at whatever rate you want when a boost is active.

 void OnTriggerEnter2D(Collider2D trig)
     {
         if (trig.gameObject.tag == "Boost" && bs.boostOn == true)
             maxVel += boostMaxIncrease;
             rb.velocity *= boostPower;      
     }

Then subtract the boostMaxIncrease from maxVel when the boost deactives.