如何在按键上添加拍摄延迟
本文关键字:添加 延迟 | 更新日期: 2023-09-27 18:34:33
我正在制作一个太空射击游戏,我想知道如何延迟射击而不是向空格键发送垃圾邮件,谢谢:)
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);
}
我认为你想使用XNA的GameTime
属性。 每当你发射子弹时,你应该记录它发生的时间作为当前的GameTime.ElapsedGameTime
值。
这是一个TimeSpan
,因此您可以像下面这样比较它:
// 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();
}
}
}
您可以使用一个计数器来计算自上次拍摄以来的帧数。
int shootCounter = 0;
。
if(shootCounter > 15)
{
Shoot();
shootcounter = 0;
}
else
{
shootcounter++;
}
如果您想更高级,可以使用默认更新方法通常为您提供的gameTime
来跟踪自上次拍摄以来已经过去了多少次。