To start you'll need to create a new XNA windows project, should with Xbox, or WP7 but I'm focusing on the windows one right now. Once the project is created in the content section in the solution explorer right-click and add an existing item. Browse to any image (jpg, png or bmp preferably) and load it. This will be the image that will bounce in the program.
We add some variable:
Texture2D theImage; // our image (*.jpg, *.png *.bmp)Then in load content we need to load our image:
Vector2 posImage = Vector2.Zero; // initial position of the image
Vector2 velImage = new Vector2(150.0f, 150.0f); // velocity vector
int MaxX, MinX, MaxY, MinY; //limits
theSprites = new SpriteBatch(GraphicsDevice);Now for the update, where we update our variables:
// load the images
theImage = Content.Load("imageName");//note: no extension in the image name
MaxX = device.Viewport.Width - theImage.Width;//calculate the horizontal limit
MinX = 0;
MaxY = device.Viewport.Height - theImage.Height;//calculate the vertical limit
MinY = 0;
GamePadState theXbox = GamePad.GetState(PlayerIndex.One);Finally in the draw, we tell the program what to draw in the screen:
KeyboardState theKeyboard = Keyboard.GetState();
//a way for the user to exit the program with the keyboard or xbox controller.
if (theXbox.Buttons.Back == ButtonState.Pressed || theKeyboard.IsKeyDown(Keys.Escape))
this.Exit();
// modify the image position with our velocity vector and the time.
posImage += velImage * (float)gameTime.ElapsedGameTime.TotalSeconds;
//chech for horizontal bounce
if (posImage.X > MaxX)
{
velImage.X *= -1;
posImage.X = MaxX;
}
else if (posImage.X < MinX)
{
velImage.X *= -1;
posImage.X = MinX;
}
// check for vertical bounce
if (posImage.Y > MaxY)
{
velImage.Y *= -1;
posImage.Y = MaxY;
}
else if (posImage.Y < MinY)
{
velImage.Y *= -1;
posImage.Y = MinY;
}
base.Update(gameTime);
GraphicsDevice.Clear(Color.MidnightBlue);You can download the full solution here. It was made in VS2010 so you'll need VS2010 to open it. Also check a friend's blog for another XNA tutorial here. Note his blog is in spanish, but the code is universal :D
// draw the image
theSprites.Begin();
theSprites.Draw(theImage, posImage, Color.White); //here white acts like transparent
theSprites.End();
base.Draw(gameTime);
No comments:
Post a Comment