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

Simple 2D Collision Dection?

Last post 25/04/2009 6:28 by crabby. 2 replies.
  • 25/04/2009 2:42

    Simple 2D Collision Dection?

    Hello All,
    I am a student working on an XNA project for a CS1 type class and need help with my project for a final exam.  I am creation a "Pac-Man" type game with all origional artwork.  I have everything working correctly for the most part, however, the part that I am having issues with is how to make the sprite not travel through walls.  The gist of the program is it needs to be simple, as I stated before, this is a CS1 class.  I have initalized all the pellets with an array of Vector2's and a for loop, and the "map" was created by aother student in the group using Paint.Net.  If someone could provide some help I will be very thankful.
        

  • 25/04/2009 4:04 In reply to

    Re: Simple 2D Collision Dection?

    If the map was drawn in Paint.NET, you will need some way of programatically knowing where the walls are. I'd recommend setting up a Wall class, which creates each section of wall as a rectangle. (The wall you define yourself can be invisible, if you have a background ready-made). Then, for the actual collision detection, you can use a class called BoundingBox. It's actually made for 3D, but you can use it for 2D just fine by only defining the first two values. It has a nice Intersects() method which determines if one BoundingBox is partially inside another.
    As for the actual handling of the collision after that, you would be best off finding some way of moving the pac-man's position outwards from the center of the wall, until his left edge is equal to the wall's right edge, for example.
    One thing that helps with collision detection is if you define the origin of your sprite as its center, rather than the upper left (as it is by default). This is somewhere in the draw method of the character.
  • 25/04/2009 6:28 In reply to

    Re: Simple 2D Collision Dection?

    The Rectangle class also has an Intersects method for checking collisions. No need to use a 3d bounding box when there's a perfectly good 2d class. You use the Intersects method like this: Rect1.Intersects(Rect2) and it returns a boolean value;

    To handle moving pacman and the baddies out of walls after detecting a collision, I would use a for loop that moves pacman 1 pixel in the desired direction, checking for a collision each time. It's not efficient, but since you only do this when a collision is detected and you have at most 5 objects checking for collisions at once, efficiency won't matter.
Page 1 of 1 (3 items) Previous Next