DEFCOM1  
 

 

XNA Level 1 Lesson 6.5

Project Clean Up

  1. Add Screen Height and Width variables
  2. Set the screen size
  3. Update the collision and move code

At the moment if we wanted to change the screen resolution we have to go through lots of code making lots of changes i.e.

  • PAL 576x520
  • NTSC 486x440
  • HD 1280x720
  • HD 1920x1080

After the SpriteBatch line add the screenHeight and screenWidth Variables

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        //screen size
        public int screenHeight;
        public int screenWidth;

 

Set the Screen Size in the initialise function 

        protected override void Initialize()
        {
            //set Screen size
            screenWidth = 800;
            screenHeight = 600;

            graphics.PreferredBackBufferWidth = screenWidth;
            graphics.PreferredBackBufferHeight = screenHeight;

 

Update the Update code

Replace

            //update asteroid
            asteroidPos.Y += 5;

            if (asteroidPos.Y > 800)
            {
                Random rand = new Random();
                asteroidPos.X = rand.Next(800 - asteroidTex.Width);
                asteroidPos.Y = -asteroidTex.Height;
                score += 10;
            }

 

With (Notice the asteroidPos.X = rand.Next(screenWidth - asteroidTex.Width);)

//update asteroid
            asteroidPos.Y += 5;

            if (asteroidPos.Y > 800)
            {
                Random rand = new Random();
                asteroidPos.X = rand.Next(screenWidth - asteroidTex.Width);
                asteroidPos.Y = -asteroidTex.Height;
                score += 10;
            }

 

You will also need to update the keyboard code that check if the ufo is trying to go off of the screen

Change the 800s and 600s to screenHeight and screenWidth

            if (key.IsKeyDown(Keys.Left) && ufoPos.X > 0)
            {
                ufoPos.X -= 5;
            }
            if (key.IsKeyDown(Keys.Right) && ufoPos.X < 800 - ufoTex.Width)
            {
                ufoPos.X += 5;
            }
            if (key.IsKeyDown(Keys.Up) && ufoPos.Y > 0)
            {
                ufoPos.Y -= 5;
            }
            if (key.IsKeyDown(Keys.Down) && ufoPos.Y < 600 - ufoTex.Height)
            {
                ufoPos.Y += 5;
            }