ganim8

package module
v2.1.29 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 24, 2023 License: MIT Imports: 11 Imported by: 8

README

ganim8

Sprite Animation library for Ebitengine inspired by anim8.

v1.x is pretty much the same API with anim8. v2.x is more optimized for Ebiten to be more performant and glanular control introducing Sprite API.

In order to build animations more easily, ganim8 divides the process in two steps: first you create a grid, which is capable of creating frames (Quads) easily and quickly. Then you use the grid to create one or more animations.

GoDoc

Example

import "github.com/yohamta/ganim8/v2"

type Game struct {
  animation *ganim8.Animation
}

func NewGame() *Game {
  g := &Game{ prevTime: time.Now() }

  g32 := ganim8.NewGrid(32, 32, 1024, 1024)
  g.animation = ganim8.New(monsterImage, g32.Frames("1-5", 5), 100*time.Millisecond)

  return g
}

func (g *Game) Draw(screen *ebiten.Image) {
  screen.Clear()
  g.animation.Draw(screen, ganim8.DrawOpts(screenWidth/2, screenHeight/2, 0, 1, 1, 0.5, 0.5))
}

func (g *Game) Update() error {
  g.animation.Update()
  // Note: it assumes that the time delta is 16ms by default 
  //       if you need to specify different delta you can use Animation.UpdateWithDelta(delta) instead
  return nil
}

You can see a more elaborated example.

That demo transforms this spritesheet:

1945

Into several animated objects:

1945

Explanation

Grids

Grids have only one purpose: To build groups of quads of the same size as easily as possible. In order to do this, they need to know only 2 things: the size of each quad and the size of the image they will be applied to. Each size is a width and a height, and those are the first 4 parameters of @ganim8.NewGrid@.

Grids are just a convenient way of getting frames from a sprite. Frames are assumed to be distributed in rows and columns. Frame 1,1 is the one in the first row, first column.

This is how you create a grid:

ganim8.NewGrid(frameWidth, frameHeight, imageWidth, imageHeight, left, top, border)
  • frameWidth and frameHeight are the dimensions of the animation frames - each of the individual "sub-images" that compose the animation. They are usually the same size as your character (so if the character is 32x32 pixels, frameWidth is 32 and so is frameHeight)
  • imageWidth and imageHeight are the dimensions of the image where all the frames are.
  • left and top are optional, and both default to 0. They are "the left and top coordinates of the point in the image where you want to put the origin of coordinates of the grid". If all the frames in your grid are the same size, and the first one's top-left corner is 0,0, you probably won't need to use left or top.
  • border is also an optional value, and it also defaults to zero. What border does is allowing you to define "gaps" between your frames in the image. For example, imagine that you have frames of 32x32, but they have a 1-px border around each frame. So the first frame is not at 0,0, but at 1,1 (because of the border), the second one is at 1,33 (for the extra border) etc. You can take this into account and "skip" these borders.

To see this a bit more graphically, here are what those values mean for the grid which contains the "submarine" frames in the demo:

explanation

Grids only have one important method: Grid.Frames(...).

Grid.Frames accepts an arbitrary number of parameters. They can be either numbers or strings.

  • Each two numbers are interpreted as quad coordinates in the format (column, row). This way, grid.Frames(3,4) will return the frame in column 3, row 4 of the grid. There can be more than just two: grid.Frames(1,1, 1,2, 1,3) will return the frames in {1,1}, {1,2} and {1,3} respectively.
  • Using numbers for long rows or columns is tedious - so grids also accept strings indicating range plus a row/column index. Diferentiating rows and columns is based on the order in which the range and index are provided. A row can be fetch by calling grid.Frames("range", rowNumber) and a column by calling grid.Frames(columnNumber, "range"). The previous column of 3 elements, for example, can be also expressed like this: grid.Frames(1,"1-3"). Again, there can be more than one string-index pair (grid.Frames(1,"1-3", "2-4",3))
  • It's also possible to combine both formats. For example: grid.Frames(1,4, 1,"1-3") will get the frame in {1,4} plus the frames 1 to 3 in column 1

