Skip to content

Instantly share code, notes, and snippets.

@mikezila
Created March 2, 2017 19:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikezila/ad2a83ed585b4d22f29faf40d358054b to your computer and use it in GitHub Desktop.
Save mikezila/ad2a83ed585b4d22f29faf40d358054b to your computer and use it in GitHub Desktop.
TileSheet class for Gosu in Ruby
# tilesheet.rb
#
# This is for loading tile sheets that either have padding between the tiles,
# do not take up the whole of the image, or both. The normal Gosu method for
# loading from tiles doesn't work if there is padding or the tiles themselves
# are not wall-to-wall on the sheet. This can load such a sheet, though you
# will need to know how many tiles there are both wide and tall, as there's no
# way to guess on such a sheet. You'll also need to make sure the sheet is a
# power-of-two in size. You can do this by adjusting the sheet to 512x512 or
# 1024x1024, just add empty space if needed.
#
# This also relies on experimental Gosu::Image.subimage, which may vanish in a
# future version of Gosu. Don't get too attached.
class TileSheet
def initialize(source, tiles_wide, tiles_tall, tile_width, tile_height, tile_padding = 0)
@tile_sheet = Gosu::Image.new(source, { :tileable => true, :retro => true })
@tiles_wide = tiles_wide
@tiles_tall = tiles_tall
@tile_width = tile_width
@tile_height = tile_height
# Padding is assumed to be between tiles, but not between the tiles and the
# outside borders. As in 0,0 is the top left pixel of the first tile, not
# padding. If you have a sheet with padding in the borders as well these
# aren't the droids you're looking for, sorry.
@tile_padding = tile_padding
# An array of subimages
@tiles = []
# Generate all of the sub-images
@tiles_tall.times do |y|
@tiles_wide.times do |x|
@tiles.push(@tile_sheet.subimage((x * @tile_width) + (x * @tile_padding), (y * @tile_height) + (y * @tile_padding), @tile_width, @tile_height))
end
end
end
# Lets you get the subimages using array syntax, so that a TileSheet can be a
# drop-in replacement for an array of Gosu::Image
def [](tile)
@tiles[tile]
end
# In case you just want the array itself instead. That's cool too, I'm easy
# like Sunday mornin'.
def to_a
@tiles
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment