class DragonSkeleton::Tilemap
A Tilemap
manages a grid of tiles and renders them to the screen.
Example:
args.state.tilemap ||= Tilemap.new(x: 0, y: 0, cell_w: 16, cell_h: 16, grid_w: 40, grid_h: 25) args.state.tilemap[0, 0].path = 'sprites/tiles/stone_floor.png' args.state.tilemap[1, 0].path = 'sprites/tiles/stone_wall.png' # ... args.state.tilemap.render(args.outputs)
Attributes
The height of each cell in the tilemap
The width of each cell in the tilemap
The height of the tilemap in cells
The width of the tilemap in cells
The x coordinate of the bottom left corner of the tilemap
The y coordinate of the bottom left corner of the tilemap
Public Class Methods
Creates a new tilemap.
You can optionally pass a tileset to use for the tilemap.
A tileset is an object that responds to the following methods:
default_tile
-
Returns a Hash with default values for each cell
[]
-
Receives a tile key as argument and returns a Hash with values for the given tile
# File lib/dragon_skeleton/tilemap.rb, line 36 def initialize(x:, y:, cell_w:, cell_h:, grid_w:, grid_h:, tileset: nil) @x = x @y = y @cell_w = cell_w @cell_h = cell_h @grid_h = grid_h @grid_w = grid_w @tileset = tileset @cells = grid_h.times.flat_map { |grid_y| grid_w.times.map { |grid_x| Cell.new(grid_x * cell_w, grid_y * cell_h, tileset: tileset) } } @primitive = RenderedPrimitive.new(@cells, self) end
Public Instance Methods
Returns the Cell
at the given grid coordinates.
# File lib/dragon_skeleton/tilemap.rb, line 63 def [](x, y) @cells[y * @grid_w + x] end
Returns the rectangle of the cell at the given grid coordinates.
# File lib/dragon_skeleton/tilemap.rb, line 81 def cell_rect(grid_coordinates) { x: @x + (grid_coordinates.x * @cell_w), y: @y + (grid_coordinates.y * @cell_h), w: @cell_w, h: @cell_h } end
Returns the height of the tilemap in pixels.
# File lib/dragon_skeleton/tilemap.rb, line 58 def h @grid_h * @cell_h end
Renders the tilemap to the given outputs / render target.
# File lib/dragon_skeleton/tilemap.rb, line 68 def render(outputs) outputs.primitives << @primitive end
Converts a position to grid coordinates.
# File lib/dragon_skeleton/tilemap.rb, line 73 def to_grid_coordinates(position) { x: (position.x - @x).idiv(@cell_w), y: (position.y - @y).idiv(@cell_h) } end
Returns the width of the tilemap in pixels.
# File lib/dragon_skeleton/tilemap.rb, line 53 def w @grid_w * @cell_w end