iT邦幫忙

2023 iThome 鐵人賽

DAY 24
0
SideProject30

HOW TO GO系列 第 24

24. ebiten (6)

  • 分享至 

  • xImage
  •  

剩最後幾天把一些功能完成

動畫實作

import (
	"bytes"
	"log"

	_ "embed"
	"image"
	_ "image/png"

	"github.com/hajimehoshi/ebiten/v2"
)

//go:embed RedSnail.png
var RedSnail []byte

type Anim struct {
	Sprites []Sprite
	Period  int
}

type Sprite struct {
	Image  *ebiten.Image
	OX     int
	OY     int
	Width  int
	Height int
}

type Snail struct {
	State string
	Anim  []Anim
	PosX  int
	PosY  int
}

func NewSnail() *Snail {
	img, _, err := image.Decode(bytes.NewReader(RedSnail))
	if err != nil {
		log.Fatal(err)
	}
	image := ebiten.NewImageFromImage(img)

	walk1 := Sprite{image, 0, 40, 40, 40}
	walk2 := Sprite{image, 44, 40, 40, 40}
	walk3 := Sprite{image, 96, 40, 50, 40}
	walk4 := Sprite{image, 156, 40, 54, 40}

	walk := Anim{
		Sprites: []Sprite{walk1, walk2, walk3, walk4},
		Period:  20,
	}

	return &Snail{
		State: "walk",
		Anim:  []Anim{walk},
		PosX:  50,
		PosY:  50,
	}
}

func (s *Snail) Draw(screen *ebiten.Image, count int) {

	anim := s.Anim[0]

	i := (count / anim.Period) % len(anim.Sprites)

	op := &ebiten.DrawImageOptions{}
	op.GeoM.Translate(float64(s.PosX), float64(s.PosY))

	sprite := anim.Sprites[i]

	screen.DrawImage(sprite.Image.SubImage(image.Rect(sprite.OX, sprite.OY, sprite.OX+sprite.Width, sprite.OY+sprite.OY)).(*ebiten.Image), op)
}


上一篇
23. Entity Component System (2)
下一篇
25. ebiten (7)
系列文
HOW TO GO30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言