Giter Club home page Giter Club logo

phaser-spine's Introduction

Phaser Spine

Spine plugin for Phaser, it works, somehow.. No? Submit an issue, otherwise have fun :)

Key features:

  • Spine for Phaser! :o
  • Skin support
  • Possible to combine skins
  • Mixes and fading animations
  • Support for scaled atlases

Spine Version

Please note that the current spine version is an older version, and as a result of that it will work best with Spine version 3.2. There is a newer version of spine available (Spine-ts, up-to-date with latest spine runtime) but work on that is currently halted for this library.

If you feel like helping out, you're welcome to clone the spine-ts branch of this library.

Getting Started

First you want to get a fresh copy of the plugin. You can get it from this repo or from npm, ain't that handy.

npm install @azerion/phaser-spine --save-dev

Next up you'd want to add it to your list of js sources you load into your game

<script src="path/to/phaser-spine.min.js"></script>

After adding the script to the page you can activate it by enabling the plugin:

game.add.plugin(PhaserSpine.SpinePlugin);

Usage

Like any other asset in Phaser, you need to preload the spine object you want in your game. A spine Javascript export will deliver you three files; *.atlas, *.json and *.png. The preloader expects these to be in the same folder, and when so you can just preload the json file by adding the following code to your game:

game.load.spine(
    'buddy',                        //The key used for Phaser's cache
    'assets/buddy_skeleton.json'    //The location of the spine's json file
    );

Now you can just add the spine animation to your game:

buddy = game.add.spine(
    400,        //X positon
    300,        //Y position
    'buddy'     //the key of the object in cache
);

Playing animations

Phaser-spine uses the same API as the original runtime for playing an animation, after adding the spine object to your game, you can call the following function on your object:

buddy.setAnimationByName(
    0,          //Track index
    "idle",     //Animation's name
    true        //If the animation should loop or not
);

Handling events

You can handle Spine events, just add your callback to Spine.onEvent, it's regular Phaser.Signal object. Your callback should be defined with two arguments: event index (number) and event object (Spine.Event):

