Collision Detection Problems

Posted by MrPlosion on Game Development See other posts from Game Development or by MrPlosion
Published on 2012-06-08T14:24:34Z Indexed on 2012/06/08 16:50 UTC
Read the original article Hit count: 212

Filed under:
|
|
|

So I'm making a 2D tile based game but I can't quite get the collisions working properly. I've taken the code from the Platformer Sample and implemented it into my game as seen below.

One problem I'm having is when I'm on the ground for some strange reason I can't move to the left. Now I'm pretty sure this problem is from the HandleCollisions() method because when I stop running it I can smoothly move around with no problems. Another problem I'm having is when I'm close to a tile the character jitters very strangely.

I will try to post a video if necessary. Here is the HandleCollisions() method:

Thanks.

        void HandleCollisions() {
        Rectangle bounds = BoundingRectangle;

        int topTile = (int)Math.Floor((float)bounds.Top / World.PixelTileSize);
        int bottomTile = (int)Math.Ceiling((float)bounds.Bottom / World.PixelTileSize) - 1;
        int leftTile = (int)Math.Floor((float)bounds.Left / World.PixelTileSize);
        int rightTile = (int)Math.Ceiling((float)bounds.Right / World.PixelTileSize) - 1;

        isOnGround = false;

        for(int x = leftTile; x <= rightTile; x++) {
            for(int y = topTile; y <= bottomTile; y++) {
                if(world.Map[y, x].Collidable == true) {
                    Rectangle tileBounds = new Rectangle(x * World.PixelTileSize, y * World.PixelTileSize, World.PixelTileSize, World.PixelTileSize);
                    Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);

                    if(depth != Vector2.Zero) {
                        if(Math.Abs(depth.Y) < Math.Abs(depth.X)) {
                            isOnGround = true;
                            position = new Vector2(position.X, position.Y + depth.Y);
                        }
                        else {
                            position = new Vector2(position.X + depth.X, position.Y);
                        }

                        bounds = BoundingRectangle;
                    }
                }
            }
        }

© Game Development or respective owner

Related posts about XNA

Related posts about c#