Friday, 14 September 2012

Handle Collision

Handle Collision

Study and study how to handle collision detection, now finally i have took the right path!



This is a preliminary code for detect the collision between Kid  and  tiles ("floor" ,"wall") :


  // Reset flag to search for ground collision.
            isOnGround = false;

            // Get the player's bounding rectangle and find neighboring tiles.
            Rectangle bounds = BoundingRectangle;
            //Find how many tiles are near on the left
            int leftTile = (int)Math.Floor((float)bounds.Left / Tile.Width);
            int rightTile = (int)Math.Ceiling(((float)bounds.Right / Tile.Width)) - 1; //tile dal bordo sx dello schermo al bordo dx del rettangolo sprite
            int topTile = (int)Math.Floor((float)bounds.Top / Tile.Height);
            int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / Tile.Height)) - 1;

       
            // For each potentially colliding Tile,
            for (int y = topTile; y <= bottomTile; ++y)
            {
                for (int x = leftTile; x <= rightTile; ++x)
                {
                    TileCollision tileCollision = room.GetCollision(x, y);
                    TileType tileType = room.GetType(x, y);

                    //interseco ?
                    Rectangle tileBounds = room.GetBounds(x, y);
                    Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);

                    if (depth == Vector2.Zero)
                    {
                        continue;
                    }
                    if (tileCollision == TileCollision.Passable)
                    {
                        continue;   
                    }

                    //Verifico se mi trovo sul terreno
                    if (IsGround(bounds.Bottom, tileBounds.Bottom, Tile.Ground) == false)
                    {
                        continue; 
                    }
                    isOnGround = true;

                    switch (tileType)
                    {
                        case TileType.Wall:
                            Position = new Vector2(Position.X + depth.X, Position.Y);
                            bounds = BoundingRectangle;
                            break; 

                        default:
                            Position = new Vector2(Position.X, tileBounds.Bottom + Tile.Ground);
                            bounds = BoundingRectangle;
                            break;
                    }
                    
                }
            }
            //???
            previousBottom = bounds.Bottom;
        

No comments:

Post a Comment