spineboy.onEvent.add(function (i,e) {
    console.log('name=' + e.data.name + ' int=' + e.intValue + ' float=' + e.floatValue + ' string=' + e.stringValue);
}

Crossfading animations

Stacking animations in spine is rather simple, you just add non-looping animations on top of eachother:

spineboy.setAnimationByName(0, "jump", false);  //We'd like to show this animation once
spineboy.addAnimationByName(0, "walk", true);   //And after the previous animations is finished, we continue with this one

Now this will just simply chain the animation, and it will look a bit akward. Spine solves this by adding mixes that tell spine how to transition nicely from one animation to another. You can set mixes in phaser spine as well by doing the following:

spineboy.setMixByName("walk", "jump", 0.2); //transition from walk to jump and fade/blend it over a period of 0.2 seconds
spineboy.setMixByName("jump", "walk", 0.4); //transition from jump to walk and fade/blend it over a period of 0.4 seconds

Switching skins

Another great additions to spine is the support of skins and the ability to freely switch between them. Like animations this is simple and we use the same API as the runtime. Don't forget to call setToSetupPose after switching skins to update all attachments correctly.

buddy.setSkinByName('outfit01');
buddy.setToSetupPose();

Combining skins

Now the last final awesome part is that you can also create skins in code yourself by simply grouping other existing skins.

var newSkin = buddy.createCombinedSkin(
    'outfit02',     //The name of the new skin, will be automaticly added to the skeleton data
    'vest',         //One of the skins we want to combine
    'mask'          //The other skin we want to combine
);

//Setting the new skin can be set with:
buddy.setSkin(newSkin);
//Or by referencing the new name
buddy.setSkinByName(outfit02);

//And then we shouldn't forget to setToSetupPose ;)
buddy.setToSetupPose();

Scaled atlases

In Spine it's possible to define different scales for your export atlases, including a special suffix that will be suffixed to each atlas name. By default this plugin assumes that no scale is configured, ergo everything is set with scale=1. If you export your atlases to a smaller scale, than this will only happen to the images, the original bone structure will still be defined at the original size you defined in your spine project.

If the exported image is scaled up (or down), than this has to be inverted by the runtime in order to have the correct size of the images for the attachments. In order to do do this correctly, the suffix for a scale any other than 1 has to be set. By default this plugin parses the suffix with a regular expression that looks for numbers start with @ and ending by x. So an atlas file with a scale of 0.5 should have a suffix of @0.5x and the resultion file name would be [email protected].

If you'd like a different setup you can do so by supplying a new RegExp object to the follow property:

PhaserSpine.SpinePlugin.RESOLUTION_REGEXP = /#(.+)r/;

Now the Spine plugin will look for suffixes that look like: #0.5r

The next step is to tell the preloader which scaling variants are available for loading, by adding them as an array in the 3rd optional parameter:

game.load.spine('shooter', "shooter.json", ['@0.7x', '@0.5x']);

The preloader will load 1 json (with all the skeleton/animation data), and 2 images and 2 atlas files.

Later in your game, when you create a new spine object, you again need to add the scaling variant you would like to have for your game. This way you can conditionally load different assets. If you pass no scaling variant to the object, it will just get the first variant from the array supplied when you preload the spine object.

shooter = game.add.spine(400, 300, "shooter", '@0.7x');
//the above is equal to:
shooter = game.add.spine(400, 300, "shooter");
//because @0.7x is the first element of the array supplied to the preloader

Todo

  • adding a body for physics
  • Handling input

Credits

Credit due, where credit's due as my mom always said. This version of phaser-spine is based on the original work by Studio krok's PhaserSpine

Disclaimer

We at Azerion just love playing and creating awesome games. We aren't affiliated with Phaser.io and/or esotericsoftware. We just needed some awesome spine animations in our awesome HTML5 games. Feel free to use it for enhancing your own awesome games!

Phaser Spine is distributed under the MIT license. All 3rd party libraries and components are distributed under their respective license terms.

phaser-spine's People

Contributors

alebles avatar fgssledz avatar florisdh avatar trachukov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phaser-spine's Issues

problems about change part of slot attachment without use skins .

I have a texture atlas made with texture packer.I want change part of slot with a image in texture packer atlas, i made the code below, but the image is invisible .

does phaser-spine can do this?

     var _outro = game.add.spine(400,400,"duck");
      var slot = _outro.skeleton.findSlot("bonus_duck");
      var image = new Phaser.Sprite(game, 0, 0, "texture_packer_atlas", "duckHunt_logo");
      image.anchor.setTo(0.5);

      var attachment = slot.attachment;
      attachment.rendererObject.texture = image;
      // slot.currentSprite.texture = image;

      _outro.setAnimationByName(1, "showing", false);
      _outro.setToSetupPose();

thanks.

How I can change the skin only of one slot?

for example I can the character with different weapons, how I can change the slot "gun"?

I tried this:
hero.skeleton.setAttachment("weapon", "weapon2");

but this slot auto back to 'weapon1' after the animation is completed.

Switching facial features programmatically?

I'm thinking of using Spine's bones to position and switch out pre-made facial parts:

  • Left eyebrow
  • Right eyebrow
  • Left eye
  • Right eye
  • Nose
  • Mouth

How should I go about it here? Do I use skins, or is there a way to set attachments? And since this is the face we're talking about, what if I want to programmatically switch out my faces during playback of different animations?

Great initiative

Hi, I'm currently trying to do some games on phaser and I buy Spine for the animations, is your phaser-spine pluggin is up to date ? Do you have some documentations ?

Thank you !

setSkinByName not updating skin.

Hey dudes. Firstly, thanks for the plugin. Super awesome and massively useful for our work.

I am trying to update skins on the fly using setSkinByName(), which works fine on create, but won't work during update - or at least the visible skin isn't changing.

Is this expected? Am I missing something simple?

Document version of spine

Hey,

It would probably be helpful if the repo mentioned what version of spine it supported. Somewhere in the readme, so it can be noticed at a glance.

Thanks :)

Bounding Box attachment types do not store vertices

We noticed this when replacing our Spine plugin.

The vertices member of BoundingBoxAttachment is a Float32Array, which is a fixed-length data type. As such, when you push the vertices in during readAttachment(), none of the data actually gets stored.

As a temporary fix, we've hacked the readAttachment() method to look like this:

        case spine.AttachmentType.boundingbox:
            var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name);
            var vertices = map["vertices"];
            attachment.vertices = new spine.Float32Array(vertices.length);
            for (var i = 0, n = vertices.length; i < n; i++){
                attachment.vertices[i] = vertices[i] * scale;
            }
            return attachment;

Draw order problem with mixes

Hi, first of all thanks a lot for all the work put into this plugin, works like a charm and it's great to test some spine animations on Phaser.

