Reputation: 127
I have a problem with XNA Game Studio. I have no idea why this code isn't working, how to spawn a missile? What I try to do here is to spawn a missile everytime space is pressed.
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
keys = Keyboard.GetState();
if (keys.IsKeyDown(Keys.Up))
{
spaceshipRectangle.Y -= 5;
}
if (keys.IsKeyDown(Keys.Down))
{
spaceshipRectangle.Y += 5;
}
if(keys.IsKeyDown(Keys.Space))
{
missileShot = true;
missile = Content.Load<Texture2D>("Missile");
missileRectangle = new Rectangle(spaceshipRectangle.X, spaceshipRectangle.Y, 30, 40);
spriteBatch.Begin();
spriteBatch.Draw(missile, missileRectangle, Color.Green);
spriteBatch.End();
}
if (missileShot = true)
{
missileRectangle.X += 5;
}
// TODO: Add your update logic here
enemyRectangle.X -= 5;
base.Update(gameTime);
}
Thank you.
Upvotes: 0
Views: 205
Reputation: 2848
You shouldn't load stuff out of the Load() method. Load the textures in the Load() method.
try moving this line to the Load() method.
missile = Content.Load<Texture2D>("Missile");
Also separate your Update and Draw code.
Upvotes: 0
Reputation: 20616
The key thing going wrong here is that you keep overwriting missile
and missileRectangle
each time space is pressed, rather than adding a new missile - it looks like you need a list of missiles. Another problem is that you're interspersing your input-processing code, update code and drawing code - what you want is to process your input, add new missiles to a list as appropriate and then loop over the list in (a) your update code, to move them, and (b) your rendering code, to draw them.
Upvotes: 2
Reputation: 905
From my memory, XNA has a Draw()
method or something like that which is seperate from Update()
? And you put all of your drawing in that method.
EDIT: try this:
protected override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
//draw all your stuff
spriteBatch.End();
}
Upvotes: 4