Let's consider the submarine in the previous example. It has 7 frames, arranged horizontally.

If you make its grid start on its first frame (using left and top), you can get its frames like this:

                  // frame, image,     offsets, border
gs := ganim8.NewGrid(32,98, 1024,768,  366,102,   1)

frames := gs.Frames("1-7",1)

However that way you will get a submarine which "emerges", then "suddenly disappears", and emerges again. To make it look more natural, you must add some animation frames "backwards", to give the illusion of "submersion". Here's the complete list:

frames := gs.Frames("1-7",1, "6-2",1)
Animations

Animations are groups of frames that are interchanged every now and then.

animation := ganim8.New(img, frames, durations, onLoop)
  • img is an image object to use for the animation.
  • frames is an array of frames (image.Rectangle). You could provide your own quad array if you wanted to, but using a grid to get them is very convenient.
  • durations is a number or a table. When it's a number, it represents the duration of all frames in the animation. When it's a table, it can represent different durations for different frames. You can specify durations for all frames individually, like this: []time.Duration{time.Milliseconds * 100, time.Milliseconds * 500, time.Milliseconds * 100} or you can specify durations for ranges of frames: map[string]time.Duration{"3-5": time.Milliseconds * 200}.
  • onLoop is an optional parameter which can be a function or a string representing one of the animation methods. It does nothing by default. If specified, it will be called every time an animation "loops". It will have two parameters: the animation instance, and how many loops have been elapsed. The most usual value (apart from none) is the string 'pauseAtEnd'. It will make the animation loop once and then pause and stop on the last frame.

Animations have the following methods:

animation.Update()

Use this inside Game.Update() so that your animation changes frames according to the time that has passed.

It assumes that the time delta is 1/60[s] (1/TPS to be exact). For more details about TPS (ticks per seconds) in Ebitengine is explained here that is written by tinne26.

If you need to specify delta for update animations, you can use UpdateWithDelta() instead:

animation.UpdateWithDelta(delta)
animation.Draw(screen, ganim8.DrawOpts(x,y, angle, sx, sy, ox, oy))
animation.GoToFrame(frame)

Moves the animation to a given frame (frames start counting in 1).

animation.Pause()

Stops the animation from updating.

animation.Resume()

Unpauses an animation

animation.Clone()