I came across a strange problem related to animation mix and drawing order.
If I try to mix 2 animations where the draw order of the bones change, sometimes they don't go back to the correct order.

For ex: I have an animation where the character arm moves behind it's body and I try to mix with an animation that pushes the arms to the front of the body, if I change back and forth between this 2 animations, the arms will stay locked either behind or in front of the body.

Webpack - anyone have a working example?

Hi,

Trying to import the phaser-spine.js via webpack using either import (es2015) or require but I can't get anything to work.

I thought I may have to use the expose-loader as I think its a global variable PhaserSpine but still no avail.

Anyone help ?

Mesh Deformation Supported?

Yeah, I've been wondering about this. Does Phaser-Spine (even the non Spine-TS version) with WebGL support this? I tried to get it to work before, but without much luck.

Problem with Local Nonuniform Scaling?

Yeah, I'm using the latest Spine ESS right now (3.4.0.2). I can see nested scales on bones transforming properly on the editor, but I noticed that it doesn't work in the current runtime. Is this because of the old runtime?

Graphics exchange

I would be fine if i could change the graphics instead of the skins to reduce the size of my project.

Scale the timeline of an animation

Is there a way to adjust the speed of an entire animation? For example, if I wanted an animation to animate at half speed, or double speed.

Something to the effect of, mySpine.currentAnimation.timeScale = .5;

Thanks!

Phaser Group support?

Hi!

Just wondering if we can use Phaser's groups to organize where the spine animation will appear in our games? (Using groups to organize Z-layer of the different aspect of the game like the BG, stage, player, GUI, etc...)

I can see that this extends Phaser.Group. What if we already have our groups defined ahead of time, how do we make sure that our Spine animations are running on the group 'layer' we want?

For example: If I have 3 layer groups: BG, LEVEL, and UI, and I initialize them at the start of the game. How do I add Spine objects later on so that they're in between LEVEL and UI?

UI
    <---- Want to insert the Spine animation here
LEVEL
BG

Examples fail with latest phaser

Phaser v2.4.3 | Pixi.js v2.2.8 | WebGL | WebAudio

All the examples - index.html, goblins.html fail with the following:

phaser.min.js:8 Uncaught TypeError: Cannot read property '0' of undefined
at b.WebGLBlendModeManager.setBlendMode (phaser.min.js:8)
at b.WebGLSpriteBatch.flush (phaser.min.js:8)
at b.WebGLSpriteBatch.end (phaser.min.js:8)
at b.WebGLRenderer.renderDisplayObject (phaser.min.js:8)
at b.WebGLRenderer.render (phaser.min.js:8)
at c.Game.updateRender (phaser.min.js:13)
at c.Game.update (phaser.min.js:13)
at c.RequestAnimationFrame.updateRAF (phaser.min.js:18)
at window.requestAnimationFrame.forceSetTimeOut._onLoop (phaser.min.js:18)

phaser-spine Typescript example

I'm having an issue trying to get phaser-spine working with Typescript, is there any chance you could add an example on how this is done.

Thanks.

Phaser CE 2.7.2

I tried to update this to use the latest Phaser CE 2.7.2 which allows for rotated sprites and other features, but there's a lot of Pixi functionality has been removed and merged which breaks it unfortunately.

e.g. "PIXI.Rope and PIXI.Strip have been removed, and all functionality merged in to Phaser.Rope, to cut down on the number of internal classes and inheritance going on."

Spine-TS 3.4 Runtimes for Phaser 2.x or 3?

Hi!

Yeah, seems like Phaser 3's going to come out, and there's a bunch of API incompatibilities if we're on Phaser 2.x. Are you planning on making Spine-TS plugin compatible for 2.x, 3, or both?

setToSetupPose Not Working?

Yeah I think this is broken. If I do a .setToSetupPose to see what it is, it returns a function, but trying to run it doesn't return my spine animation back to the setup pose. Is there a work around for this?

Issue with flipping images?

atami_spine_correct
atami_spine_default
atami_spine_issue

Hi there! First off, thanks for putting this together, it's a huge help.

We're experiencing an issue though, as displayed by the images. One shows the correct behaviour in Unity, one shows the neutral state, and one shows the problem behaviour in Phaser. We're flipping some assets during animations across a single axis, but in Phaser it appears to be flipping it along both axis. In this pose, the hand is flipped away from the character, but this results in the hand asset being turned upside down as well.

