sprite

package module
v0.0.0-...-68cf2a7 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2023 License: MIT Imports: 12 Imported by: 0

README

goaseprite

pkg.go.dev link

Goaseprite is a JSON loader for Aseprite files for Golang.

How To Use

Usage is pretty straightforward. You export a sprite sheet and its corresponding JSON data file from Aseprite (Ctrl+E). The values should be set to Hash with Frame Tags and Slices (optionally) on.

Then you'll want to load the Aseprite data. To do this, you'll call goaseprite.Open() with a string argument of where to find the Aseprite JSON data file, or manually pass the bytes to goaseprite.Read(). From this, you'll get a *goaseprite.File, which represents an Aseprite file. It's from here that you control your animation.

You can call File.Play() to play a tag / animation, and use the File.Update() function with an argument of delta time (the time between the previous frame and the current one) to update the animation. Call File.CurrentFrame() to get the current frame, which gives you the X and Y position of the current frame on the sprite sheet. Assuming a tag with a blank name ("") doesn't exist in your Aseprite file, goaseprite will create a default animation with that name, allowing you to easily play all of the frames in sequence.

Here'a quick example, using ebiten for rendering:

package main

import (
	"image"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
	"github.com/solarlune/goaseprite"

	_ "image/png"
)

type Game struct {
	Sprite *goaseprite.File
	Player *goaseprite.Player
	Img    *ebiten.Image
}

func NewGame() *Game {

	game := &Game{
		Sprite: goaseprite.Open("16x16Deliveryman.json"),
	}
	game.Player = goaseprite.NewPlayer(game.Sprite)

	img, _, err := ebitenutil.NewImageFromFile(game.Sprite.ImagePath)
	if err != nil {
		panic(err)
	}

    game.Sprite.Play("walk")

	game.Img = img

	return game

}

func (game *Game) Update() error {

	game.Sprite.Update(float32(1.0 / 60.0))

	return nil
}

func (game *Game) Draw(screen *ebiten.Image) {

	opts := &ebiten.DrawImageOptions{}

	sub := game.Img.SubImage(image.Rect(game.Sprite.CurrentFrameCoords()))

	screen.DrawImage(sub.(*ebiten.Image), opts)

}

func (game *Game) Layout(w, h int) (int, int) { return 320, 180 }

func main() {

	ebiten.RunGame(NewGame())

}


You also have the ability to use File.OnLoop, File.OnFrameChange, File.OnTagEnter, and File.OnTagExit callbacks to trigger events when an animation's state changes, for example. That's roughly it!

Additional Notes

As for dependencies, GoAseprite makes use of tidwall's nice gjson package.

Documentation

Overview

Package sprite is an Aseprite JSON loader written in Golang.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoTagByName = errors.New("no tags by name")
)

Functions

This section is empty.

Types

type Direction

type Direction string
const (
	// PlayForward plays animations forward
	PlayForward Direction = "forward"
	// PlayBackward plays animations backwards
	PlayBackward Direction = "reverse"
	// PlayPingPong plays animation forward then backward
	PlayPingPong Direction = "pingpong"
)

type File

type File struct {
	Path                    string          // Path to the file (exampleSprite.json); blank if the *File was loaded using Read().
	ImagePath               string          // Path to the image associated with the Aseprite file (exampleSprite.png).
	Width, Height           int32           // Overall width and height of the File.
	FrameWidth, FrameHeight int32           // Width and height of the frames in the File.
	Frames                  []Frame         // The animation Frames present in the File.
	Tags                    map[string]*Tag // A map of Tags, with their names being the keys.
	Layers                  []Layer         // A slice of Layers.
	Slices                  []Slice         // A slice of the Slices present in the file.
}

File contains all properties of an exported aseprite file. ImagePath is the absolute path to the image as reported by the exported Aseprite JSON data. Path is the string used to open the File if it was opened with the Open() function; otherwise, it's blank.

func OpenAseprite

func OpenAseprite(jsonPath string) (*File, error)

OpenAseprite will use os.ReadFile() to open the Aseprite JSON file path specified to parse the data. Returns a *goaseprite.File. This can be your starting point. Files created with Open() will put the JSON filepath used in the Path field.

func OpenSpritesheet

func OpenSpritesheet(filename string, duration float32) (*File, error)

func ReadAseprite

func ReadAseprite(data []byte) (*File, error)

ReadAseprite returns a *goaseprite.File for a given sequence of bytes read from an Aseprite JSON file.

func ReadSpritesheet

func ReadSpritesheet(r io.Reader, filename string, duration float32) (*File, error)

func (*File) CreatePlayer

func (f *File) CreatePlayer() *Player

CreatePlayer returns a new animation player that plays animations from a given Aseprite file.

func (*File) CreatePlayerWithImage

func (f *File) CreatePlayerWithImage(img *ebiten.Image) *Player

func (*File) HasSlice

func (f *File) HasSlice(sliceName string) bool

HasSlice returns true if the File has a Slice of the specified name.

func (*File) SliceByName

func (f *File) SliceByName(sliceName string) (Slice, bool)

SliceByName returns a Slice that has the name specified and a boolean indicating whether it could be found or not. Note that a File can have multiple Slices by the same name.

type Frame

type Frame struct {
	X, Y     int
	Duration float32 // The duration of the frame in seconds.
}

Frame contains timing and position information for the frame on the spritesheet.

