Reputation: 51
I'm making a space shooter and I'm wondering how to make a delay with the shooting instead of spamming the space bar thanks :)
public void Shoot()
{
Bullets newBullet = new Bullets(Content.Load<Texture2D>("PlayerBullet"));
newBullet.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 5f;
newBullet.position = playerPosition + playerVelocity + newBullet.velocity * 5;
newBullet.isVisible = true;
if (bullets.Count() >= 0)
bullets.Add(newBullet);
}
Upvotes: 1
Views: 758
Reputation: 11252
I think you want to use XNA's GameTime
property. Whenever you shoot a bullet you should record the time it happened as the current GameTime.ElapsedGameTime
value.
This is a TimeSpan
so you could compare it like the following:
// Create a readonly variable which specifies how often the user can shoot. Could be moved to a game settings area
private static readonly TimeSpan ShootInterval = TimeSpan.FromSeconds(1);
// Keep track of when the user last shot. Or null if they have never shot in the current session.
private TimeSpan? lastBulletShot;
protected override void Update(GameTime gameTime)
{
if (???) // input logic for detecting the spacebar goes here
{
// if we got here it means the user is trying to shoot
if (lastBulletShot == null || gameTime.ElapsedGameTime - (TimeSpan)lastBulletShot >= ShootInterval)
{
// Allow the user to shoot because he either has not shot before or it's been 1 second since the last shot.
Shoot();
}
}
}
Upvotes: 4
Reputation: 31184
You can have a counter that counts the number of frames since the last shot.
int shootCounter = 0;
...
if(shootCounter > 15)
{
Shoot();
shootcounter = 0;
}
else
{
shootcounter++;
}
If you want to go more advanced, you can use the gameTime
that the default update method normally gives you to keep track of how much times has passed since you've last shot.
Upvotes: 0