Any insight would be a tremendous help. We're also seeing an issue with issues of transparency not blending. Is there a way to change the blend mode to additive? PIXI has a blendMode that can be changed but it doesn't appear to be working when applied to my Spine object in Phaser.

Thanks,
JPK

Error when replacing old phaser-spine.js with Spine-TS branch's.

Looks like I'm getting the error below. I'm using Phaser 2.7.3 CE and I just replaced the phaser-spine.js from the master branch to the one found in spine-ts branch. On canvas mode. I'm not sure what to make of this.

image

Here's the code when you click on where the error is

SpinePlugin.init (phaser-spine.js:5541)

image

I have the plugin added with this line:

this.Spine = this.game.add.plugin(PhaserSpine.SpinePlugin);

in my preloader.js' preload: {} section.

Reusing spine atlas frames

Hi!

Is there any way to use spine atlas frames as Phaser images? I know there's atlas image loaded into cache and I can use it but it doesn't contain any frames.

Don't really get how the scaling works

Hi everyone!

I'm having an issue with the scaling here : I think I'm following the doc carefully but the result is not what I expected.

Here is my code :

// In the preload() method
this.game.load.spine('char', "img/char.json", ["@0.25x"]);

// In the create() method
let char = this.game.add.spine(400, 800, "char");
char.setAnimationByName(0, "idle", false);

I have 3 files :

As you might have guessed, I animated images 4 times too big in spine (just not to get blind, because original char is small), then exported the output 4 times smaller.

So I was expecting the plugin to understand that and make my char 4 times smaller ingame, but on the contrary it puts the char back to its 4-times-too-big size : it's really big and blurry (because images were shrunk 4 times, thus scaling them up by 4 makes them super blurry).
Simply put, instead of understanding that char has been reduced by 4, the plugin tries to get it back to its original size.

Is that the correct behaviour? How could I accomplish my feature (that is, animating big sprites in Spine and exporting them to a smaller, final scale?).

Thanks a lot guys!

[SOLVED]there maybe a bug about setAnimationByName()

I have 5 animations made with spine 3.x . when i use setAniamtion() to change animation ,it doesnt work.
if i invoke setMixByName(a,b) and a and b can change,but others still cannot change.

hope to replay. thks man.

please watch the demo here ,click to change animaitons.

repo is here

post:
I am not sure , there minght be some different about spine2.x and 3.x at animations section in json files.

Equivalent of triangleRendering ? For mesh ?

Hi,

I have downloaded the example project and got them working. I have some spine files that use mesh, currently it rendered with a black background, its as if the background isn't present.

I also downloaded the spine-ts - Html 5 canvas and tried my file, I got the same problem, but setting the triangleRendering to true, forced my spine render to display perfectly.

So i was wondering if there is something similar that exists in orange -phaser - spine.

I must admit my knowledge of spine is limited, although setting the triangleRendering to true renders the spine file inside the html 5 canvas.

Any help really appreciated

Thanks

Phaser Spine and Phaser 2.6.2/2.7.3 Loading Bug

Hey guys,

This isn't an issue, but just something I thought I'd let you guys know about. If you're using an older version of Phaser Spine (Still using the Fabrique class name, version available around Oct 30, 2016), and Phaser 2.6.2, there's a loading bug that occurs when you've created a save game system and you keep loading a save game that has commands that reloads the stage and add spine objects.

The error is quite random, but the more spine objects you load in, the higher the chances of this happening. It'll throw out a type error about the Canvas2D renderer unable to load a graphic or something because it's not an image.

I'm testing out the latest Phaser Spine with Phaser CE 2.7.3 and so far no problems!

EDIT: Ok, seems like the problem's still around.

See attached to see messages when Phaser is set to Canvas and WebGL modes:

image

image

Here's some things I've figured out so far:

It seems to occur when I've a save game down the line of my scripts. The game relies on custom script files being parsed line-by-line. Loading a game with a marker in the middle of the script with a couple of these spine characters being loaded and faded in seems to trigger the problem.

Multi Page Textures Broken

I just noticed this now while I was trying to export a spine project that needed to use multi-page textures since mine won't fit on a single 1024 x 1024 image. So when I exported with multi-page textures, the spine character appears screwed up when it shows up in the Phaser game. If the spine character uses a single-page texture, it appears fine.

Ok, multi page texture images don't seem to be read properly (I only see the first image loaded), and they're not positioned, rotated, etc.. properly.

I tested the sample export files with the newest spine-ts runtime example (canvas mode) code just to see if it looks fine, and it does.

