7 Replies - 2510 Views - Last Post: 27 November 2012 - 12:15 PM

#1 TheBoyWhoCriedAlien  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 23-November 12

I NEED HELP WITH XNA 4.0 2D Collision

Posted 23 November 2012 - 01:37 PM

I NEED HELP UNDERSTANDING HOW TO DO COLLISION. WHEN THE PLAYER HITS A CRATE I DON"T WANT HIM TO GO THROUGH IT, I WANT HIM TO COLLIDE WITH IT BUT CANT GO THROUGH IT, LIKE A SOLID OBJECT OR LIKE IN REAL LIFE. HOW CAN I DO THIS, THIS IS MY CODE. THE IMAGE FILES ARE BELOW

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

        //Boy
        Texture2D boy;
        Vector2 boyPosition = Vector2.Zero;
        float boySpeed = 3;
        Point boyFrameSize = new Point(45, 70);

        //Game Object
        Texture2D box;
        Vector2 boxPosition = new Vector2(250, 100);
        Point boxFrameSize = new Point(30, 30);

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <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()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here

            boy = Content.Load<Texture2D>(@"Images/BoyAnimation");
            box = Content.Load<Texture2D>(@"Images/box");
            

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <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)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            KeyboardState keyboardState = Keyboard.GetState();

            if (keyboardState.IsKeyDown(Keys.Up))
                boyPosition.Y -= boySpeed;
            if (keyboardState.IsKeyDown(Keys.Down))
                boyPosition.Y += boySpeed;
            if (keyboardState.IsKeyDown(Keys.Right))
                boyPosition.X += boySpeed;
            if (keyboardState.IsKeyDown(Keys.Left))
                boyPosition.X -= boySpeed;

            if (boyPosition.X < 0)
                boyPosition.X = 0;
            if (boyPosition.Y < 0)
                boyPosition.Y = 0;
            if (boyPosition.X > window.ClientBounds.Width - boyFrameSize.X)
                boyPosition.X = window.ClientBounds.Width - boyFrameSize.X;
            if (boyPosition.Y > window.ClientBounds.Height - boyFrameSize.Y)
                boyPosition.Y = window.ClientBounds.Height - boyFrameSize.Y;
                                   
            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.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            spriteBatch.Begin();
            spriteBatch.Draw(boy, boyPosition, Color.White);
            spriteBatch.Draw(box, boxPosition, Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

Attached image(s)

  • Attached Image
  • Attached Image

This post has been edited by macosxnerd101: 23 November 2012 - 01:38 PM
Reason for edit:: Please use code tags


Is This A Good Question/Topic? 0
  • +

Replies To: I NEED HELP WITH XNA 4.0 2D Collision

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10821
  • View blog
  • Posts: 40,340
  • Joined: 27-December 08

Re: I NEED HELP WITH XNA 4.0 2D Collision

Posted 23 November 2012 - 01:38 PM

Moved to XNA.
Was This Post Helpful? 0
  • +
  • -

#3 LiberLogic969  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 34
  • View blog
  • Posts: 85
  • Joined: 03-September 12

Re: I NEED HELP WITH XNA 4.0 2D Collision

Posted 23 November 2012 - 02:31 PM

You should look into Seperating Axis Theorem (SAT for short). Also, if you want physics, there are a few good free Engines you could use. I would recommend checking out Farseer Physics on codeplex.

Here is a decent intro to SAT with some example code.

http://www.codezealot.org/archives/55

If you go with this dont forget to read the comments on that article, they are very helpful.
Was This Post Helpful? 1
  • +
  • -

#4 bonyjoe  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 176
  • View blog
  • Posts: 548
  • Joined: 08-September 10

Re: I NEED HELP WITH XNA 4.0 2D Collision

Posted 25 November 2012 - 11:26 AM

HEY THIS IS MY CODE, I HAVEN'T ACTUALLY DONE ANYTHING AT ALL RELEVANT TO THE QUESTION BUT MAYBE IF I POST IT I WON'T JUST LOOK LIKE I'M ASKING YOU TO DO ALL THE WORK.

You can deal with that collision with simple bounding box collision as they are both approximately rectangular, I suggest you read one of the 6 million tutorials that exist online.
Was This Post Helpful? 1
  • +
  • -

#5 BBeck  Icon User is offline

  • Here to help.
  • member icon


Reputation: 592
  • View blog
  • Posts: 1,322
  • Joined: 24-April 12

Re: I NEED HELP WITH XNA 4.0 2D Collision

Posted 26 November 2012 - 02:39 PM

The subject of "handling collisions" can get pretty complex, but you should try some of the easier solutions.

On a grid, you can just not allow an object to go into a grid square that's already occupied. Basically, the player gives the command to move forward. But the request is not immediately granted. First, a test is run to see whether this movement is allowed.

The test could be a grid where each square of the grid matches a number in an array. Zero might mean the grid square is unoccupied. So, if the value for that grid square is greater than zero it's occupied and the player cannot move into that square.

If you don't want everything to be tied that tightly to the grid you can do bounding circles. Basically, you have an invisible circle around each object that is roughly the size of the object. If the distance between their centers is less than the combined radii of both objects, then they are overlapping. If you test whether the next move would result in overlapping before you grant the request to move, you can deny the request to move when it would cause overlap.

Or, you could do what is most commonly done and use Axis Aligned Bounding Boxes. Basically, you have an imaginary rectangle around both objects that move with the objects. You can test whether the rectangles overlap by checking their minimum and maximum x and y values against one another to see if they overlap. Other than how the test is carried out it works exactly the same as using circles.

Just test when a request to move is made and deny the request to move when it causes overlap.

There are at least a couple more methods of doing collision detection, but master these before you worry about those.
Was This Post Helpful? 1
  • +
  • -

#6 no2pencil  Icon User is online

  • Admiral Fancy Pants
  • member icon

Reputation: 5411
  • View blog
  • Posts: 27,423
  • Joined: 10-May 07

Re: I NEED HELP WITH XNA 4.0 2D Collision

Posted 26 November 2012 - 02:41 PM

View PostTheBoyWhoCriedAlien, on 23 November 2012 - 03:37 PM, said:

I NEED HELP UNDERSTANDING HOW TO DO COLLISION.

Keep typing in all caps, & someone will find you & punch you in the face.

Then you will be well educated in the ways of collision.
Was This Post Helpful? 0
  • +
  • -

#7 TheBoyWhoCriedAlien  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 23-November 12

Re: I NEED HELP WITH XNA 4.0 2D Collision

Posted 26 November 2012 - 05:33 PM

View PostLiberLogic969, on 23 November 2012 - 02:31 PM, said:

You should look into Seperating Axis Theorem (SAT for short). Also, if you want physics, there are a few good free Engines you could use. I would recommend checking out Farseer Physics on codeplex.

Here is a decent intro to SAT with some example code.

http://www.codezealot.org/archives/55

If you go with this dont forget to read the comments on that article, they are very helpful.


Thank you so much for your support I'll be working on this for the next couple of days.

View Postno2pencil, on 26 November 2012 - 02:41 PM, said:

View PostTheBoyWhoCriedAlien, on 23 November 2012 - 03:37 PM, said:

I NEED HELP UNDERSTANDING HOW TO DO COLLISION.

Keep typing in all caps, & someone will find you & punch you in the face.

Then you will be well educated in the ways of collision.


Sorry, I just wanted to get as much help as I possibly could get so I could learn. Sorry if the caps bothered you.

View Postbonyjoe, on 25 November 2012 - 11:26 AM, said:

HEY THIS IS MY CODE, I HAVEN'T ACTUALLY DONE ANYTHING AT ALL RELEVANT TO THE QUESTION BUT MAYBE IF I POST IT I WON'T JUST LOOK LIKE I'M ASKING YOU TO DO ALL THE WORK.

You can deal with that collision with simple bounding box collision as they are both approximately rectangular, I suggest you read one of the 6 million tutorials that exist online.


I looked at all of the tutorials and all of them are dealing with games like pong. That's not what I need, I was hoping you could give me some advice with this situation so I could learn. Oh and sorry for not posting my code for the physics because I don't know how to make a piece of code that does that, sorry.
Was This Post Helpful? 0
  • +
  • -

#8 Robin19  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: I NEED HELP WITH XNA 4.0 2D Collision

Posted 27 November 2012 - 12:15 PM

I imagine that most examples of pong do the following:
Test where the ball is going
Is the ball's new location "colliding" with a paddle or wall?
Calculate new trajectory for ball

Change it to the following
Test where the user (or gravity) want the player to move
Is the player's new location "colliding" with a box or wall?
Do not move the player. Act like nothing was pressed or gravity was turned off.

The collision tests are the same. The theory is the same. The only difference is your reaction to the "collision". In my space shooter challenge game, I had to test collisions between projectiles, enemies, and the player. Only the reactions to the collisions (remove the projectiles, assign damage) was different.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1