type Layer

type Layer struct {
	Name      string
	Opacity   uint8
	BlendMode string
}

Layer contains details regarding the layers exported from Aseprite, including the layer's name (string), opacity (0-255), and blend mode (string).

type Player

type Player struct {
	File           *File
	PlaySpeed      float32 // The playback speed; altering this can be used to globally slow down or speed up animation playback.
	CurrentTag     *Tag    // The currently playing animation.
	FrameIndex     int     // The current frame of the File's animation / tag playback.
	PrevFrameIndex int     // The previous frame in the playback.

	// OnLoop gets called when the playing animation / tag does a complete loop. For a ping-pong
	// animation, this is a full forward + back cycle.
	OnLoop func(p *Player)
	// OnFrameChange gets called when the playing animation / tag changes frames.
	OnFrameChange func(p *Player, frame int)
	// OnTagEnter gets called when entering a tag from "outside" of it (i.e. if not playing a
	//tag and then it gets played, this gets called, or if you're playing a tag and you pass
	// through another tag).
	OnTagEnter func(p *Player, t *Tag)
	OnTagExit  func(p *Player, t *Tag)

	// OnDraw callbacl called just before drawing the sprite, if return false the draw is aborted.
	OnDraw func(p *Player, screen, img *ebiten.Image, opts *ebiten.DrawImageOptions) bool
	// contains filtered or unexported fields
}

Player is an animation player for Aseprite files.

func (*Player) Clone

func (p *Player) Clone() *Player

Clone clones the Player.

func (*Player) CurrentFrame

func (p *Player) CurrentFrame() (Frame, bool)

CurrentFrame returns the current frame for the currently playing Tag in the File and a boolean indicating if the Player is playing a Tag or not.

func (*Player) CurrentFrameCoords

func (p *Player) CurrentFrameCoords() (int, int, int, int)

CurrentFrameCoords returns the four corners of the current frame, of format (x1, y1, x2, y2). If File.CurrentFrame() is nil, it will instead return all -1's.

func (*Player) CurrentUVCoords

func (p *Player) CurrentUVCoords() (float64, float64)

CurrentUVCoords returns the top-left corner of the current frame, of format (x, y). If File.CurrentFrame() is nil, it will instead return (-1, -1).

func (*Player) CurrentUVCoordsDelta

func (p *Player) CurrentUVCoordsDelta() (float64, float64)

CurrentUVCoordsDelta returns the current UV Coords as a coordinate movement delta. For example, if an animation were to return the X-axis UV coordinates of : [ 0, 0, 0, 0, 0.5, 0.5, 0.5, 0.5 ], CurrentUVCoordsDelta would return [ 0, 0, 0, 0, 0.5, 0, 0, 0 ], as the UV coordinate only changes on that one frame in the middle, from 0 to 0.5. Once it goes to the end, it would return -0.5 to return back to the starting frame.

func (*Player) Draw

func (p *Player) Draw(screen *ebiten.Image) error

func (*Player) FrameIndexInAnimation

func (p *Player) FrameIndexInAnimation() int

FrameIndexInAnimation returns the currently visible frame index, using the playing animation as the range. This means that a FrameIndexInAnimation of 0 would be the first frame in the currently playing animation, regardless of what frame in the sprite strip that is). If no animation is being played, this function will return -1.

func (*Player) Play

func (p *Player) Play(tagName string) error

Play sets the specified tag name up to be played back. A tagName of "" will play back the entire file.

func (*Player) SetFrameIndex

func (p *Player) SetFrameIndex(frameIndex int)

SetFrameIndex sets the currently visible frame to frameIndex, using the playing animation as the range. This means calling SetFrameIndex with a frameIndex of 2 would set it to the third frame of the animation that is currently playing.

func (*Player) TouchingTagByName

func (p *Player) TouchingTagByName(tagName string) bool

TouchingTagByName returns if a tag by the given name is being touched by the Player (tag).

func (*Player) TouchingTags

func (p *Player) TouchingTags() []*Tag

TouchingTags returns the tags currently being touched by the Player (tag).

func (*Player) Update

func (p *Player) Update(dt float32)

Update updates the currently playing animation. dt is the delta value between the previous frame and the current frame.

type Slice

type Slice struct {
	Name  string     // Name is the name of the Slice, as specified in Aseprite.
	Data  string     // Data is blank by default, but can be specified on export from Aseprite to be whatever you need it to be.
	Keys  []SliceKey // The individual keys (positions and sizes of Slices) according to the Frames they operate on.
	Color int64
}

Slice represents a Slice (rectangle) that was defined in Aseprite and exported in the JSON file.

type SliceKey

type SliceKey struct {
	Frame      int32
	X, Y, W, H int
}

SliceKey represents a Slice's size and position in the Aseprite file on a specific frame. An individual Aseprite File can have multiple Slices inside, which can also have multiple frames in which the Slice's position and size changes. The SliceKey's Frame indicates which frame the key is operating on.

func (SliceKey) Center

func (k SliceKey) Center() (int, int)

Center returns the center X and Y position of the Slice in the current key.

type Tag

type Tag struct {
	Name       string
	Start, End int
	Direction  Direction
	File       *File
}

Tag contains details regarding each tag or animation from Aseprite. Start and End are the starting and ending frame of the Tag. Direction is a string, and can be assigned one of the playback constants.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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