Exemplo n.º 1
0
        private void adjustVelocityForRectangleCollision(Entity entity, float deltaT, Rectangle rect, ref Vector2 velocity)
        {
            Vector2 intersectionAmount;
            Vector2 tempPosition = entity.Position + (velocity * deltaT);
            if (rect.EIntersects(entity.GetBoundingBoxAt(tempPosition)))
            {
                tempPosition = entity.Position;
                tempPosition.X += velocity.X * deltaT;
                if (entity.GetBoundingBoxAt(tempPosition).Intersects(rect, out intersectionAmount))
                {
                    bool positive = velocity.X >= 0;
                    velocity.X -= intersectionAmount.X / deltaT;
                    if ((positive && velocity.X < 0) || (!positive && velocity.X > 0))
                        velocity.X = 0;
                }

                tempPosition = entity.Position;
                tempPosition.Y += velocity.Y * deltaT;
                if (entity.GetBoundingBoxAt(tempPosition).Intersects(rect, out intersectionAmount))
                {
                    bool positive = velocity.Y >= 0;
                    velocity.Y -= intersectionAmount.Y / deltaT;
                    if ((positive && velocity.Y < 0) || (!positive && velocity.Y > 0))
                        velocity.Y = 0;
                }
            }
        }
        public bool CollidesWith(Map map)
        {
            Rectangle bounds = GetBoundingBox();

            Point topLeftTileCoord = new Point(bounds.Left / Map.TileSize, bounds.Top / Map.TileSize);
            Point bottomRightTileCoord = new Point(bounds.Right / Map.TileSize, bounds.Bottom / Map.TileSize);

            for (int x = topLeftTileCoord.X; x <= bottomRightTileCoord.X; ++x)
            {
                for (int y = topLeftTileCoord.Y; y <= bottomRightTileCoord.Y; ++y)
                {
                    if (map.CollisionMap[x, y])
                    {
                        Rectangle tileRect = new Rectangle(x * Map.TileSize, y * Map.TileSize, Map.TileSize, Map.TileSize);
                        if (tileRect.EIntersects(bounds))
                            return true;
                    }
                }
            }

            return false;
        }