BoundingBox.Intersects versus rectangle.Intersect

BoundingBox.Intersects versus rectangle.Intersect: In 2D the use of rectangle is very simple to use, bounding box is some what of an overkill.  I try to make the difference clear in this article.

In the code for the example HelloXNAFramework, a collision is detected using the following code:

//Start code

void CheckForCollision()
{
        BoundingBox bb1 = new BoundingBox(

                                             new Vector3(spritePosition1.X - (sprite1Width / 2),

                                                                     spritePosition1.Y - (sprite1Height / 2), 0),

                                             new Vector3(spritePosition1.X + (sprite1Width / 2),

                                                                     spritePosition1.Y + (sprite1Height / 2), 0));

                     BoundingBox bb2 = new BoundingBox(

                                                          new Vector3(spritePosition2.X - (sprite2Width / 2),

                                                                                  spritePosition2.Y - (sprite2Height / 2), 0),

                                                         new Vector3(spritePosition2.X + (sprite2Width / 2),

                                                                                  spritePosition2.Y + (sprite2Height / 2), 0));

            if (bb1.Intersects(bb2))
            { 
                    b_collision = true;           

             }

     }

        //End Code

WOW!  This appears to be a simple approach, but it actually is more complicated than needed for a 2D collision.  For 3D, it would be normal to use a bounding box or similar.

I would do this code differently, first I would define a rectangle and texture, which I find useful in 2D game design.

The use of Bounding Boxes isn’t needed in 2D collisions the complete code is shown at the bottom of the discussion, the characters are included in a zip file that is attached to this blog:

Here is the code of a method that checks to see if two rectangles intersect, make sure you have a rectangled named r_PinkGirl and a rectangle r_PlanetBoy, using the boolean Intersects, and that is it!  Here is an example method:

private void CollisionTest()
{
            if (r_PinkGirl.Intersects(r_PlanetBoy))
            {
                b_collision = true;
            }
}

 

Code example, is shown here with all of the default comments, unused “usings” and empty methods removed.  Plus I added the main method, so make sure to remove the Program.cs from your default project and the code will run if you simply replace all of the default code in a new XNA Game Project.  Make sure to add the images to the content project before running the code, the image files are named correctly.

The reason for moving the "main" to this class module is that a project requires a "main" method somewhere in the project, but using this process it makes it easier to insure you will get your code running quickly.

//Code starts here

// Planet girl sort of disappears at the top of the screen, move your mouse up to the top

// and she should show up.

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

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

        Texture2D t_PlanetBoy, t_PinkGirl, t_GreenGem;
        Rectangle r_PlanetBoy, r_PinkGirl, r_GreenGem;
        bool b_collision = false;

        public CollisionExample()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);
            // Pre-autoscale settings.
            graphics.PreferredBackBufferWidth = 480;
            graphics.PreferredBackBufferHeight = 800;
        }
        protected override void Initialize()
        {
            r_PlanetBoy = new Rectangle(400, 400, 50, 50);
            r_PinkGirl = new Rectangle(200, 200, 50, 50);
            r_GreenGem = new Rectangle(300, 300, 100, 100);
            base.Initialize();
        }

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            t_PinkGirl = Content.Load<Texture2D>("PinkGirl");
            t_PlanetBoy = Content.Load<Texture2D>("PlanetBoy");
            t_GreenGem = Content.Load<Texture2D>("GreenGem");
        }

        protected override void Update(GameTime gameTime)
        {
            CollisionTest();

            HandleInput();
            base.Update(gameTime);
        }

        private void CollisionTest()
        {
            if (r_PinkGirl.Intersects(r_PlanetBoy))
            {
                b_collision = true;
            }
        }

        private void HandleInput()
        {
            MouseState currentMouse = Mouse.GetState();
            r_PinkGirl.X = currentMouse.X;
            r_PinkGirl.Y = currentMouse.Y;
        }

        protected override void Draw(GameTime gameTime)
        {
            if (b_collision)
            {
               GraphicsDevice.Clear(Color.Yellow);
            }
            else
            {
               GraphicsDevice.Clear(Color.CornflowerBlue);
            }
            spriteBatch.Begin();
            spriteBatch.Draw(t_PinkGirl, r_PinkGirl, Color.White);
            spriteBatch.Draw(t_PlanetBoy, r_PlanetBoy, Color.White);
            spriteBatch.Draw(t_GreenGem, r_GreenGem, Color.White);
            spriteBatch.End();
            base.Draw(gameTime);
        }

        static void Main(string[] args)
        {
            using (CollisionExample game = new CollisionExample())
            {
                game.Run();
            }
        }

    }
}

//Code ends

Planet Cute.zip