diff --git a/README.md b/README.md index ce02883..e91ce86 100644 --- a/README.md +++ b/README.md @@ -1,199 +1,199 @@ # ganim8 -Sprite animation library for [Ebitengin](https://ebiten.org/) inspired by [anim8](https://github.com/kikito/anim8). +Animation library for [Ebitengin](https://ebiten.org/) inspired by [anim8](https://github.com/kikito/anim8). -- v1.x is pretty much the same API with [anim8](https://github.com/kikito/anim8). -- v2.x is more optimized for Ebiten to be more performant and glanular control introducing [Sprite](https://pkg.go.dev/github.com/yohamta/ganim8/v2#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](https://pkg.go.dev/github.com/yohamta/ganim8/v2) ## Contents - - [Concept](#concept) - - [Brief usage](#brief-usage) +- [ganim8](#ganim8) + - [Contents](#contents) - [Example](#example) + - [Explanation](#explanation) + - [Grids](#grids) + - [Animations](#animations) - [How to contribute?](#how-to-contribute) -## Concept +## Example -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. +```go +import "github.com/yohamta/ganim8/v2" + +type Game struct { + prevTime time.Time + 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 { + now := time.Now() + delta := now.Sub(g.prevTime) -## Brief usage + g.animation.Update(delta) + g.prevTime = now + + return nil +} +``` + +You can see a more elaborated [examples](examples/demo/main.go). + +That demo transforms this spritesheet: + +![1945](examples/demo/assets/1945.png) + +Into several animated objects: + +![1945](assets/demo.gif) + +## 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 @anim8.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: -**Create a Grid** ```go -gridWidth, gridHeight := 32, 32 -imgWidth, imgHeight := 320, 320 -var grid *Grid = ganim8.NewGrid(gridWidth, gridHeight, imageWidth, imageHeight int) +ganim8.NewGrid(frameWidth, frameHeight, imageWidth, imageHeight, left, top, border) ``` -**Create frames(Quads) from a Grid** +* `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](assets/explanation.png) + +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: ```go -var column string = "1-5" -var row int = 1 -var frames []*image.Rectangle = grid.GetFrames(column, row) + // frame, image, offsets, border +gs := ganim8.NewGrid(32,98, 1024,768, 366,102, 1) + +frames := gs.Framees("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: +```go +frames := gs.Frames("1-7",1, "6-2",1) ``` -**Create a Sprite from frames(Quads)** +### Animations + +Animations are groups of frames that are interchanged every now and then. ```go -var spr *ganim8.Sprite = ganim8.NewSprite(img, frames) +animation := anim8.New(img, frames, durations, onLoop) +``` + +* `img` is an image object to use for the animation. +* `frames` is an array of frames ([image.Rectangle](https://pkg.go.dev/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. -// Draw a Sprite -x, y := 0, 0 -rotaion, scaleX, scaleY, originX, originY := 0.0, 1.0, 1.0, 0.5, 0.5 -ganim8.DrawSprite(screen, spr, frameIndex, x, y, rotation, scaleX, scaleY, originX, originY) +Animations have the following methods: + +```go +animation.Update(dt) ``` -**Create an Animation from a Sprite** +Use this inside `Game.Update()` so that your animation changes frames according to the time that has passed. ```go -// Create an Animation from a Sprite -var duration time.Duration = time.Milliseconds * 20 -var onLoop func(anim *Animation, loops int) = ganim8.Nop // LOOP animation -var anim *ganim8.Animation = ganim8.NewAnimation(spr, durations, onLoop) +animation.Draw(screen, ganim8.DrawOpts(x,y, angle, sx, sy, ox, oy)) +``` -// Update an Animation with elapsed time -anim.Update(time.Milliseconds * 20) +```go +animation.GoToFrame(frame) +``` -// Draw an Animation -ganim8.DrawAnime(screen, spr, frameIndex, x, y, rotation, scaleX, scaleY, originX, originY) +Moves the animation to a given frame (frames start counting in 1). + +```go +animation.Pause() ``` -There're other utility functions such as [DrawOpts](https://pkg.go.dev/github.com/yohamta/ganim8/v2#DrawOpts), [DrawSpriteWithOpts](https://pkg.go.dev/github.com/yohamta/ganim8/v2#DrawSpriteWithOpts), and [DrawAnimeWithOpts](https://pkg.go.dev/github.com/yohamta/ganim8/v2#DrawAnimeWithOpts). Refer the [GoDoc](https://pkg.go.dev/github.com/yohamta/ganim8/v2) for more details. +Stops the animation from updating. -## Example +```go +animation.Resume() +``` + +Unpauses an animation ```go -import "github.com/yohamta/ganim8/v2" +animation.Clone() +``` -type Game struct { - prevUpdateTime time.Time - anim *ganim8.Animation -} +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). -func NewGame() *Game { - g := &Game{ prevUpdateTime: time.Now() } - - // Grids are just a convenient way of getting frames of the same size from a - // single sprite texture. - // animation frames are represented as groups of rectangles (image.Rectangle). - // They need to know only 2 things: the size of frames and the size of - // the image they will be applied to, and those are the first 4 parameters of NewGrid() - // - // NewGrid() parameters accpets 4 - 6 parameters: - // ganim8.NewGrid(frameWidth, frameHeight, imageWidth, imageHeight, left, top) - // "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". - // - // In this example, it make a grid with the frame size of {100,100} and - // the image size of {500,600} - grid := ganim8.NewGrid(100, 100, 500, 600) - - // Grids have one important method: Grid.GetFrames(...). - // Grid.GetFrames() accepts an arbitrary number of parameters. - // They can be either number or strings. - // Each two numbers are interpreted as rectangle coordinates in - // the format (column, row). - // - // This way, grid.GetFrames(3, 4) will return the frame in column 3, - // row 4 of the grid. - // They can be more than just two: grid.GetFrames(1,1, 1,2, 1,3) will - // return frames in {1,2}, {1,2} and {1,3} respectively. - // - // Using numbers for long rows or columns is tedious - so grid - // also accpet strings indicating range plus a row/column index. - // A row can be fetch by calling grid.GetFrames('range', rowNumber) and - // a column by calling grid.GetFrames(columnNumber, 'range'). - // - // It's also possible to combine both formats. - // For example: grid.GetFrames(1, 3, 1, '1-3') will get the frame in {1,4} - // plus the frames 1 to 3 in column 1. - // - // The below code get frames 1 to 5 column in row 5 - frames := grid.GetFrames("1-5", 5) - - // Sprites are groups of frames that caches subImages of the specified grid and the texture - // Sprite accepts 2 parameters: a textureImage and frames - // frames is an array of frames ([]*image.Rectangle). - sprite := ganim8.NewSprite(monsterImage, grid.GetFrames("1-5", 5)) - - // Animations are wrappers of Sprites. - // It is handy to update the sprite automatically with specified time duration. - // - // NewAnimation() accepts 3 parameters: - // ganim8.NewAnimation(sprite, durations, onLoop) - // - // durations is a time.Duration or []time.Duration or - // map[string]time.Duration. - // When it's a time.Duration, it represents the duration of all frames - // in the animation. - // When it's a slice, it can represent different durations for different frames. - // You can specify durations for all frames individually or you can - // specify duration for ranges of frames: - // map[string]time.Duration{ "3-5" : 2 * time.Millisecond } - // - // onLoop is function of the animetion methods or callback. - // If ganim8.Nop is specified, it does nothing. - // If ganim8.PauseAtEnd is specified, it pauses at the end of the animation. - // It can be any function that follows the type "func(anim *Animation, loops int)". - // The first parameter is the animation object and the second parameter is - // the count of the loops that elapsed since the previous Animation.Update(). - g.anim = ganim8.NewAnimation(sprite, 100*time.Millisecond, ganim8.Nop) +```go +animation.Sprite().FlipH() +``` - return g -} +Flips an animation horizontally (left goes to right and viceversa). This means that the frames are simply drawn differently, nothing more. -func (g *Game) Draw(screen *ebiten.Image) { - screen.Clear() +Note that this method does not create a new animation. If you want to create a new one, use the `Clone` method. - // Animation.Draw() draws the current frame of the animation. - // It accepts screen image to draw on, source texture image, and draw options. - // Draw options are x, y, angle (radian), scaleX, scaleY, originX and originY. - // OriginX and OriginY are useful to draw the animation with scaling, centering, - // rotating etc. - // - // DrawOpts() is just a shortcut of creating DrawOption object. - // It only needs the first 2 parameters x and y. - // The rest of the parameters (angle, scaleX, scaleY, originX, orignY) - // are optional. - // If those are not specified, defaults values will be applied. - // - // In this example, it draws the animation at the center of the screen. - g.anim.Draw(screen, ganim8.DrawOpts(screenWidth/2, screenHeight/2, 0, 1, 1, 0.5, 0.5)) -} +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()`. -func (g *Game) Update() error { - now := time.Now() +```go +animation.FlipV() +``` - // Animation.Update() updates the animation. - // It receives time.Duration value and set the current frame of the animation. - // Each duration time of each frames can be customized for example like this: - // ganim8.NewAnimation( - // grid.GetFrames("1-5", 5), - // map[string]time.Duration { - // "1-2" : 100*time.Millisecond, - // "3" : 300*time.Millisecond, - // "4-5" : 100*time.Millisecond, - // }) - g.anim.Update(now.Sub(g.prevUpdateTime)) - - g.prevUpdateTime = now - return nil -} +Flips an animation vertically. The same rules that apply to `FlipH` also apply here. + +```go +animation.PauseAtEnd() ``` -[source code](https://github.com/yohamta/ganim8/blob/master/examples/simple/main.go) +Moves the animation to its last frame and then pauses it. -Example Result +```go +animation.PauseAtStart() +``` - +Moves the animation to its first frame and then pauses it. -The texture used in the example +```go +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? diff --git a/assets/demo.gif b/assets/demo.gif new file mode 100644 index 0000000..733a3c8 Binary files /dev/null and b/assets/demo.gif differ diff --git a/assets/explanation.png b/assets/explanation.png new file mode 100644 index 0000000..1c0f2e5 Binary files /dev/null and b/assets/explanation.png differ diff --git a/examples/demo/assets/1945.png b/examples/demo/assets/1945.png new file mode 100644 index 0000000..01118ad Binary files /dev/null and b/examples/demo/assets/1945.png differ diff --git a/examples/demo/assets/LICENSE.txt b/examples/demo/assets/LICENSE.txt new file mode 100644 index 0000000..996c37d --- /dev/null +++ b/examples/demo/assets/LICENSE.txt @@ -0,0 +1,6 @@ +The accompaning png file is a slightly modified version of the one that +can be found in Spritelib: + +http://www.widgetworx.com/widgetworx/portfolio/spritelib.html + +Released under the terms of the Public Common License diff --git a/examples/demo/main.go b/examples/demo/main.go new file mode 100644 index 0000000..226942d --- /dev/null +++ b/examples/demo/main.go @@ -0,0 +1,132 @@ +package main + +import ( + "bytes" + "embed" + "image" + _ "image/png" + "log" + "math" + "time" + + "github.com/hajimehoshi/ebiten/v2" + + "github.com/yohamta/ganim8/v2" +) + +const ( + screenWidth = 800 + screenHeight = 600 +) + +type Game struct { + prev time.Time + spinning []*ganim8.Animation + plane *ganim8.Animation + seaplane *ganim8.Animation + seaplaneAngle float64 + submarine *ganim8.Animation +} + +func NewGame() *Game { + g := &Game{ + prev: time.Now(), + } + g.setupAnimations() + + return g +} + +func (g *Game) Update() error { + now := time.Now() + delta := now.Sub(g.prev) + g.prev = now + + for _, a := range g.spinning { + a.Update(delta) + } + g.plane.Update(delta) + g.seaplane.Update(delta) + g.submarine.Update(delta) + g.seaplaneAngle += g.seaplaneAngle + float64(delta.Milliseconds())*math.Pi/180 + + return nil +} + +func (g *Game) Draw(screen *ebiten.Image) { + screen.Clear() + + for i, a := range g.spinning { + a.Draw(screen, ganim8.DrawOpts(float64(i)*75, float64(i)*50)) + // Alternative way to draw an animation: + // ganim8.DrawAnime(screen, a, float64(i)*75, float64(i)*50, 0, 1, 1, .5, .5) + } + g.plane.Draw(screen, ganim8.DrawOpts(100, 400)) + g.seaplane.Draw(screen, ganim8.DrawOpts(250, 432, g.seaplaneAngle, 1, 1, 32, 32)) + g.submarine.Draw(screen, ganim8.DrawOpts(600, 100)) +} + +func (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) { + return screenWidth, screenHeight +} + +func (g *Game) setupAnimations() { + img := ebiten.NewImageFromImage(readImage("assets/1945.png")) + + // frame(w,h), image(w,h), offsets, border + g32 := ganim8.NewGrid(32, 32, 1024, 768, 3, 3, 1) + + g.spinning = []*ganim8.Animation{ + ganim8.New(img, g32.Frames("1-8", 1), time.Millisecond*100), + ganim8.New(img, g32.Frames(18, "8-11", 18, "10-7"), time.Millisecond*200), + ganim8.New(img, g32.Frames("1-8", 2), time.Millisecond*300), + ganim8.New(img, g32.Frames(19, "8-11", 19, "10-7"), time.Millisecond*400), + ganim8.New(img, g32.Frames("1-8", 3), time.Millisecond*500), + ganim8.New(img, g32.Frames(20, "8-11", 20, "10-7"), time.Millisecond*600), + ganim8.New(img, g32.Frames("1-8", 4), time.Millisecond*700), + ganim8.New(img, g32.Frames(21, "8-11", 21, "10-7"), time.Millisecond*800), + ganim8.New(img, g32.Frames("1-8", 5), time.Millisecond*900), + } + + // frame(w,h), image(w,h), offsets, border + g64 := ganim8.NewGrid(64, 64, 1024, 768, 299, 101, 2) + + g.plane = ganim8.New(img, g64.Frames(1, "1-3"), time.Millisecond*100) + g.seaplane = ganim8.New(img, g64.Frames("2-4", 3), time.Millisecond*100) + g.seaplaneAngle = 0 + + // frame(w,h), image(w,h), offsets, border + gs := ganim8.NewGrid(32, 98, 1024, 768, 366, 102, 1) + + g.submarine = ganim8.New(img, gs.Frames("1-7", 1, "6-2", 1), + // individual frame delays + map[string]time.Duration{ + "1": time.Second * 2, + "2-6": time.Millisecond * 100, + "7": time.Second * 1, + "8-12": time.Millisecond * 100, + }) +} + +//go:embed assets/* +var assets embed.FS + +func readImage(file string) image.Image { + b, _ := assets.ReadFile(file) + return bytes2Image(&b) +} + +func bytes2Image(rawImage *[]byte) image.Image { + img, format, error := image.Decode(bytes.NewReader(*rawImage)) + if error != nil { + log.Fatal("Bytes2Image Failed: ", format, error) + } + return img +} + +func main() { + ebiten.SetWindowSize(screenWidth, screenHeight) + if err := ebiten.RunGame(NewGame()); err != nil { + log.Fatal(err) + } +} diff --git a/examples/simple/assets/monster.png b/examples/simple/assets/monster.png deleted file mode 100755 index 0f9f8fc..0000000 Binary files a/examples/simple/assets/monster.png and /dev/null differ diff --git a/examples/simple/main.go b/examples/simple/main.go deleted file mode 100644 index 9365917..0000000 --- a/examples/simple/main.go +++ /dev/null @@ -1,81 +0,0 @@ -package main - -import ( - "bytes" - "embed" - "image" - _ "image/png" - "log" - "time" - - "github.com/hajimehoshi/ebiten/v2" - - "github.com/yohamta/ganim8/v2" -) - -const ( - screenWidth = 300 - screenHeight = 300 -) - -type Game struct { - prev time.Time - animation *ganim8.Animation -} - -func NewGame() *Game { - g := &Game{ - prev: time.Now(), - } - g.setupMonsterAnimation() - - return g -} - -func (g *Game) Update() error { - elapsedTime := time.Now().Sub(g.prev) - g.prev = time.Now() - - g.animation.Update(elapsedTime) - - return nil -} - -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) Layout(outsideWidth, outsideHeight int) (int, int) { - return screenWidth, screenHeight -} - -func (g *Game) setupMonsterAnimation() { - grid := ganim8.NewGrid(100, 100, 500, 600) - img := ebiten.NewImageFromImage(readImage("assets/monster.png")) - sprite := ganim8.NewSprite(img, grid.GetFrames("1-5", 5)) - g.animation = ganim8.NewAnimation(sprite, 100*time.Millisecond, ganim8.Nop) -} - -//go:embed assets/* -var assets embed.FS - -func readImage(file string) image.Image { - b, _ := assets.ReadFile(file) - return bytes2Image(&b) -} - -func bytes2Image(rawImage *[]byte) image.Image { - img, format, error := image.Decode(bytes.NewReader(*rawImage)) - if error != nil { - log.Fatal("Bytes2Image Failed: ", format, error) - } - return img -} - -func main() { - ebiten.SetWindowSize(screenWidth, screenHeight) - if err := ebiten.RunGame(NewGame()); err != nil { - log.Fatal(err) - } -}