Skip to content

Commit

Permalink
feat: Implement #to_grid_coordinates and #cell_rect for Tilemap
Browse files Browse the repository at this point in the history
  • Loading branch information
kfischer-okarin committed Feb 26, 2023
1 parent d46347d commit cfeec2c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/dragon_skeleton/tilemap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,24 @@ def render(outputs)
outputs.primitives << @primitive
end

# Converts a position to grid coordinates.
def to_grid_coordinates(position)
{
x: (position.x - @x).idiv(@cell_w),
y: (position.y - @y).idiv(@cell_h)
}
end

# Returns the rectangle of the cell at the given grid coordinates.
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

class RenderedPrimitive # :nodoc: Internal class responsible for rendering the tilemap.
def initialize(cells, tilemap)
@cells = cells
Expand Down
12 changes: 12 additions & 0 deletions tests/lib/dragon_skeleton/tilemap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ def test_tilemap_render(args, assert)
# rubocop:enable all
end

def test_tilemap_to_grid_coordinates(_args, assert)
tilemap = Tilemap.new(x: 50, y: 50, cell_w: 100, cell_h: 100, grid_w: 2, grid_h: 3)

assert.equal! tilemap.to_grid_coordinates({ x: 55, y: 55 }), { x: 0, y: 0 }
end

def test_tilemap_cell_rect(_args, assert)
tilemap = Tilemap.new(x: 50, y: 50, cell_w: 100, cell_h: 100, grid_w: 2, grid_h: 3)

assert.equal! tilemap.cell_rect({ x: 1, y: 2 }), { x: 150, y: 250, w: 100, h: 100 }
end

def test_tilemap_tileset_assigns_default_tile(_args, assert)
tileset = TestTileset.new(
default_tile: { tile_w: 50, tile_h: 50 },
Expand Down

0 comments on commit cfeec2c

Please sign in to comment.