Skip to content

Commit

Permalink
Merge pull request #6 from yohamta/develop
Browse files Browse the repository at this point in the history
Update README & Demo
  • Loading branch information
yohamta authored Aug 8, 2022
2 parents c43ab3d + e64deb7 commit 7b6c5e8
Show file tree
Hide file tree
Showing 8 changed files with 286 additions and 229 deletions.
296 changes: 148 additions & 148 deletions README.md
Original file line number Diff line number Diff line change
@@ -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()
```

<img src="examples/gif/example.gif?raw=true" width="300" />
Moves the animation to its first frame and then pauses it.

The texture used in the example
```go
animation.GetDimensions()
```

<img src="examples/assets/images/Character_Monster_Slime_Blue.png?raw=true" width="500" />
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?

Expand Down
Binary file added assets/demo.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/explanation.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/demo/assets/1945.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions examples/demo/assets/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -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
Loading

0 comments on commit 7b6c5e8

Please sign in to comment.