Creates a new animation identical to the current one. The only difference is that its internal counter is reset to 0 (it's on the first frame).

animation.Sprite().FlipH()

Flips an animation horizontally (left goes to right and viceversa). This means that the frames are simply drawn differently, nothing more.

Note that this method does not create a new animation. If you want to create a new one, use the Clone method.

This method returns the animation, so you can do things like a := ganim8.New(img, g.Frames(1,"1-10"), time.Milliseconds * 100).FlipH() or b := a.Clone().FlipV().

animation.FlipV()

Flips an animation vertically. The same rules that apply to FlipH also apply here.

animation.PauseAtEnd()

Moves the animation to its last frame and then pauses it.

animation.PauseAtStart()

Moves the animation to its first frame and then pauses it.

animation.GetDimensions()

Returns the width and height of the current frame of the animation. This method assumes the frames passed to the animation are all quads (like the ones created by a grid).

How to contribute?

Feel free to contribute in any way you want. Share ideas, questions, submit issues, and create pull requests. Thanks!

Documentation

Index

Constants

View Source
const (
	Playing = iota
	Paused
)

Variables

View Source
var DefaultDelta = time.Millisecond * 16

Functions

func DrawAnime added in v2.0.7

func DrawAnime(screen *ebiten.Image, anim *Animation, x, y, rot, sx, sy, ox, oy float64)

DrawAnime draws an animation to the screen.

func DrawAnimeWithOpts added in v2.0.11

func DrawAnimeWithOpts(screen *ebiten.Image, anim *Animation, opts *DrawOptions, shaderOpts *ShaderOptions)

DrawAnimeWithOpts draws an anime to the screen.

func DrawSprite added in v2.0.8

func DrawSprite(screen *ebiten.Image, spr *Sprite, index int, x, y, rot, sx, sy, ox, oy float64)

DrawSprite draws a sprite to the screen.

func DrawSpriteWithOpts added in v2.0.11

func DrawSpriteWithOpts(screen *ebiten.Image, spr *Sprite, index int, opts *DrawOptions, shaderOpts *ShaderOptions)

DrawSpriteWithOpts draws a sprite to the screen.

func Nop

func Nop(anim *Animation, loops int)

Nop does nothing.

func Pause

func Pause(anim *Animation, loops int)

Pause pauses the animation on loop finished.

func PauseAtEnd

func PauseAtEnd(anim *Animation, loops int)

PauseAtEnd pauses the animation and set the position to the last frame.

func PauseAtStart

func PauseAtStart(anim *Animation, loops int)

PauseAtStart pauses the animation and set the position to the first frame.

Types

type Animation

type Animation struct {
	// contains filtered or unexported fields
}

Animation represents an animation created from specified frames and an *ebiten.Image

func New added in v2.1.0

func New(img *ebiten.Image, frames []*image.Rectangle, durations interface{}, onLoop ...OnLoop) *Animation

New creates a new animation from the specified image

func NewAnimation

func NewAnimation(sprite *Sprite, durations interface{}, onLoop ...OnLoop) *Animation

NewAnimation returns a new animation object

durations is a time.Duration or a []time.Duration or a map[string]time.Duration. When it's a time.Duration, it represents the duration of all frames in the animation. When it's a []time.Duration, it can represent different durations for different frames. You can specify durations for all frames individually, like this: []time.Duration { 100 * time.Millisecond, 100 * time.Millisecond } or you can specify durations for ranges of frames: map[string]time.Duration { "1-2": 100 * time.Millisecond, "3-5": 200 * time.Millisecond }.

func (*Animation) Clone

func (anim *Animation) Clone() *Animation

Clone return a copied animation object.

func (*Animation) Draw

func (anim *Animation) Draw(screen *ebiten.Image, opts *DrawOptions)

Draw draws the animation with the specified option parameters.

func (*Animation) DrawWithShader

func (anim *Animation) DrawWithShader(screen *ebiten.Image, opts *DrawOptions, shaderOpts *ShaderOptions)

DrawWithShader draws the animation with the specified option parameters.

func (*Animation) Durations

func (anim *Animation) Durations() []time.Duration

Duration returns the current durations of each frames.

func (*Animation) GoToFrame

func (anim *Animation) GoToFrame(position int)

GoToFrame sets the position of the animation and sets the timer at the start of the frame.

func (*Animation) H

func (anim *Animation) H() int

H is a shortcut for Size().Y.

func (*Animation) IsEnd added in v2.1.29

func (anim *Animation) IsEnd() bool

func (*Animation) Pause

func (anim *Animation) Pause()

Pause pauses the animation.

func (*Animation) PauseAtEnd

func (anim *Animation) PauseAtEnd()

PauseAtEnd pauses the animation and set the position to the last frame.

func (*Animation) PauseAtStart

func (anim *Animation) PauseAtStart()

PauseAtStart pauses the animation and set the position to the first frame.

func (*Animation) Position

func (anim *Animation) Position() int

Position returns the current position of the frame. The position counts from 1 (not 0).

func (*Animation) Resume

func (anim *Animation) Resume()

Resume resumes the animation

func (*Animation) SetDurations added in v2.0.18

func (anim *Animation) SetDurations(durations interface{})

SetDurations sets the durations of the animation.

func (*Animation) SetOnLoop added in v2.1.28

func (anim *Animation) SetOnLoop(onLoop OnLoop)

SetOnLoop sets the callback function which representing

func (*Animation) Size

func (anim *Animation) Size() (int, int)

Size returns the size of the current frame.

func (*Animation) Sprite added in v2.0.20

func (anim *Animation) Sprite() *Sprite

Sprite returns the sprite of the animation.

func (*Animation) Status

func (anim *Animation) Status() Status

Status returns the status of the animation.

func (*Animation) Timer

func (anim *Animation) Timer() time.Duration

Timer returns the current accumulated times of current frame.

func (*Animation) TotalDuration

func (anim *Animation) TotalDuration() time.Duration

TotalDuration returns the total duration of the animation.

func (*Animation) Update

func (anim *Animation) Update()

Update updates the animation.

func (*Animation) UpdateWithDelta added in v2.1.24

func (anim *Animation) UpdateWithDelta(elapsedTime time.Duration)

UpdateWithDelta updates the animation with the specified delta.

func (*Animation) W

func (anim *Animation) W() int

W is a shortcut for Size().X.

type DrawOptions

type DrawOptions struct {
	X, Y             float64
	Rotate           float64
	ScaleX, ScaleY   float64
	OriginX, OriginY float64
	ColorM           ebiten.ColorM
	CompositeMode    ebiten.CompositeMode
}

DrawOptions represents the option for Sprite.Draw(). For shortcut, DrawOpts() function can be used.

func DrawOpts

func DrawOpts(x, y float64, args ...float64) *DrawOptions

DrawOpts returns DrawOptions pointer with specified settings. The paramters are x, y, rotate (in radian), scaleX, scaleY originX, originY. If scaleX and ScaleY is not specified the default value will be 1.0, 1.0. If OriginX and OriginY is not specified the default value will be 0, 0

func (*DrawOptions) Reset added in v2.0.9

func (drawOpts *DrawOptions) Reset()

Reset resets the DrawOptions to default values.

func (*DrawOptions) ResetValues added in v2.0.10

func (drawOpts *DrawOptions) ResetValues(x, y, rot, sx, sy, ox, oy float64)

ResetValues resets the DrawOptions to default values

func (*DrawOptions) SetOrigin added in v2.0.6

func (drawOpts *DrawOptions) SetOrigin(x, y float64)

SetOrigin sets the origin of the sprite.

func (*DrawOptions) SetPos added in v2.0.6

func (drawOpts *DrawOptions) SetPos(x, y float64)

SetPos sets the position of the sprite.

func (*DrawOptions) SetRot added in v2.0.7

func (drawOpts *DrawOptions) SetRot(r float64)

SetRotate sets the rotation of the sprite.

func (*DrawOptions) SetScale added in v2.0.6

func (drawOpts *DrawOptions) SetScale(x, y float64)

SetScale sets the scale of the sprite.

type Grid

type Grid struct {
	// contains filtered or unexported fields
}

Grid represents a grid

func NewGrid

func NewGrid(frameWidth, frameHeight, imageWidth, imageHeight int, args ...int) *Grid

NewGrid returns a new grid with specified frame size, image size, and offsets (left, top).

Grids have only one purpose: To build groups of quads of the same size as easily as possible.

They need to know only 2 things: the size of each frame and the size of the image they will be applied to.

Grids are just a convenient way of getting frames from a sprite. Frames are assumed to be distributed in rows and columns. Frame 1,1 is the one in the first row, first column.

func (*Grid) Frames added in v2.1.0

func (g *Grid) Frames(args ...interface{}) []*image.Rectangle

Frames is a shorter name of GetFrames

func (*Grid) G

func (g *Grid) G(args ...interface{}) []*image.Rectangle

G is a shorter name of GetFrames

func (*Grid) GetFrames

func (g *Grid) GetFrames(args ...interface{}) []*image.Rectangle

GetFrames accepts an arbitrary number of parameters. They can be either numbers or strings.

Each two numbers are interpreted as quad coordinates in the format (column, row). This way, grid:getFrames(3,4) will return the frame in column 3, row 4 of the grid.

There can be more than just two: grid:getFrames(1,1, 1,2, 1,3) will return the frames in {1,1}, {1,2} and {1,3} respectively.

func (*Grid) Height added in v2.0.17

func (g *Grid) Height() int

Height returns the height of the grid

func (*Grid) Width added in v2.0.17

func (g *Grid) Width() int

Width returns the width of the grid

type OnLoop

type OnLoop func(anim *Animation, loops int)

OnLoop is callback function which representing one of the animation methods. it will be called every time an animation "loops".

It will have two parameters: the animation instance, and how many loops have been elapsed.

The value would be Nop (No operation) if there's nothing to do except for looping the animation.

The most usual value (apart from none) is the string 'pauseAtEnd'. It will make the animation loop once and then pause and stop on the last frame.

type ShaderOptions

type ShaderOptions struct {
	Uniforms map[string]interface{}
	Shader   *ebiten.Shader
	Images   [3]*ebiten.Image
}

ShaderOptions represents the option for Sprite.DrawWithShader()

type Sprite

type Sprite struct {
	// contains filtered or unexported fields
}

Sprite is a sprite that can be drawn to the screen. It can be animated by changing the current frame.

func NewSprite

func NewSprite(img *ebiten.Image, frames []*image.Rectangle) *Sprite

NewSprite returns a new sprite.

func (*Sprite) Clone added in v2.1.26

func (spr *Sprite) Clone() *Sprite

func (*Sprite) Draw

func (spr *Sprite) Draw(screen *ebiten.Image, index int, opts *DrawOptions)

Draw draws the current frame with the specified options.

func (*Sprite) DrawWithShader

func (spr *Sprite) DrawWithShader(screen *ebiten.Image, index int, opts *DrawOptions, shaderOpts *ShaderOptions)

DrawWithShader draws the current frame with the specified options.

func (*Sprite) FlipH

func (spr *Sprite) FlipH()

FlipH flips the animation horizontally.

func (*Sprite) FlipV

func (spr *Sprite) FlipV()

FlipV flips the animation horizontally.

func (*Sprite) H

func (spr *Sprite) H() int

H is a shortcut for Height().

func (*Sprite) Height added in v2.0.19

func (spr *Sprite) Height() int

Height returns the height of the sprite.

func (*Sprite) IsEnd

func (spr *Sprite) IsEnd(index int) bool

IsEnd returns true if the current frame is the last frame.

func (*Sprite) Length added in v2.0.5

func (spr *Sprite) Length() int

Length returns the number of frames.

func (*Sprite) LoopIndex added in v2.0.15

func (spr *Sprite) LoopIndex(index int) int

LoopIndex returns loop index of the sprite.

func (*Sprite) RandomIndex added in v2.0.14

func (spr *Sprite) RandomIndex() int

RandomIndex returns random index of the sprite

func (*Sprite) SetFlipH added in v2.0.22

func (spr *Sprite) SetFlipH(flipH bool)

SetFlipH flips the sprite horizontally.

func (*Sprite) SetFlipV added in v2.0.22

func (spr *Sprite) SetFlipV(flipV bool)

SetFlipV flips the sprite vertically.

func (*Sprite) Size

func (spr *Sprite) Size() (int, int)

Size returns the size of the sprite.

func (*Sprite) W

func (spr *Sprite) W() int

W is a shortcut for Width().

func (*Sprite) Width added in v2.0.19

func (spr *Sprite) Width() int

Width returns the width of the sprite.

type SpriteSize

type SpriteSize struct {
	W, H int
}

type SpriteSizeF added in v2.0.4

type SpriteSizeF struct {
	W, H float64
}

type Status

type Status int

Status represents the animation status.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL