Search Unity

Question Help With game I am Making

Discussion in 'Scripting' started by HGTech, Sep 27, 2020.

  1. HGTech

    HGTech

    Joined:
    Dec 20, 2019
    Posts:
    2
    Hello,

    In the game I am making I want speed to increase if the key is pressed faster/spammed but if the key is pressed less (Every 5 seconds for example) Then I want the speed to be slower. Any help is very much appreciated.

    Thanks.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Create a timer system that counts up when the key is pressed and then when the key is pressed again, it calculates the amount of time passed and you can pass that into a switch statement or a math statement to calculate the speed increase. Apply that speed increase, then reset the timer and start it again.
     
  3. Ciava

    Ciava

    Joined:
    Jun 1, 2018
    Posts:
    50
    Hello!
    This is the first time for me trying to give an answer so .... I am afraid to give a bad advice!

    I'd use something like this

    Code (CSharp):
    1. public float speed = 20f;
    2.     public float time;
    3.  
    4.     void Update()
    5.     {
    6.         time += Time.deltaTime;
    7.         if (time >= 5f) { speed -= 1f * Time.deltaTime; }
    8.         if (Input.GetKeyDown("up")) { speed += 0.25f; time = 0f; }
    9.         Debug.Log("Time: " + time);
    10.         Debug.Log("Speed: " + speed);
    11.     }
    So. You set initial speed (= 20f) and then you start the timer ...

    When 5 seconds are passed, speed will decrease by 1f. When you press UP key speed will increase and you must wait again 5 seconds to let speed decrease again.
     
    HGTech likes this.
  4. HGTech

    HGTech

    Joined:
    Dec 20, 2019
    Posts:
    2
    Thanks so much, I have been trying to get this working for ages.
     
    Ciava likes this.
  5. Bloodhunteryt

    Bloodhunteryt

    Joined:
    Sep 25, 2020
    Posts:
    4
    Its crazy how nice and helpful people are in this community
     
    Ciava likes this.