Monday, October 18, 2010

XNA Tutorial: Your first Game!

Here is the code

// Add these lines in the Game1() Method
// -------------------------------- //
// Set the window size
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 600;
// You can also set it to fullscreen
// graphics.IsFullScreen = true;
// -------------------------------- //

// Above and in the LoadContent() Method
Texture2D mytexture; // A texture we can render (our sprite)
Vector2 sPos = Vector2.Zero; // Set the coordinates where the sprite will be drawn (2-dimensional space) 
// -------------------------------- //
mytexture = Content.Load("ball"); // Load the sprite
// -------------------------------- //

// Above and in the Update(GameTime gameTime) Method
Vector2 sSpeed = Vector2.One; // This is something like a direction indicator
// -------------------------------- //
if (Keyboard.GetState().IsKeyDown(Keys.Escape)) // Exit game when the ESC key is pressed
    this.Exit();
sPos += sSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds * 100; // Let's speed it up :)
int MaxX = graphics.GraphicsDevice.Viewport.Width - mytexture.Width;
int MinX = 0;
int MaxY = graphics.GraphicsDevice.Viewport.Height - mytexture.Height;
int MinY = 0;
// Check if the sprite hits the sides of the window. If it does so then make it to move the opposite direction.
if (sPos.X > MaxX)
{
    sSpeed.X *= -1;
    sPos.X = MaxX;
}
else if (sPos.X < MinX) 
{
    sSpeed.X *= -1;
    sPos.X = MinX; 
}
if (sPos.Y > MaxY)
{
    sSpeed.Y *= -1;
    sPos.Y = MaxY;
}
else if (sPos.Y < MinY) 
{
    sSpeed.Y *= -1;
    sPos.Y = MinY;
}
// -------------------------------- //

// Add these lines in the Draw(GameTime gameTime) Method
// -------------------------------- //
GraphicsDevice.Clear(Color.Red); // You can change the background color here
// Draw the sprite
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
spriteBatch.Draw(mytexture, sPos, Color.White);
spriteBatch.End(); 
// -------------------------------- //

Or download the solution

No comments:

Post a Comment