Sprites
The Sprite
struct in the hlg
package provides a way to handle sprite sheets for rendering animations or a series of images in a grid-like structure. Each Sprite
is a subset of a larger texture, representing a single frame of an animation or a single image within a sprite sheet.
Constructor Function
NewSprite
Creates a new Sprite
instance from a given image, frame size, and sheet size.
1func NewSprite(img image.Image, frameSize, sheetSize image.Point) *Sprite
img
: The source image, typically a sprite sheet.frameSize
: The size of a single frame within the sprite sheet.sheetSize
: The size of the sprite sheet in terms of the number of frames horizontally and vertically.
Methods
NextFrame
Advances the sprite to the next frame in the sprite sheet. The method updates the clipping region of the underlying texture to display the next frame.
1func (s *Sprite) NextFrame()
- This method increments the current frame and wraps around if it reaches the end of the sprite sheet.
- Automatically updates the clip region to render the new current frame.
- Calls
Render()
to render the sprite with the updated frame.
Usage Example
1// Assuming you have a sprite sheet image and you know the frame and sheet sizes
2spriteSheetImage := // Load your sprite sheet image
3frameSize := image.Pt(32, 32) // Each frame is 32x32 pixels
4sheetSize := image.Pt(4, 4) // 4 columns and 4 rows in the sprite sheet
5
6sprite := hlg.NewSprite(spriteSheetImage, frameSize, sheetSize)
7
8hlg.Run(func() {
9 sprite.NextFrame() // Update the sprite to the next frame each update call
10}, func() {
11 hlg.Clear(colornames.Black)
12})
In this usage example, sprite.NextFrame()
is called in the hlg.Update
loop to animate the sprite by cycling through frames on each update.
Full Example
1package main
2
3import (
4 "bytes"
5 "image"
6 "time"
7
8 _ "image/png"
9
10 "github.com/dfirebaugh/hlg"
11 "github.com/dfirebaugh/hlg/assets"
12)
13
14func main() {
15 hlg.SetWindowSize(600, 600)
16 hlg.SetTitle("hlg sprite example")
17
18 reader := bytes.NewReader(assets.BuddyDanceSpriteSheet)
19 img, _, err := image.Decode(reader)
20 if err != nil {
21 panic(err)
22 }
23
24 frameSize := image.Point{X: 32, Y: 32}
25 sheetSize := image.Point{X: 4, Y: 1}
26
27 sprite := hlg.NewSprite(img, frameSize, sheetSize)
28 sprite.Scale(.5, .5)
29
30 lastFrameTime := time.Now()
31 frameDuration := time.Millisecond * 200
32
33 hlg.Run(func() {
34 sprite.NextFrame()
35 }, func() {
36 if time.Since(lastFrameTime) >= frameDuration {
37 lastFrameTime = time.Now()
38 }
39 })
40}