1
0

spritesheet.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2021 The Ebiten Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "bytes"
  17. "image"
  18. _ "image/png"
  19. "github.com/hajimehoshi/ebiten/v2"
  20. "github.com/hajimehoshi/ebiten/v2/examples/resources/images"
  21. )
  22. // SpriteSheet represents a collection of sprite images.
  23. type SpriteSheet struct {
  24. Floor *ebiten.Image
  25. Wall *ebiten.Image
  26. Statue *ebiten.Image
  27. Tube *ebiten.Image
  28. Crown *ebiten.Image
  29. Portal *ebiten.Image
  30. }
  31. // LoadSpriteSheet loads the embedded SpriteSheet.
  32. func LoadSpriteSheet(tileSize int) (*SpriteSheet, error) {
  33. img, _, err := image.Decode(bytes.NewReader(images.Spritesheet_png))
  34. if err != nil {
  35. return nil, err
  36. }
  37. sheet := ebiten.NewImageFromImage(img)
  38. // spriteAt returns a sprite at the provided coordinates.
  39. spriteAt := func(x, y int) *ebiten.Image {
  40. return sheet.SubImage(image.Rect(x*tileSize, (y+1)*tileSize, (x+1)*tileSize, y*tileSize)).(*ebiten.Image)
  41. }
  42. // Populate SpriteSheet.
  43. s := &SpriteSheet{}
  44. s.Floor = spriteAt(10, 4)
  45. s.Wall = spriteAt(2, 3)
  46. s.Statue = spriteAt(5, 4)
  47. s.Tube = spriteAt(3, 4)
  48. s.Crown = spriteAt(8, 6)
  49. s.Portal = spriteAt(5, 6)
  50. return s, nil
  51. }