问题:按下空格键后,我需要我的炮弹发射并继续它的生命,无论是否再次按下或松开空格键。
下面是添加、更新和绘制射弹的代码。我已经尝试过多次重新编写此代码,但遗憾的是,我的经验还不够,还没有找到合适的解决方案。
在下方添加投射代码
在此处输入代码
//add projectile if spacebar is pressed
private void AddProjectile(Vector2 position)
{
//i need somthing like this to make bullets autofire on phone
//while (TouchPanel.IsGestureAvailable)
//{
// Projectile projectile = new Projectile();
// projectile.Initialize(GraphicsDevice.Viewport, projectileTexture, position);
// projectiles.Add(projectile);
//}
if (currentKeyboardState.IsKeyDown(Keys.Space) ||
currentGamePadState.Buttons.A == ButtonState.Pressed)
{
Projectile projectile = new Projectile();
projectile.Initialize(GraphicsDevice.Viewport, projectileTexture, position);
projectiles.Add(projectile);
}
}
更新下方的炮弹代码
private void UpdateProjectiles()
{
//update projectiles
for (int i = projectiles.Count - 1; i >= 0; i--)
{
if (currentKeyboardState.IsKeyDown(Keys.Space) ||
currentGamePadState.Buttons.A == ButtonState.Pressed)
{
//adds particle to first projectile but not again until the next fire butotn press
//particleEngine.EmitterLocation = new Vector2(projectiles[i].Position.X, projectiles[i].Position.Y);
projectiles[i].Update();
projectileOn = true;
}
//if projectiles not being fired remove them from the game screen
else
{
projectiles.RemoveAt(i);
}
}
}
绘制投射物以屏蔽的绘制方法
//draw the projectiles
//***********************************************************
//using the if here allows control of projectiles to pass...
//...to the "currentstate of the spacebar (is pressed = fire)
/***/
if (currentKeyboardState.IsKeyDown(Keys.Space) ||
currentGamePadState.Buttons.A == ButtonState.Pressed)
{
for (int i = 0; i < projectiles.Count; i++)
{
projectiles[i].Draw(spriteBatch);
}
}
//remove projectiles and reset
if (currentKeyboardState.IsKeyUp(Keys.Space) ||
currentGamePadState.Buttons.A == ButtonState.Released)
{
UpdateProjectiles();
}
所以,这就是我到目前为止所拥有的,正如所说的,一旦我放开键盘空格键,我就无法让他们继续他们的生活(直到碰撞或他们到达屏幕的尽头)。
我看到的导致isses的问题的快速概述:
- 您正在检查添加、更新和绘制方法期间是否按下了键/按钮
- 如果未按下某个键,则表示在更新过程中删除了该项目,而在绘制过程中未绘制该项目
为了实现我认为你正在努力实现的目标,我会沿着以下路线做一些事情(当然,根据你的需求进行定制和清理):
private void Update(GameTime gameTime)
{
// Only add a new projectile if Space or A is pressed
if (currentKeyboardState.IsKeyDown(Keys.Space) ||
currentGamePadState.Buttons.A == ButtonState.Pressed)
{
AddProjectile(); // some method that adds a new projectile to 'projectiles'
}
// Update all existing projectiles, regardless of button press.
// This will allow your projectiles to continue flying after they have been fired.
for (int i = 0; i < projectiles.Count; i++)
{
projectiles[i].Update();
if (projectiles[i].Dead) // check if projectiles[i] is out of bounds or has collided with something
{
projectiles.RemoveAt(i);
i--;
}
}
}
private void Draw(GameTime gameTime)
{
// Draw all existing projectiles, regardless of button press.
for (int i = 0; i < projectiles.Count; i++)
{
projectiles[i].Draw(spriteBatch);
}
}
您的空格键或A按钮仅用于发射新炮弹。你希望炮弹一直飞到击中什么东西或飞离屏幕一侧,这不应该取决于你是否按下了按钮。两人都不应该画子弹。
有道理吗?