Search Unity

[Solved] Finally! Nailed down 'Accelerating Object Speed Only After 'X' Seconds'

Discussion in 'Scripting' started by Alien_J, Oct 5, 2020.

  1. Alien_J

    Alien_J

    Joined:
    May 29, 2019
    Posts:
    70
    I spent so long GOOGLE'ing, and watching a buttload of videos that mostly was about rigidbody. And I don't need rb on this specific object.

    Coroutines just wasn't working for me. InvokeRepeating was pretty close, but the start was too slow, and trying to get the right acceleration and max speed... UGH.

    I came across a couple different posts that were close to what I needed. It just took a couple extra days to figure out how to combine the two to make things work.

    So for anyone else that may need something like this. It uses invokerepeating and Mathf.SmoothStep.

    And a huge shout out to @Hellium for that Mathf.SmoothStep snippet.

    Code (CSharp):
    1. {
    2.     float currentSpeed = 0f;
    3.     float speedLimit = 5f;
    4.     private float minSpeed;
    5.     private float time;
    6.  
    7.     public float maxSpeed = 5f;
    8.     public float accelerationTime = 5f;
    9.    
    10.  
    11.     private void Start()
    12.     {
    13.         //Wait 'X' seconds for initial execution, execute every 'X' seconds
    14.         InvokeRepeating("IncreaseSpeed", 0f, 10f);
    15.  
    16.         minSpeed = currentSpeed;
    17.         time = 0;
    18.     }
    19.  
    20.  
    21.     private void Update()
    22.     {
    23.  
    24.         currentSpeed = Mathf.SmoothStep(minSpeed, maxSpeed, time / accelerationTime);
    25.         transform.Rotate(new Vector3(currentSpeed * Time.deltaTime * 1, 0, 0));
    26.         time += Time.deltaTime;
    27.  
    28.         Debug.Log(currentSpeed);
    29.  
    30.     }
    31.  
    32.     public void IncreaseSpeed()
    33.     {
    34.         maxSpeed = currentSpeed + speedLimit;
    35.         currentSpeed += maxSpeed;
    36.  
    37.     }
    38.  
    39. }