I have been working on a small game that is kind of similar to space invaders.
Instead, my player shoots dogs at balls (see video). The dogs are spawned by pressing my enter bar.
My only problem is that I want my player to only spawn a new dog after a certain amount of time has passed to prevent “spamming” the enter bar. I have been having trouble with this and I was wondering if someone knowledgeable knows where to start with this. I have been googling like crazy and I thought it would be time to ask for some help. Thank you in advance.
using System.Collections;
using System.Collections.Generic;
using System.Timers;
using UnityEngine;
public class PlayerControllerX : MonoBehaviour
{
public GameObject dogPrefab;
public Timer newTimer = new Timer();
public int measureTime = 1;
// Update is called once per frame
void Update()
{
newTimer.Interval = 6;
newTimer.Elapsed += new ElapsedEventHandler(TimerStart);
newTimer.Enabled = true;
newTimer.Start();
// On spacebar press, send dog
if (Input.GetKeyDown(KeyCode.Space) & measureTime > 3)
{
Instantiate(dogPrefab, transform.position, dogPrefab.transform.rotation);
measureTime = 1;
newTimer.Stop();
}
}
private void TimerStart(object o, ElapsedEventArgs e)
{
measureTime++;
}
}
// cool the gun
if (gunHeat > 0)
{
gunHeat -= Time.deltaTime;
}
// is the player asking to shoot?
if (PlayerAskedToShoot)
{
// can we shoot yet?
if (gunHeat <= 0)
{
// heat the gun up so we have to wait a bit before shooting again
gunHeat = TimeBetweenShots;
// DO THE SHOT HERE
}
}
Way simpler.
Now you can actually give the player powerups that reduce the TimeBetweenShots (which is a constant above, but you can make it variable).
Or you can have SUPER shots that take a really long time to recharge, for instance.