XNA Creators Club Online
Page 1 of 1 (5 items)
Sort Posts: Previous Next

Changing Background

Last post 2/5/2010 5:47 PM by Octacon100. 4 replies.
  • 1/27/2010 12:14 AM

    Changing Background

    i'm working from the Rectangle Collision tutorial here and decided to modify the game a little just to learn something. I have changed the code so there are now two different falling objects and one of them moves the character down on the screen, and the good object moves the character towards the top of the screen. When the character gets to the top of the screen i would like to change the background to the bgTexture2 texture and make the game restart, however haven't had much luck figuring it out. If you have any ideas please let me know.


    #region File Description 
    //----------------------------------------------------------------------------- 
    // Game.cs 
    // 
    // Microsoft XNA Community Game Platform 
    // Copyright (C) Microsoft Corporation. All rights reserved. 
    //----------------------------------------------------------------------------- 
    #endregion 
    #region Using Statements 
    using System; 
    using System.Collections.Generic; 
    using Microsoft.Xna.Framework; 
    using Microsoft.Xna.Framework.Audio; 
    using Microsoft.Xna.Framework.Content; 
    using Microsoft.Xna.Framework.Graphics; 
    using Microsoft.Xna.Framework.Input; 
    using Microsoft.Xna.Framework.Storage; 
    #endregion 
     
     
     
    namespace RectangleCollision 
        /// <summary> 
        /// This is the main type for your game 
        /// </summary> 
        public class RectangleCollisionGame : Microsoft.Xna.Framework.Game 
        { 
            GraphicsDeviceManager graphics; 
     
            // The images we will draw 
            Texture2D personTexture; 
            Texture2D blockTexture; 
            Texture2D bgTexture; 
            Texture2D badTexture; 
            Texture2D bgTexture2; 
           // Texture2D goodobj; 
     
            // The images will be drawn with this SpriteBatch 
            SpriteBatch spriteBatch; 
     
            // Person  
            Vector2 bgArea; 
            Vector2 personPosition; 
            const int PersonMoveSpeed = 5; 
     
            // Blocks 
            List<Vector2> blockPositions = new List<Vector2>(); 
            float BlockSpawnProbability = 0.01f; 
            const int BlockFallSpeed = 2; 
     
            //Bad Object 
            List<Vector2> badPositions = new List<Vector2>(); 
     
            Random random = new Random(); 
     
            //screenManager = new ScreenManager(this) 
     
            // For when a collision is detected 
            bool personHit = false
            bool personHit2 = false
     
            // The sub-rectangle of the drawable area which should be visible on all TVs 
            Rectangle safeBounds; 
            // Percentage of the screen on every side is the safe area 
            const float SafeAreaPortion = 0.02f; 
     
     
            public RectangleCollisionGame() 
            { 
                graphics = new GraphicsDeviceManager(this); 
                Content.RootDirectory = "Content"
     
                // Prefer a resolution suitable for both Windows and XBox 360 
               // graphics.PreferredBackBufferWidth = 853; 
               // graphics.PreferredBackBufferHeight = 480; 
            } 
     
     
            /// <summary> 
            /// Allows the game to perform any initialization it needs to before starting to 
            /// run. This is where it can query for any required services and load any 
            /// non-graphic related content.  Calling base.Initialize will enumerate through 
            /// any components and initialize them as well. 
            /// </summary> 
            protected override void Initialize() 
            { 
                base.Initialize(); 
     
                // Calculate safe bounds based on current resolution 
                Viewport viewport = graphics.GraphicsDevice.Viewport; 
                safeBounds = new Rectangle( 
                    (int)(viewport.Width * SafeAreaPortion), 
                    (int)(viewport.Height * SafeAreaPortion), 
                    (int)(viewport.Width * (1 - 2 * SafeAreaPortion)), 
                    (int)(viewport.Height * (1 - 2 * SafeAreaPortion))); 
     
                // Start the player in the center along the bottom of the screen 
                personPosition.X = (safeBounds.Width - personTexture.Width) / 2; 
                personPosition.Y = safeBounds.Height - personTexture.Height; 
            } 
     
     
            /// <summary> 
            /// Load your graphics content. 
            /// </summary> 
            protected override void LoadContent() 
            { 
                // Load textures 
                blockTexture = Content.Load<Texture2D>("Block"); 
                personTexture = Content.Load<Texture2D>("Person");           
                badTexture = Content.Load<Texture2D>("badobj"); 
                bgTexture = Content.Load<Texture2D>("Background");            
                bgTexture2 = Content.Load<Texture2D>("Background2"); 
                 
                // Create a sprite batch to draw those textures 
                spriteBatch = new SpriteBatch(graphics.GraphicsDevice); 
            } 
     
     
            /// <summary> 
            /// Allows the game to run logic such as updating the world, 
            /// checking for collisions, gathering input and playing audio. 
            /// </summary> 
            /// <param name="gameTime">Provides a snapshot of timing values.</param> 
            protected override void Update(GameTime gameTime) 
            {             
                // Get input 
                KeyboardState keyboard = Keyboard.GetState(); 
                GamePadState gamePad = GamePad.GetState(PlayerIndex.One); 
     
                 
                if (personPosition.Y <= -5) 
                { 
                    //insert code to switch backgrounds and restart game 
                   // this.Exit(); 
                    // this.BeginRun(); 
                    personPosition.X = (safeBounds.Width - personTexture.Width) / 2; 
                    personPosition.Y = safeBounds.Height - personTexture.Height;               
     
                } 
                 
     
                // Allows the game to exit 
                if (gamePad.Buttons.Back == ButtonState.Pressed || 
                    keyboard.IsKeyDown(Keys.Escape)) 
                { 
                    this.Exit(); 
                } 
     
                // Move the player left and right with arrow keys or d-pad 
                if (keyboard.IsKeyDown(Keys.Left) || 
                    gamePad.DPad.Left == ButtonState.Pressed) 
                { 
                    personPosition.X -= PersonMoveSpeed; 
                } 
                if (keyboard.IsKeyDown(Keys.Right) || 
                    gamePad.DPad.Right == ButtonState.Pressed) 
                { 
                    personPosition.X += PersonMoveSpeed; 
                } 
     
                // Prevent the person from moving off of the screen 
                personPosition.X = MathHelper.Clamp(personPosition.X, 
                    safeBounds.Left, safeBounds.Right - personTexture.Width); 
     
                // Spawn new falling blocks 
                if (random.NextDouble() < BlockSpawnProbability) 
                { 
                    float x = (float)random.NextDouble() * 
                        (Window.ClientBounds.Width - blockTexture.Width); 
                    blockPositions.Add(new Vector2(x, -blockTexture.Height)); 
                } 
     
     
                // Spawn new falling Bad Objects 
                if (random.NextDouble() < BlockSpawnProbability) 
                { 
                    float x = (float)random.NextDouble() * 
                        (Window.ClientBounds.Width - badTexture.Width); 
                    badPositions.Add(new Vector2(x, -badTexture.Height)); 
                } 
     
                // Get the bounding rectangle of the person 
                Rectangle personRectangle = 
                    new Rectangle((int)personPosition.X, (int)personPosition.Y, 
                    personTexture.Width, personTexture.Height); 
     
                // Update each block 
                personHit = false
                for (int i = 0; i < blockPositions.Count; i++) 
                { 
                    // Animate this block falling 
                    blockPositions[i] = 
                        new Vector2(blockPositions[i].X, 
                                    blockPositions[i].Y + BlockFallSpeed); 
     
                    // Get the bounding rectangle of this block 
                    Rectangle blockRectangle = 
                        new Rectangle((int)blockPositions[i].X, (int)blockPositions[i].Y, 
                        blockTexture.Width, blockTexture.Height); 
     
                    // Check collision with person 
                    if (personRectangle.Intersects(blockRectangle)) 
                        personHit = true
     
                    // Remove this block if it have fallen off the screen 
                    if (blockPositions[i].Y > Window.ClientBounds.Height) 
                    { 
                        blockPositions.RemoveAt(i); 
     
                        // When removing a block, the next block will have the same index 
                        // as the current block. Decrement i to prevent skipping a block. 
                        i--; 
                    } 
                } 
     
     
                // Update each block 
                personHit2 = false
                for (int i = 0; i < badPositions.Count; i++) 
                { 
                    // Animate this block falling 
                    badPositions[i] = 
                        new Vector2(badPositions[i].X, 
                                    badPositions[i].Y + BlockFallSpeed); 
     
                    // Get the bounding rectangle of this block 
                    Rectangle badRectangle = 
                        new Rectangle((int)badPositions[i].X, (int)badPositions[i].Y, 
                        badTexture.Width, badTexture.Height); 
     
                
                    //Get the bounding rectangle of Bad Object 
     
                    // Check collision with person 
                    if (personRectangle.Intersects(badRectangle)) 
                        personHit2 = true
     
                    // Remove this block if it have fallen off the screen 
                    if (badPositions[i].Y > Window.ClientBounds.Height) 
                    { 
                        badPositions.RemoveAt(i); 
     
                        // When removing a block, the next block will have the same index 
                        // as the current block. Decrement i to prevent skipping a block. 
                        i--; 
                    } 
                } 
     
     
          
                base.Update(gameTime); 
            } 
             
     
            /// <summary> 
            /// This is called when the game should draw itself. 
            /// </summary> 
            /// <param name="gameTime">Provides a snapshot of timing values.</param> 
            ///  
     
             
     
            protected override void Draw(GameTime gameTime) 
            { 
                GraphicsDevice device = graphics.GraphicsDevice; 
     
                // Change the background to red when the person was hit by a block 
                if (personHit) 
                { 
                   //device.Clear(Color.Red); 
                    personPosition.Y = personPosition.Y - 40; 
                } 
                else 
                { 
                    device.Clear(Color.CornflowerBlue); 
                } 
     
                if (personHit2) 
                { 
                    personPosition.Y = personPosition.Y + 40; 
                } 
                else 
                { 
                    device.Clear(Color.CornflowerBlue); 
                } 
     
     
     
                spriteBatch.Begin(); 
     
                //draw background 
                spriteBatch.Draw(bgTexture, bgArea, Color.White); 
     
                // Draw person 
                spriteBatch.Draw(personTexture, personPosition, Color.White); 
     
                // Draw blocks 
                foreach (Vector2 blockPosition in blockPositions) 
                    spriteBatch.Draw(blockTexture, blockPosition, Color.White); 
     
                // Draw Bad Object 
                foreach (Vector2 badPosition in badPositions) 
                    spriteBatch.Draw(badTexture, badPosition, Color.White); 
     
                spriteBatch.End(); 
     
                base.Draw(gameTime); 
     
            } 
        } 
     

  • 1/27/2010 2:37 AM In reply to

    Re: Changing Background

    If i'm to understand you properly you want to change the background image whenever the character reaches the top of the screen and you want the player to be put back at the bottom of the screen? This flips repeats over and over?

    OK.

    You could do this a few ways. I'll show you a switch statement.  Remember, this is just one way you could do this, it's not a definitive method ; just a pointer for you to look at, absorb and hopefully put you in the right direction.

    First, declare an int to hold the value for our caseSwitch and set the value to 1

    int caseSwitch = 1; 

    then modify your draw() method like this

    //draw background  
    switch (caseSwitch)  
    {  
        case 1:  
            spriteBatch.Draw(bgTexture, bgArea, Color.White);  
            break;  
        case 2:  
            spriteBatch.Draw(bgTexture2, bgArea, Color.White);  
            break;  

    And in your update function, where you reset the players position, add some code to change the value of the cases

    if (personPosition.Y <= -5)  
    {  
        //insert code to switch backgrounds and restart game    
        personPosition.X = (safeBounds.Width - personTexture.Width) / 2;  
        personPosition.Y = safeBounds.Height - personTexture.Height;  
     
        //change the caseSwitch to change backgrounds  
        if (caseSwitch == 1)  
            caseSwitch = 2;  
        else if (caseSwitch == 2)  
            caseSwitch = 1;  

    So what happens here is, when the character reaches the top and resets position, the caseSwitch value changes and we use a different SpriteBatch.Draw method for a different background.

    Of course, there are other ways you could tackle with if statements and such like or other more complex methods but this is probably a good example if you're just starting out coding like this.

    Hope that helps.
  • 1/27/2010 6:10 AM In reply to

    Re: Changing Background

    thank you for the help, i was actually trying to do something similar but with if statements and a bool variable... kept coming up with issues. This however works perfect :)
  • 1/27/2010 3:44 PM In reply to

    Re: Spawning

    so, i have another question... instead of making the object spawn randomly how could i make only 3 of the same objects spawn at a time, so there will be 3 badTextures etc. Then  just make it so when one of those hits the personTexture it just gets puts back on the top of the screen and falls down again?

    here is my updated code...

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using Microsoft.Xna.Framework; 
    using Microsoft.Xna.Framework.Audio; 
    using Microsoft.Xna.Framework.Content; 
    using Microsoft.Xna.Framework.GamerServices; 
    using Microsoft.Xna.Framework.Graphics; 
    using Microsoft.Xna.Framework.Input; 
    using Microsoft.Xna.Framework.Media; 
    using Microsoft.Xna.Framework.Net; 
    using Microsoft.Xna.Framework.Storage; 
     
    namespace XNAJBO02B 
        /// <summary> 
        /// This is the main type for your game 
        /// </summary> 
        public class Game1 : Microsoft.Xna.Framework.Game 
        { 
            GraphicsDeviceManager graphics; 
     
            // The images we will draw 
            Texture2D personTexture; 
            Texture2D blockTexture; 
            Texture2D bgTexture; 
            Texture2D badTexture; 
            Texture2D bgTexture2; 
           // Texture2D goodobj; 
     
            int caseSwitch = 1;  
     
            // The images will be drawn with this SpriteBatch 
            SpriteBatch spriteBatch; 
     
            // Person  
            Vector2 bgArea; 
            Vector2 personPosition; 
            const int PersonMoveSpeed = 5; 
     
            // Blocks 
            List<Vector2> blockPositions = new List<Vector2>(); 
            float BlockSpawnProbability = 0.01f; 
            const int BlockFallSpeed = 2; 
     
            //Bad Object 
            List<Vector2> badPositions = new List<Vector2>(); 
     
            Random random = new Random(); 
     
            //screenManager = new ScreenManager(this) 
     
            // For when a collision is detected 
            bool personHit = false
            bool personHit2 = false
     
            // The sub-rectangle of the drawable area which should be visible on all TVs 
            Rectangle safeBounds; 
            // Percentage of the screen on every side is the safe area 
            const float SafeAreaPortion = 0.02f; 
     
     
            public Game1() 
            { 
                graphics = new GraphicsDeviceManager(this); 
                Content.RootDirectory = "Content"
     
                // Prefer a resolution suitable for both Windows and XBox 360 
               // graphics.PreferredBackBufferWidth = 853; 
               // graphics.PreferredBackBufferHeight = 480; 
            } 
     
     
            /// <summary> 
            /// Allows the game to perform any initialization it needs to before starting to 
            /// run. This is where it can query for any required services and load any 
            /// non-graphic related content.  Calling base.Initialize will enumerate through 
            /// any components and initialize them as well. 
            /// </summary> 
            protected override void Initialize() 
            { 
                base.Initialize(); 
     
                // Calculate safe bounds based on current resolution 
                Viewport viewport = graphics.GraphicsDevice.Viewport; 
                safeBounds = new Rectangle( 
                    (int)(viewport.Width * SafeAreaPortion), 
                    (int)(viewport.Height * SafeAreaPortion), 
                    (int)(viewport.Width * (1 - 2 * SafeAreaPortion)), 
                    (int)(viewport.Height * (1 - 2 * SafeAreaPortion))); 
     
                // Start the player in the center along the bottom of the screen 
                personPosition.X = (safeBounds.Width - personTexture.Width) / 2; 
                personPosition.Y = safeBounds.Height - personTexture.Height; 
            } 
     
     
            /// <summary> 
            /// Load your graphics content. 
            /// </summary> 
            protected override void LoadContent() 
            { 
                // Load textures 
                blockTexture = Content.Load<Texture2D>(@"Images\goodobj"); 
                personTexture = Content.Load<Texture2D>(@"Images\playerObj");           
                badTexture = Content.Load<Texture2D>(@"Images\badobj"); 
                bgTexture = Content.Load<Texture2D>(@"Images\Background");            
                bgTexture2 = Content.Load<Texture2D>(@"Images\Background2"); 
                 
                // Create a sprite batch to draw those textures 
                spriteBatch = new SpriteBatch(graphics.GraphicsDevice); 
            } 
     
     
            /// <summary> 
            /// Allows the game to run logic such as updating the world, 
            /// checking for collisions, gathering input and playing audio. 
            /// </summary> 
            /// <param name="gameTime">Provides a snapshot of timing values.</param> 
            protected override void Update(GameTime gameTime) 
            {             
                // Get input 
                KeyboardState keyboard = Keyboard.GetState(); 
                GamePadState gamePad = GamePad.GetState(PlayerIndex.One); 
     
     
                //draw background   
                if (personPosition.Y <= -5) 
                { 
                    //insert code to switch backgrounds and restart game     
                    personPosition.X = (safeBounds.Width - personTexture.Width) / 2; 
                    personPosition.Y = safeBounds.Height - personTexture.Height; 
     
                    //change the caseSwitch to change backgrounds   
                    if (caseSwitch == 1) 
                        caseSwitch = 2; 
                    else if (caseSwitch == 2) 
                        caseSwitch = 1; 
                } 
     
                //keeps player obect from being pushed to far down and off the screen 
                if (personPosition.Y > safeBounds.Height - personTexture.Height) 
                    personPosition.Y = safeBounds.Height - personTexture.Height; 
                 
     
                // Allows the game to exit 
                if (gamePad.Buttons.Back == ButtonState.Pressed || 
                    keyboard.IsKeyDown(Keys.Escape)) 
                { 
                    this.Exit(); 
                } 
     
                // Move the player left and right with arrow keys or d-pad 
                if (keyboard.IsKeyDown(Keys.Left) || 
                    gamePad.DPad.Left == ButtonState.Pressed) 
                { 
                    personPosition.X -= PersonMoveSpeed; 
                } 
                if (keyboard.IsKeyDown(Keys.Right) || 
                    gamePad.DPad.Right == ButtonState.Pressed) 
                { 
                    personPosition.X += PersonMoveSpeed; 
                } 
     
                // Prevent the person from moving off of the screen 
                personPosition.X = MathHelper.Clamp(personPosition.X, 
                    safeBounds.Left, safeBounds.Right - personTexture.Width); 
                 
                // Spawn new falling blocks 
                if (random.NextDouble() < BlockSpawnProbability) 
                { 
                    float x = (float)random.NextDouble() * 
                        (Window.ClientBounds.Width - blockTexture.Width); 
                    blockPositions.Add(new Vector2(x, -blockTexture.Height)); 
                } 
                  
     
     
                // Spawn new falling Bad Objects 
                if (random.NextDouble() < BlockSpawnProbability) 
                { 
                    float x = (float)random.NextDouble() * 
                        (Window.ClientBounds.Width - badTexture.Width); 
                    badPositions.Add(new Vector2(x, -badTexture.Height)); 
                } 
     
                // Get the bounding rectangle of the person 
                Rectangle personRectangle = 
                    new Rectangle((int)personPosition.X, (int)personPosition.Y, 
                    personTexture.Width, personTexture.Height); 
     
                // Update each block 
                personHit = false
                for (int i = 0; i < blockPositions.Count; i++) 
                { 
                    // Animate this block falling 
                    blockPositions[i] = 
                        new Vector2(blockPositions[i].X, 
                                    blockPositions[i].Y + BlockFallSpeed); 
     
                    // Get the bounding rectangle of this block 
                    Rectangle blockRectangle = 
                        new Rectangle((int)blockPositions[i].X, (int)blockPositions[i].Y, 
                        blockTexture.Width, blockTexture.Height); 
     
                    // Check collision with person 
                    if (personRectangle.Intersects(blockRectangle)) 
                        personHit = true
     
                    // Remove this block if it have fallen off the screen 
                    if (blockPositions[i].Y > Window.ClientBounds.Height) 
                    { 
                        blockPositions.RemoveAt(i); 
     
                        // When removing a block, the next block will have the same index 
                        // as the current block. Decrement i to prevent skipping a block. 
                        i--; 
                    } 
                } 
     
     
     
                // Update each block 
                personHit2 = false
                for (int i = 0; i < badPositions.Count; i++) 
                { 
                    // Animate this block falling 
                    badPositions[i] = 
                        new Vector2(badPositions[i].X, 
                                    badPositions[i].Y + BlockFallSpeed); 
     
                    // Get the bounding rectangle of this block 
                    Rectangle badRectangle = 
                        new Rectangle((int)badPositions[i].X, (int)badPositions[i].Y, 
                        badTexture.Width, badTexture.Height); 
     
                
                    //Get the bounding rectangle of Bad Object 
     
                    // Check collision with person 
                    if (personRectangle.Intersects(badRectangle)) 
                    { 
      
                        personHit2 = true
     
                    } 
     
     
                    // Remove this block if it have fallen off the screen 
                    if (badPositions[i].Y > Window.ClientBounds.Height) 
                    { 
                        //badPositions.RemoveAt(i); 
             
                        // When removing a block, the next block will  
                        //have the same index 
                        // as the current block. Decrement i to prevent skipping a block. 
                        i--; 
                    } 
                } 
     
     
          
                base.Update(gameTime); 
            } 
             
     
            /// <summary> 
            /// This is called when the game should draw itself. 
            /// </summary> 
            /// <param name="gameTime">Provides a snapshot of timing values.</param> 
            ///  
     
             
     
            protected override void Draw(GameTime gameTime) 
            { 
                GraphicsDevice device = graphics.GraphicsDevice; 
     
                // Change the background to red when the person was hit by a block 
                if (personHit) 
                { 
                    personPosition.Y = personPosition.Y - 2; 
                    //vibrate gamepad 
                    GamePad.SetVibration(PlayerIndex.One, 1, 1); 
                } 
                else 
                { 
                    device.Clear(Color.CornflowerBlue); 
                    //vibrate gamepad 
                    GamePad.SetVibration(PlayerIndex.One, 1, 1); 
                } 
     
                if (personHit2) 
                { 
                    personPosition.Y = personPosition.Y + 2; 
                } 
                else 
                { 
                    device.Clear(Color.CornflowerBlue); 
                } 
     
     
     
                spriteBatch.Begin(); 
     
                //draw background 
                //draw background   
                switch (caseSwitch) 
                { 
                    case 1: 
                        spriteBatch.Draw(bgTexture, bgArea, Color.White); 
                        break
                    case 2: 
                        spriteBatch.Draw(bgTexture2, bgArea, Color.White); 
                        break
                }  
                //spriteBatch.Draw(bgTexture, bgArea, Color.White); 
     
                // Draw person 
                spriteBatch.Draw(personTexture, personPosition, Color.White); 
     
                // Draw blocks 
                foreach (Vector2 blockPosition in blockPositions) 
                    spriteBatch.Draw(blockTexture, blockPosition, Color.White); 
     
                // Draw Bad Object 
                foreach (Vector2 badPosition in badPositions) 
                    spriteBatch.Draw(badTexture, badPosition, Color.White); 
     
                spriteBatch.End(); 
     
                base.Draw(gameTime); 
     
            } 
        } 

  • 2/5/2010 5:47 PM In reply to

    Re: Spawning

    So, I think I can help with the number of things spawned. You already know about the badPositions.count property. So you could make a Constant, something like MAX_BAD_SPAWNS, set it to three, and put that constant in the same area that decides if a bad object is spawned or not.

                // Spawn new falling blocks 
                if (random.NextDouble() < BlockSpawnProbability blockPositions.Count <= MAX_BLOCK_SPAWNS) 
                { 
                    float x = (float)random.NextDouble() * 
                        (Window.ClientBounds.Width - blockTexture.Width); 
                    blockPositions.Add(new Vector2(x, -blockTexture.Height)); 
                } 
                  
     
     
                // Spawn new falling Bad Objects 
                if (random.NextDouble() < BlockSpawnProbability && badPositions.Count <= MAX_BAD_SPAWNS) 
                { 
                    float x = (float)random.NextDouble() * 
                        (Window.ClientBounds.Width - badTexture.Width); 
                    badPositions.Add(new Vector2(x, -badTexture.Height)); 
                } 

    I'm not totally sure about the collision detection. There's stack's of help with that online or in books. You'd probably want to fire an event or something.

    Hope that helps.
Page 1 of 1 (5 items) Previous Next