Questions about PowerUps?
I created a basic powerup that will double my speed when I go over it. Now I would like to make the speed only last for 'X' number of seconds and for that PowerUp to not be active for 'Y' number of seconds. How should I go about doing this?
Here is my code:
void OnTriggerEnter (Collider collider)
{
if (collider.CompareTag("PowerUp"))
{
IncreaseSpeed (Speed + Speed);
}
}
Answer by corn · Jan 29, 2016 at 09:58 AM
The best way to do that would be to use Coroutines and WaitForSeconds.
Coroutines are enumerators that can be started by a MonoBehaviour, and are executed separately by the engine, on a frame-by-frame basis. A very convenient feature is the ability of Coroutines to suspend execution for a given amount of time, which is hands down the best way to deal with bonus duration and bonus cooldown.
So what you need to do is :
Lock the power up when it is activated
Increase speed
Wait for X seconds
Reset speed
Wait for Y seconds
Unlock the powerup
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { float m_Speed = 10f; float m_DefaultSpeedBonus = 10f; float m_DefaultPowerUpDuration = 5f; float m_DefaultPowerUpCooldown = 10f; bool m_PowerUpIsActivable = true; IEnumerator SpeedPowerUp(float bonus, float bonusDuration, float cooldown) { // Lock the PowerUp m_PowerUpIsActivable = false; // Activate the speed bonus m_Speed += bonus; // Let it last for bonusDuration seconds yield return new WaitForSeconds(bonusDuration); // Remove the speed bonus m_Speed -= bonus; // Start cooldown yield return new WaitForSeconds(cooldown); // After cooldown is over, unlock the PowerUp m_PowerUpIsActivable = true; } void OnTriggerEnter(Collider collider) { if (collider.CompareTag("PowerUp") && m_PowerUpIsActivable) { StartCoroutine(SpeedPowerUp(m_DefaultSpeedBonus, m_DefaultPowerUpDuration, m_DefaultPowerUpCooldown)); } } }
You can apply the same logic to any PowerUp you want to implement.
Your answer
Follow this Question
Related Questions
Collider disabling by itself... 2 Answers
How to make a POWER UP that slows the player down with force. 0 Answers
2D Game powerup script not working at all 0 Answers
2D Power up script not working 0 Answers
How can I separate my Code efficiently ? 0 Answers