How to make a temporary powerup?

Asked

Viewed 52 times

4

Hello. I’m developing a game in which the player throws some balls (shots), so I created a powerup that decreases the time between the thrown balls. I need to make the time between the balls back 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);     
}

1 answer

4

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

However, an alternative that I find more elegant is that you have a private method that returns the value of timeBetweenBullets to the original and invoke it after the time set up 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
            //++++++++++++++++++++
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.