Problem appears in both Canvas or WebGL mode.

Upgrade version of spine

Support for the latest version of spine would really help my team out. If there's any low hanging fruit you're aware of, please let us know. With some direction we might be able to take on some of what's needed to support the latest spine.

The first issue we noticed was no support for the attachment type: path. The error messages generated from trying to load this unsupported attachment type could also be a bit better.

Let me know how I can help!

Thanks

[SOLVED] Distorted / misplaced slot attachments with .json export Spine version 3.3

Hi,

thanks you for your plugin.

I tested it with a Spine 2.x project and Phaser and everything worked fine.
Unfortunately we "merged" all of our animations to Spine 3.3
and now the skeleton character attachments (maybe even the bones) are displaced / distorted / shown with an offset:
spine3-3_dislocated_slotimages

Red rectangles are the imported spine character attachments
and in the green rectangle is the correct placed character, as it should be.

Skeleton character animation is called as written in your documentation with:

elephant.setAnimationByName(0, "idle", true);

Any idea, why this is happening?

Nobody else seem to have this problem.
It is a single sprite sheet atlas.
Strange to me, as it was working before and we are not using shear animations or other "fancy" stuff.

Thanks,
Linda

Reset state with new animation

Hi everyone,

I'm having an issue and I think it's because I'm using the lib poorly. I need your help!

When I play an animation, and interrupt it for another animation, weird things happen. Z-order of sprites is sometimes messed up, or data from previous animation is kept. I haven't found a way to "clear" previous animation and start the new one on a clean slate.

For example, I used the spineboy example, which I slightly modified as is :

   function create() {
        //create the spine object
        spineboy = game.add.spine(200, 400, "spineboy");

        // Add animations
        spineboy.addAnimationByName(0, "walk", true);
        spineboy.addAnimationByName(0, "jump", true);

        // Play walk by default
        spineboy.setAnimationByName(0, "walk", true);

        let anim = 1;
        game.input.onDown.add(function(){
          if(anim === 1){
            spineboy.setAnimationByName(0, "jump", true);
            anim = 2;
          }else{
            spineboy.setAnimationByName(0, "walk", true);
            anim = 1;
          }
        });
    }

If you use this code and click once, the spineboy will play the jump indefinitely. And if you click a second time it will go back to the walk animation. But the strange thing is, that it will keep any angle it previously had from the jump animation! For example, if you let the boy crouch (before the jump), and then click again, then he will walk but with the same angle he had while crouching!

How could I properly reset all animation data to the walk animation, not inheriting undesired properties from the jump animation?

Thanks a lot guys!

Scaling Down Bones and Assets

Hey guys,

This is a tip. In case you've got a huge animation and assets and have issues scaling it down because it's too slow on Phaser, here's what worked for me:

Let's say you need to scale it down to 60% or 0.6 from 100%.

  1. On your original PSD file, resize image to 60%.
  2. Export to Spine-ready PNGs using the Extend Toolkit Script
  3. Export your JSON (100% size).
  4. Now that you've got a smaller set of assets in its own directory, it's time to deal with the bone. In the Spine Editor, do [IMPORT DATA] and import the JSON file from step 3.
  5. Select your .spine file. Under scale, select 0.6 or 60% to match our asset size.
  6. Once it's in, under [IMAGES], select the directory where your smaller exported images are from Step 2.
  7. Go to the root, you'll see X and Y scales are set to 0.6. Set these to 1.0 and 1.0.
  8. Done! You should now have a skeleton with animations that fit your new image assets.

Support for shearing?

http://fr.esotericsoftware.com/blog#Shearing

Hi guys!

First, I wanted to tell you guys how freaking awesome this plugin is! Spine is just amazing, it's gonna save us megas of spritesheets data, for much better animations.. And for almost no performance cost!

This plugin rocks.

That said, do you guys plan on adding any new feature, like shearing? Is there any way of "warping" shapes (like distortion?). This helps giving a lot more natural organic feel to the characters.

Thanks a lot!

Dont start example :(

In console.log write this:

Uncaught ReferenceError: Fabrique is not defined
    at Object.preload (spineboy.html:28)
    at Phaser.StateManager.preUpdate (phaser.js:29844)
    at Phaser.Game.updateLogic (phaser.js:36333)
    at Phaser.Game.update (phaser.js:36226)
    at Phaser.RequestAnimationFrame.updateRAF (phaser.js:61979)
    at _onLoop (phaser.js:61962)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.