Merge pull request #14 from zcking/feature/tilemap-example

refactored to use batch rendering
This commit is contained in:
Michal Štrba 2019-02-06 17:46:30 +01:00 committed by GitHub
commit 5880f0311b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 19 additions and 6 deletions

View File

@ -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++
}
}
@ -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
@ -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()
}
}
@ -123,7 +136,7 @@ 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)
@ -131,7 +144,7 @@ func loadSprite(path string) *pixel.Sprite {
panicIfErr(err)
pd := pixel.PictureDataFromImage(img)
return pixel.NewSprite(pd, pd.Bounds())
return pixel.NewSprite(pd, pd.Bounds()), pd
}
func main() {