0

im trying to reset my car position by pressing Q to avoid the vehicle to be stuck rollover, but when i press Q, there is no cooldown and if i keep pressing the car will go up flying. I dont want that, hopefully someone can help me :> I also wanted to change only the X and Z rotation with the same keycode but im having problems to make it work.

This is the code that i have currently

if (inVehicle == true && Input.GetKey(KeyCode.Q))
        {
            Vector3 car = transform.position;
            car.y += 1;
            transform.position = car;
            Quaternion rotation = Quaternion.Euler(0, 0, 0);
        }
derHugo
  • 83,094
  • 9
  • 75
  • 115

2 Answers2

1

Use Coroutines to make a cooldown

public float cooldown = 1;
bool canReset = true;

void Update ()
{
    if (inVehicle == true && Input.GetKey(KeyCode.Q) && canReset)
    {
        StartCoroutine(Cooldown(cooldown));
        ...
    }
}

    
IEnumerator Cooldown(float seconds)
{
    canReset = false;
    yield return new WaitForSeconds(seconds);
    canReset = true;
}
CorrieJanse
  • 2,374
  • 1
  • 6
  • 23
0

Common solution is to use Time.time difference.

// ... Class fields ... //
[SerializeField]
protected float cooldown = 0.5f; //Half a second

float lastKeyPressed = 0f;

// ... In Update Function ... //
if ((Time.time - lastKeyPressed) >= cooldown && inVehicle == true && Input.GetKey(KeyCode.Q))
{
    Vector3 car = transform.position;
    car.y += 1;
    transform.position = car;
    Quaternion rotation = Quaternion.Euler(0, 0, 0);
    lastKeyPressed = Time.time;
}

You can also use Time.unscaledTime if you don't want it to be affected by current Time Scale.

Other option is use coroutines as convenient way mentioned in other answer, but be careful, coroutines often involves unnecessary GC allocations

Alex
  • 526
  • 2
  • 8