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

cell_h[R]

The height of each cell in the tilemap

cell_w[R]

The width of each cell in the tilemap

grid_h[R]

The height of the tilemap in cells

grid_w[R]

The width of the tilemap in cells

x[RW]

The x coordinate of the bottom left corner of the tilemap

y[RW]

The y coordinate of the bottom left corner of the tilemap

Public Class Methods

new(x:, y:, cell_w:, cell_h:, grid_w:, grid_h:, tileset: nil) click to toggle source

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

[](x, y) click to toggle source

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
cell_rect(grid_coordinates) click to toggle source

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
h() click to toggle source

Returns the height of the tilemap in pixels.

# File lib/dragon_skeleton/tilemap.rb, line 58
def h
  @grid_h * @cell_h
end
render(outputs) click to toggle source

Renders the tilemap to the given outputs / render target.

# File lib/dragon_skeleton/tilemap.rb, line 68
def render(outputs)
  outputs.primitives << @primitive
end
to_grid_coordinates(position) click to toggle source

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
w() click to toggle source

Returns the width of the tilemap in pixels.

# File lib/dragon_skeleton/tilemap.rb, line 53
def w
  @grid_w * @cell_w
end