How to make a temporary powerup?

4

Hello. I'm developing a game in which the player throws some balls (shots), so I created a powerup that reduces the time between the balls thrown. I need to make the time between the balls return to normal after a certain time.

void Update()
{
    cax = GameObject.FindGameObjectWithTag ("PowerUp");

    if(Input.GetButton("Fire1") && Time.time >= nextFire)
    {
        Fire();
        nextFire = Time.time + timeBetweenBullets;
    }
}

// Capturar o 
//POWERUP
void OnTriggerEnter(Collider other)
        {   
            if(other.gameObject == cax)
            {
                timeBetweenBullets = 0.10f;
                Destroy(cax);
            }
        }

void Fire()
{
    //BULLET
    //1

    // Create the Bullet from the Bullet Prefab
        var bullet1 = (GameObject)Instantiate(
        bulletPrefab,
        bulletSpawn.position,
        bulletSpawn.rotation);

    // Add velocity to the bullet
    bullet1.GetComponent<Rigidbody>().velocity = bullet1.transform.forward * 50;
    GetComponent<AudioSource>().clip = Tiro;
    GetComponent<AudioSource>().Play ();
    // Destroy the bullet after 2 seconds
    Destroy(bullet1, 2.0f);        

    //BULLET
    //2


            // Create the Bullet from the Bullet Prefab
        var bullet2 = (GameObject)Instantiate(
        bulletPrefabs,
        bulletSpawns.position,
        bulletSpawns.rotation);

    // Add velocity to the bullet
    bullet2.GetComponent<Rigidbody>().velocity = bullet2.transform.forward * 50;
    GetComponent<AudioSource>().clip = Tiro;
    GetComponent<AudioSource>().Play ();

    // Destroy the bullet after 2 seconds
    Destroy(bullet2, 2.0f);     
}
    
asked by anonymous 12.12.2017 / 23:44

1 answer

4

You can keep a second private attribute of the class to "count" the elapsed time in the same way as you count nextFire . This second time would be counted down to the value you set for the end-time of the power-up and then you would return the value from timeBetweenBullets to the original.

However, one alternative that I find most elegant is that you have a private method that returns the value of timeBetweenBullets to the original and invokes it after the time set using a Invoke . For example:

void resetPowerup()
{
    timeBetweenBullets = 1f; // Supondo que o valor original era 1
}

void OnTriggerEnter(Collider other)
    {   
        if(other.gameObject == cax)
        {
            timeBetweenBullets = 0.10f;
            Destroy(cax);

            //++++++++++++++++++++
            Invoke("resetPowerup", 10); // Invoca "resetPowerup" após 10s
            //++++++++++++++++++++
        }
    }
    
13.12.2017 / 17:21