Skip to content

Commit

Permalink
Merge pull request #14 from zcking/feature/tilemap-example
Browse files Browse the repository at this point in the history
refactored to use batch rendering
  • Loading branch information
faiface committed Feb 6, 2019
2 parents d8a6e4b + a65de95 commit 5880f03
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions community/tilemap/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,20 @@ import (

var clearColor = colornames.Skyblue

var sprites []*pixel.Sprite

func gameloop(win *pixelgl.Window, tilemap *tmx.Map) {
batches := make([]*pixel.Batch, 0)
batchIndices := make(map[string]int)
batchCounter := 0

// Load the sprites
sprites := make(map[string]*pixel.Sprite)
for _, tileset := range tilemap.Tilesets {
if _, alreadyLoaded := sprites[tileset.Image.Source]; !alreadyLoaded {
sprites[tileset.Image.Source] = loadSprite(tileset.Image.Source)
sprite, pictureData := loadSprite(tileset.Image.Source)
sprites[tileset.Image.Source] = sprite
batches = append(batches, pixel.NewBatch(&pixel.TrianglesData{}, pictureData))
batchIndices[tileset.Image.Source] = batchCounter
batchCounter++
}
}

Expand Down Expand Up @@ -59,6 +65,10 @@ func gameloop(win *pixelgl.Window, tilemap *tmx.Map) {
win.Clear(clearColor)

// Draw tiles
for _, batch := range batches {
batch.Clear()
}

for _, layer := range tilemap.Layers {
for tileIndex, tile := range layer.DecodedTiles {
ts := layer.Tileset
Expand All @@ -82,10 +92,13 @@ func gameloop(win *pixelgl.Window, tilemap *tmx.Map) {
sprite := sprites[ts.Image.Source]
sprite.Set(sprite.Picture(), pixel.R(iX, iY, fX, fY))
pos := gamePos.ScaledXY(pixel.V(float64(ts.TileWidth), float64(ts.TileHeight)))
sprite.Draw(win, pixel.IM.Moved(pos))
sprite.Draw(batches[batchIndices[ts.Image.Source]], pixel.IM.Moved(pos))
}
}

for _, batch := range batches {
batch.Draw(win)
}
win.Update()
}
}
Expand Down Expand Up @@ -123,15 +136,15 @@ func run() {
gameloop(win, tilemap)
}

func loadSprite(path string) *pixel.Sprite {
func loadSprite(path string) (*pixel.Sprite, *pixel.PictureData) {
f, err := os.Open(path)
panicIfErr(err)

img, err := png.Decode(f)
panicIfErr(err)

pd := pixel.PictureDataFromImage(img)
return pixel.NewSprite(pd, pd.Bounds())
return pixel.NewSprite(pd, pd.Bounds()), pd
}

func main() {
Expand Down

0 comments on commit 5880f03

Please sign in to comment.