Beispiel #1
0
        /// <summary>
        /// Detects and resolves all collisions between the player and his neighboring
        /// tiles. When a collision is detected, the player is pushed away along one
        /// axis to prevent overlapping. There is some special logic for the Y axis to
        /// handle platforms which behave differently depending on direction of movement.
        /// </summary>
        private void HandleCollisions()
        {
            // Get the player's bounding rectangle and find neighboring tiles.
            Rectangle bounds = BoundingRectangle;

            bounds.X -= offSetX;
            bounds.Y -= offSetY;
            int leftTile   = (int)Math.Floor((float)(bounds.Left) / Tile.Width);
            int rightTile  = (int)Math.Ceiling(((float)(bounds.Right) / Tile.Width)) - 1;
            int topTile    = (int)Math.Floor((float)(bounds.Top) / ((float)Tile.Height * ((float)SCREENHEIGHT / 1200f)));
            int bottomTile = (int)Math.Ceiling(((float)(bounds.Bottom) / ((float)Tile.Height * ((float)SCREENHEIGHT / 1200f)))) - 1;

            bounds = BoundingRectangle;
            // Reset flag to search for ground collision.
            isOnGround = true;

            // For each potentially colliding tile,
            for (int y = topTile; y <= bottomTile; ++y)
            {
                for (int x = leftTile; x <= rightTile; ++x)
                {
                    // If this tile is collidable,
                    TileCollision collision = Level.GetCollision(x, y);
                    if (collision != TileCollision.Passable)
                    {
                        // Determine collision depth (with direction) and magnitude.
                        Rectangle tileBounds = Level.GetBounds(x, y);
                        Vector2   depth      = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
                        if (depth != Vector2.Zero)
                        {
                            colliding = true;
                        }
                        else
                        {
                            colliding = false;
                        }
                    }
                }
            }
        }