Latest commit

History

16 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Charm - Tweening for Pixi (v3.0.11)

Charm is an easy to use tweening library for the Pixi 2D rendering engine.

(Important! this library targets Pixi v3.0.11, which is the most stable version of Pixi, and is the only version I can recommend using. This library will eventually be upgraded for Pixi v4 when the v4 branch matures.)

Table of contents

Setting up
Sliding tweens
Tween objects
Setting the easing type
Following curves
Following paths
Following connected curves
Fade-out and fade-in
Pulse
Scale
Breathe
Strobe
Wobble
Make your own custom tweens

Setting up and running Charm

To start using Charm, link to the charm.js file in your HTML document with a <script> tag. Next, create a new instance of Charm at the beginning of your program, and initialize it using the PIXI object in the constructor, like this:

c=newCharm(PIXI);

Charm needs to be updated each frame in your application's game loop. Call charm's update method in the game loop. Here's an example of a simple game loop that updates Charm:

functiongameLoop(){//Create the looprequestAnimationFrame(gameLoop);//Update charmc.update();//Optionally, you probably also need to render Pixi's root//container. If your root container is called `stage` you could//update it like this://PIXI.renderer.render(stage);}

Now you're ready to start tweening!

Let's learn how to use Charm by looking in-depth at one its most useful methods: slide.

Sliding tweens

Use Charm's slide method to make a sprite move smoothly from its current position on the canvas, to any other position. The slide method takes 7 arguments (but only the first 3 are required):

slide(anySprite,//A spritefinalXPosition,//The x position where the movement should endfinalYPosition,//The y position where the movement should enddurationInFrames,//How long the movement should last, in frameseasingType,//The easing style of the movementyoyo?,//A Boolean. Should the sprite yoyo?delayTimeBeforeRepeat//Delay time, in ms, before the sprite yoyos.)

durationInFrames determines the number of frames over which the tween should occur (the default is 60.) The easingType is a string which can be any of 15 different types, which you'll find listed ahead (the default is "smoothstep".) yoyo is a Boolean which determines whether the sprite should move back and forth, continuously between the tween's start and end points. delayTimeBeforeRepeat is a number, in milliseconds, that determines the amount of optional delay between before the sprite yoyos back.

Here's how you could use the slide method to make a sprite move from its original position to x/y point 128/128 over 120 frames:

c.slide(anySprite,128,128,120);

That's the only line of code you need to write – Charm's engine animates the sprite automatically for you. Here's the effect it produces:

Slide tween

If you want the sprite to yoyo back and forth between its start and end points, here's some code you could write:

c.slide(pixie,128,128,120,"smoothstep",true);

(true turns the yoyo effect on.)

Tween objects

All of Charm's tween methods return a tween object, that you can create like this:

letslideTween=c.slide(anySprite,128,128,120);

slideTween is the tween object in this example, and it contains some useful properties and methods that let you control the tween. One of these is a user-assignable onComplete method that will run as soon as the tween is finished. Here's how you could use onComplete to display a message in the console when the sprite has reached its destination.

letslideTween=c.slide(anySprite,128,128,120);slideTween.onComplete=()=>console.log("slide completed");

If you set yoyo to true, onComplete will run whenever the sprite reaches both its start and end points, continuously.

Tweens also have pause and play methods that let you stop and start the tween.

slideTween.pause();
slideTween.play();

Tween objects have a playing property that will be true if the tween is currently playing. All Charm's methods return tween objects that you can control and access like this.

Setting the easing types

The slide method's fourth argument is the easingType. It's a string that determines how quickly or slowly the tween speeds up and slows down. There are 15 of these types to choose from, and they're the same for all of Charm's different tween methods. The easing types fall in to 5 general categories, so you can pick one by first choosing the general category, and then the more specific type. Each category has a basic type, and then a squared and cubed version. The squared and cubed versions just exaggerate the basic effect to further degrees. The default easing type for most of Charm's tweens is "smoothstep".

  • Linear: "linear". No easing on the sprite at all; the sprite just starts and stops abruptly.
  • Smoothstep: "smoothstep", "smoothstepSquared", "smoothstepCubed". Speeds the sprite up and slows it down in a very natural looking way.
  • Acceleration: "acceleration", "accelerationCubed". Gradually speeds the sprite up and stops it abruptly. For a slightly more rounded acceleration effect, use "sine", "sineSquared", "sineCubed",
  • Deceleration: "deceleration", "decelerationCubed". Starts the sprite abruptly and gradually slows it down. For a slightly more rounded deceleration effect, use "inverseSine", "inverseSineSquared", "inverseSineCubed"
  • Bounce: "bounce 10 -10". This will make the sprite overshoot the start and end points and bounce slightly when it hits them. Try changing the multipliers, 10 and -10, to vary the effect.

Use any of these easing types in Charm's tween methods in the examples that follow.

Following curves

The slide method animates a sprite along a straight line, but you can use another method called followCurve to make a sprite move along a Bezier curve.

Follow a curve

First, define the Bezier curve as a 2D array of 4 x/y points, like this:

letcurve=[[anySprite.x,anySprite.y],//Start position[108,32],//Control point 1[176,32],//Control point 2[196,160]//End position];

The second and third set of points are the Bezier curve's control points.

Next, use Charm's followCurve method to make a sprite follow that curve. (Supply the curve array as the second argument.)

c.followCurve(anySprite,//The spritecurve,//The Bezier curve array120,//Duration, in milliseconds"smoothstep",//Easing typetrue,//Should the tween yoyo?1000//Delay, in milliseconds, before it yoyos);

Only the first two arguments are required.

You'll have the best result if you center the sprite over the curve. You can do that by centering the sprite's anchor point, like this:

anySprite.anchor.set(0.5,0.5);

The slide and followCurve methods are good for simple back and forth animation effects, but you can also connect them together to make sprites traverse complex paths.

Following paths

You can use Charm's walkPath method to connect a series of points together and make a sprite move to each of those points. Each point in the series is called a waypoint. First, start with a 2D array of x/y position waypoints that map out the path you want the sprite to follow.

letwaypoints=[[32,32],//First x/y point[32,128],//Next x/y point[300,128],//Next x/y point[300,32],//Next x/y point[32,32]//Last x/y point];

You can use as many waypoints as you need.

Next, use the walkPath method to make the sprite move to all those points, in sequence. (Only the first two arguments are required.)

c.walkPath(anySprite,//The spritewaypoints,//The array of waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path reverse?1000//Delay in milliseconds between segments);

If you set the 5th argument to true, the sprite will start again from the beginning when it reaches the end. If you set the 6th argument to true, the sprite will walk the path in reverse when it reaches the end. The last argument sets the delay, in milliseconds, that the sprite should wait before moving to the next section of the path.

Here's the effect of this code:

Following paths

Following connected curves

You can make a sprite follow a series of connected curves with the walkCurve method. First, create any array of Bezier curves that describe the path you want the sprite to follow.

letcurvedWaypoints=[//First curve[[anySprite.x,anySprite.y],[75,500],[200,500],[300,300]],//Second curve[[300,300],[250,100],[100,100],[anySprite.x,anySprite.y]]];

The four points for each curve are the same as in the followCurve method: the start position, control point 1, control point 2, and the end position. The last point in the first curve should be the same as the first point in the next curve. You can use as many curves as you need.

Next, supply the curvedWapoints array as the second argument in the walkCurve method:

letspritePath=c.walkCurve(anySprite,//The spritecurvedWaypoints,//Array of curved waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path yoyo?1000//Delay in milliseconds between segments);

Here's the effect of this code:

Following paths

Using walkPath and walkCurve will give you a great head start for making some fun animated sprites for games.

Charm has bunch of other built-in, tween effects that you'll find a lot of use for in games and applications. Here's a quick round-up:

Fade-out and fade-in

Use fadeOut to make a sprite become gradually transparent, and fadeIn to make it re-appear. Here's their most basic usage:

c.fadeOut(anySprite);c.fadeIn(anySprite);

The optional second argument is the duration, in frames, that the fade should last (the default is 60 frames.)

Pulse

Use pulse to make a sprite fade out and in, continuously, at a steady rate.

c.pulse(anySprite);

The optional second argument is the duration, in frames, between each fade-in and fade-out. An optional 3rd argument lets you set the minimum alpha level that the sprite should be reduced to. For example, if you only want the sprite to become half-transparent before fading in again, set the 3rd argument to 0.5, like this:

c.pulse(anySprite,60,0.5);

Scale

You can tween a sprite's scale with the scale method. Here are the arguments you can use (only the first is required.)

c.scale(anySprite,//The spriteendScaleX,//The final x scale valueendScaleY,//The final y scale valuedurationInframes//The duration, in frames);

Breathe

If you want the scale tween effect to yoyo back and forth, use the breathe method. It's a scaling effect that makes a sprite look as though it's breathing in and out. Here's the full argument list (only the first is required.)

c.breathe(anySprite,//The spriteendScaleX,//The final scale x valueendScaleY,//The final scale y valueframes,//The duration, in framesyoyo,//Should the tween yoyo?delayBeforeRepeat,//Delay, in milliseconds, before yoyoing);

Strobe

Use the strobe method to make a sprite appear to flash like a strobe light by rapidly changing its scale.

c.strobe(sprite);

Wobble

Make a sprite wobble like a plate of jelly using the wobble method:

c.wobble(sprite);

If you use any of these scaling tween effects (scale, breathe, strobe or wobble), center the sprite's anchor point so that the scaling happens from the sprite's center.

Make your own custom tweens

These tweening effects will cover most of your needs for all kinds of games and applications. But, if you need a new effect, try writing your own. Use Charm's existing methods as your template, and if you create something really fun, let us know and we'll add it to the library!

About

No description, website, or topics provided.

Resources

Stars

121 stars

Watchers

7 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

16 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Charm - Tweening for Pixi (v3.0.11)

Charm is an easy to use tweening library for the Pixi 2D rendering engine.

(Important! this library targets Pixi v3.0.11, which is the most stable version of Pixi, and is the only version I can recommend using. This library will eventually be upgraded for Pixi v4 when the v4 branch matures.)

Table of contents

Setting up
Sliding tweens
Tween objects
Setting the easing type
Following curves
Following paths
Following connected curves
Fade-out and fade-in
Pulse
Scale
Breathe
Strobe
Wobble
Make your own custom tweens

Setting up and running Charm

To start using Charm, link to the charm.js file in your HTML document with a <script> tag. Next, create a new instance of Charm at the beginning of your program, and initialize it using the PIXI object in the constructor, like this:

c=newCharm(PIXI);

Charm needs to be updated each frame in your application's game loop. Call charm's update method in the game loop. Here's an example of a simple game loop that updates Charm:

functiongameLoop(){//Create the looprequestAnimationFrame(gameLoop);//Update charmc.update();//Optionally, you probably also need to render Pixi's root//container. If your root container is called `stage` you could//update it like this://PIXI.renderer.render(stage);}

Now you're ready to start tweening!

Let's learn how to use Charm by looking in-depth at one its most useful methods: slide.

Sliding tweens

Use Charm's slide method to make a sprite move smoothly from its current position on the canvas, to any other position. The slide method takes 7 arguments (but only the first 3 are required):

slide(anySprite,//A spritefinalXPosition,//The x position where the movement should endfinalYPosition,//The y position where the movement should enddurationInFrames,//How long the movement should last, in frameseasingType,//The easing style of the movementyoyo?,//A Boolean. Should the sprite yoyo?delayTimeBeforeRepeat//Delay time, in ms, before the sprite yoyos.)

durationInFrames determines the number of frames over which the tween should occur (the default is 60.) The easingType is a string which can be any of 15 different types, which you'll find listed ahead (the default is "smoothstep".) yoyo is a Boolean which determines whether the sprite should move back and forth, continuously between the tween's start and end points. delayTimeBeforeRepeat is a number, in milliseconds, that determines the amount of optional delay between before the sprite yoyos back.

Here's how you could use the slide method to make a sprite move from its original position to x/y point 128/128 over 120 frames:

c.slide(anySprite,128,128,120);

That's the only line of code you need to write – Charm's engine animates the sprite automatically for you. Here's the effect it produces:

Slide tween

If you want the sprite to yoyo back and forth between its start and end points, here's some code you could write:

c.slide(pixie,128,128,120,"smoothstep",true);

(true turns the yoyo effect on.)

Tween objects

All of Charm's tween methods return a tween object, that you can create like this:

letslideTween=c.slide(anySprite,128,128,120);

slideTween is the tween object in this example, and it contains some useful properties and methods that let you control the tween. One of these is a user-assignable onComplete method that will run as soon as the tween is finished. Here's how you could use onComplete to display a message in the console when the sprite has reached its destination.

letslideTween=c.slide(anySprite,128,128,120);slideTween.onComplete=()=>console.log("slide completed");

If you set yoyo to true, onComplete will run whenever the sprite reaches both its start and end points, continuously.

Tweens also have pause and play methods that let you stop and start the tween.

slideTween.pause();
slideTween.play();

Tween objects have a playing property that will be true if the tween is currently playing. All Charm's methods return tween objects that you can control and access like this.

Setting the easing types

The slide method's fourth argument is the easingType. It's a string that determines how quickly or slowly the tween speeds up and slows down. There are 15 of these types to choose from, and they're the same for all of Charm's different tween methods. The easing types fall in to 5 general categories, so you can pick one by first choosing the general category, and then the more specific type. Each category has a basic type, and then a squared and cubed version. The squared and cubed versions just exaggerate the basic effect to further degrees. The default easing type for most of Charm's tweens is "smoothstep".

  • Linear: "linear". No easing on the sprite at all; the sprite just starts and stops abruptly.
  • Smoothstep: "smoothstep", "smoothstepSquared", "smoothstepCubed". Speeds the sprite up and slows it down in a very natural looking way.
  • Acceleration: "acceleration", "accelerationCubed". Gradually speeds the sprite up and stops it abruptly. For a slightly more rounded acceleration effect, use "sine", "sineSquared", "sineCubed",
  • Deceleration: "deceleration", "decelerationCubed". Starts the sprite abruptly and gradually slows it down. For a slightly more rounded deceleration effect, use "inverseSine", "inverseSineSquared", "inverseSineCubed"
  • Bounce: "bounce 10 -10". This will make the sprite overshoot the start and end points and bounce slightly when it hits them. Try changing the multipliers, 10 and -10, to vary the effect.

Use any of these easing types in Charm's tween methods in the examples that follow.

Following curves

The slide method animates a sprite along a straight line, but you can use another method called followCurve to make a sprite move along a Bezier curve.

Follow a curve

First, define the Bezier curve as a 2D array of 4 x/y points, like this:

letcurve=[[anySprite.x,anySprite.y],//Start position[108,32],//Control point 1[176,32],//Control point 2[196,160]//End position];

The second and third set of points are the Bezier curve's control points.

Next, use Charm's followCurve method to make a sprite follow that curve. (Supply the curve array as the second argument.)

c.followCurve(anySprite,//The spritecurve,//The Bezier curve array120,//Duration, in milliseconds"smoothstep",//Easing typetrue,//Should the tween yoyo?1000//Delay, in milliseconds, before it yoyos);

Only the first two arguments are required.

You'll have the best result if you center the sprite over the curve. You can do that by centering the sprite's anchor point, like this:

anySprite.anchor.set(0.5,0.5);

The slide and followCurve methods are good for simple back and forth animation effects, but you can also connect them together to make sprites traverse complex paths.

Following paths

You can use Charm's walkPath method to connect a series of points together and make a sprite move to each of those points. Each point in the series is called a waypoint. First, start with a 2D array of x/y position waypoints that map out the path you want the sprite to follow.

letwaypoints=[[32,32],//First x/y point[32,128],//Next x/y point[300,128],//Next x/y point[300,32],//Next x/y point[32,32]//Last x/y point];

You can use as many waypoints as you need.

Next, use the walkPath method to make the sprite move to all those points, in sequence. (Only the first two arguments are required.)

c.walkPath(anySprite,//The spritewaypoints,//The array of waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path reverse?1000//Delay in milliseconds between segments);

If you set the 5th argument to true, the sprite will start again from the beginning when it reaches the end. If you set the 6th argument to true, the sprite will walk the path in reverse when it reaches the end. The last argument sets the delay, in milliseconds, that the sprite should wait before moving to the next section of the path.

Here's the effect of this code:

Following paths

Following connected curves

You can make a sprite follow a series of connected curves with the walkCurve method. First, create any array of Bezier curves that describe the path you want the sprite to follow.

letcurvedWaypoints=[//First curve[[anySprite.x,anySprite.y],[75,500],[200,500],[300,300]],//Second curve[[300,300],[250,100],[100,100],[anySprite.x,anySprite.y]]];

The four points for each curve are the same as in the followCurve method: the start position, control point 1, control point 2, and the end position. The last point in the first curve should be the same as the first point in the next curve. You can use as many curves as you need.

Next, supply the curvedWapoints array as the second argument in the walkCurve method:

letspritePath=c.walkCurve(anySprite,//The spritecurvedWaypoints,//Array of curved waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path yoyo?1000//Delay in milliseconds between segments);

Here's the effect of this code:

Following paths

Using walkPath and walkCurve will give you a great head start for making some fun animated sprites for games.

Charm has bunch of other built-in, tween effects that you'll find a lot of use for in games and applications. Here's a quick round-up:

Fade-out and fade-in

Use fadeOut to make a sprite become gradually transparent, and fadeIn to make it re-appear. Here's their most basic usage:

c.fadeOut(anySprite);c.fadeIn(anySprite);

The optional second argument is the duration, in frames, that the fade should last (the default is 60 frames.)

Pulse

Use pulse to make a sprite fade out and in, continuously, at a steady rate.

c.pulse(anySprite);

The optional second argument is the duration, in frames, between each fade-in and fade-out. An optional 3rd argument lets you set the minimum alpha level that the sprite should be reduced to. For example, if you only want the sprite to become half-transparent before fading in again, set the 3rd argument to 0.5, like this:

c.pulse(anySprite,60,0.5);

Scale

You can tween a sprite's scale with the scale method. Here are the arguments you can use (only the first is required.)

c.scale(anySprite,//The spriteendScaleX,//The final x scale valueendScaleY,//The final y scale valuedurationInframes//The duration, in frames);

Breathe

If you want the scale tween effect to yoyo back and forth, use the breathe method. It's a scaling effect that makes a sprite look as though it's breathing in and out. Here's the full argument list (only the first is required.)

c.breathe(anySprite,//The spriteendScaleX,//The final scale x valueendScaleY,//The final scale y valueframes,//The duration, in framesyoyo,//Should the tween yoyo?delayBeforeRepeat,//Delay, in milliseconds, before yoyoing);

Strobe

Use the strobe method to make a sprite appear to flash like a strobe light by rapidly changing its scale.

c.strobe(sprite);

Wobble

Make a sprite wobble like a plate of jelly using the wobble method:

c.wobble(sprite);

If you use any of these scaling tween effects (scale, breathe, strobe or wobble), center the sprite's anchor point so that the scaling happens from the sprite's center.

Make your own custom tweens

These tweening effects will cover most of your needs for all kinds of games and applications. But, if you need a new effect, try writing your own. Use Charm's existing methods as your template, and if you create something really fun, let us know and we'll add it to the library!

About

No description, website, or topics provided.

Resources

Stars

121 stars

Watchers

7 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

16 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Charm - Tweening for Pixi (v3.0.11)

Charm is an easy to use tweening library for the Pixi 2D rendering engine.

(Important! this library targets Pixi v3.0.11, which is the most stable version of Pixi, and is the only version I can recommend using. This library will eventually be upgraded for Pixi v4 when the v4 branch matures.)

Table of contents

Setting up
Sliding tweens
Tween objects
Setting the easing type
Following curves
Following paths
Following connected curves
Fade-out and fade-in
Pulse
Scale
Breathe
Strobe
Wobble
Make your own custom tweens

Setting up and running Charm

To start using Charm, link to the charm.js file in your HTML document with a <script> tag. Next, create a new instance of Charm at the beginning of your program, and initialize it using the PIXI object in the constructor, like this:

c=newCharm(PIXI);

Charm needs to be updated each frame in your application's game loop. Call charm's update method in the game loop. Here's an example of a simple game loop that updates Charm:

functiongameLoop(){//Create the looprequestAnimationFrame(gameLoop);//Update charmc.update();//Optionally, you probably also need to render Pixi's root//container. If your root container is called `stage` you could//update it like this://PIXI.renderer.render(stage);}

Now you're ready to start tweening!

Let's learn how to use Charm by looking in-depth at one its most useful methods: slide.

Sliding tweens

Use Charm's slide method to make a sprite move smoothly from its current position on the canvas, to any other position. The slide method takes 7 arguments (but only the first 3 are required):

slide(anySprite,//A spritefinalXPosition,//The x position where the movement should endfinalYPosition,//The y position where the movement should enddurationInFrames,//How long the movement should last, in frameseasingType,//The easing style of the movementyoyo?,//A Boolean. Should the sprite yoyo?delayTimeBeforeRepeat//Delay time, in ms, before the sprite yoyos.)

durationInFrames determines the number of frames over which the tween should occur (the default is 60.) The easingType is a string which can be any of 15 different types, which you'll find listed ahead (the default is "smoothstep".) yoyo is a Boolean which determines whether the sprite should move back and forth, continuously between the tween's start and end points. delayTimeBeforeRepeat is a number, in milliseconds, that determines the amount of optional delay between before the sprite yoyos back.

Here's how you could use the slide method to make a sprite move from its original position to x/y point 128/128 over 120 frames:

c.slide(anySprite,128,128,120);

That's the only line of code you need to write – Charm's engine animates the sprite automatically for you. Here's the effect it produces:

Slide tween

If you want the sprite to yoyo back and forth between its start and end points, here's some code you could write:

c.slide(pixie,128,128,120,"smoothstep",true);

(true turns the yoyo effect on.)

Tween objects

All of Charm's tween methods return a tween object, that you can create like this:

letslideTween=c.slide(anySprite,128,128,120);

slideTween is the tween object in this example, and it contains some useful properties and methods that let you control the tween. One of these is a user-assignable onComplete method that will run as soon as the tween is finished. Here's how you could use onComplete to display a message in the console when the sprite has reached its destination.

letslideTween=c.slide(anySprite,128,128,120);slideTween.onComplete=()=>console.log("slide completed");

If you set yoyo to true, onComplete will run whenever the sprite reaches both its start and end points, continuously.

Tweens also have pause and play methods that let you stop and start the tween.

slideTween.pause();
slideTween.play();

Tween objects have a playing property that will be true if the tween is currently playing. All Charm's methods return tween objects that you can control and access like this.

Setting the easing types

The slide method's fourth argument is the easingType. It's a string that determines how quickly or slowly the tween speeds up and slows down. There are 15 of these types to choose from, and they're the same for all of Charm's different tween methods. The easing types fall in to 5 general categories, so you can pick one by first choosing the general category, and then the more specific type. Each category has a basic type, and then a squared and cubed version. The squared and cubed versions just exaggerate the basic effect to further degrees. The default easing type for most of Charm's tweens is "smoothstep".

  • Linear: "linear". No easing on the sprite at all; the sprite just starts and stops abruptly.
  • Smoothstep: "smoothstep", "smoothstepSquared", "smoothstepCubed". Speeds the sprite up and slows it down in a very natural looking way.
  • Acceleration: "acceleration", "accelerationCubed". Gradually speeds the sprite up and stops it abruptly. For a slightly more rounded acceleration effect, use "sine", "sineSquared", "sineCubed",
  • Deceleration: "deceleration", "decelerationCubed". Starts the sprite abruptly and gradually slows it down. For a slightly more rounded deceleration effect, use "inverseSine", "inverseSineSquared", "inverseSineCubed"
  • Bounce: "bounce 10 -10". This will make the sprite overshoot the start and end points and bounce slightly when it hits them. Try changing the multipliers, 10 and -10, to vary the effect.

Use any of these easing types in Charm's tween methods in the examples that follow.

Following curves

The slide method animates a sprite along a straight line, but you can use another method called followCurve to make a sprite move along a Bezier curve.

Follow a curve

First, define the Bezier curve as a 2D array of 4 x/y points, like this:

letcurve=[[anySprite.x,anySprite.y],//Start position[108,32],//Control point 1[176,32],//Control point 2[196,160]//End position];

The second and third set of points are the Bezier curve's control points.

Next, use Charm's followCurve method to make a sprite follow that curve. (Supply the curve array as the second argument.)

c.followCurve(anySprite,//The spritecurve,//The Bezier curve array120,//Duration, in milliseconds"smoothstep",//Easing typetrue,//Should the tween yoyo?1000//Delay, in milliseconds, before it yoyos);

Only the first two arguments are required.

You'll have the best result if you center the sprite over the curve. You can do that by centering the sprite's anchor point, like this:

anySprite.anchor.set(0.5,0.5);

The slide and followCurve methods are good for simple back and forth animation effects, but you can also connect them together to make sprites traverse complex paths.

Following paths

You can use Charm's walkPath method to connect a series of points together and make a sprite move to each of those points. Each point in the series is called a waypoint. First, start with a 2D array of x/y position waypoints that map out the path you want the sprite to follow.

letwaypoints=[[32,32],//First x/y point[32,128],//Next x/y point[300,128],//Next x/y point[300,32],//Next x/y point[32,32]//Last x/y point];

You can use as many waypoints as you need.

Next, use the walkPath method to make the sprite move to all those points, in sequence. (Only the first two arguments are required.)

c.walkPath(anySprite,//The spritewaypoints,//The array of waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path reverse?1000//Delay in milliseconds between segments);

If you set the 5th argument to true, the sprite will start again from the beginning when it reaches the end. If you set the 6th argument to true, the sprite will walk the path in reverse when it reaches the end. The last argument sets the delay, in milliseconds, that the sprite should wait before moving to the next section of the path.

Here's the effect of this code:

Following paths

Following connected curves

You can make a sprite follow a series of connected curves with the walkCurve method. First, create any array of Bezier curves that describe the path you want the sprite to follow.

letcurvedWaypoints=[//First curve[[anySprite.x,anySprite.y],[75,500],[200,500],[300,300]],//Second curve[[300,300],[250,100],[100,100],[anySprite.x,anySprite.y]]];

The four points for each curve are the same as in the followCurve method: the start position, control point 1, control point 2, and the end position. The last point in the first curve should be the same as the first point in the next curve. You can use as many curves as you need.

Next, supply the curvedWapoints array as the second argument in the walkCurve method:

letspritePath=c.walkCurve(anySprite,//The spritecurvedWaypoints,//Array of curved waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path yoyo?1000//Delay in milliseconds between segments);

Here's the effect of this code:

Following paths

Using walkPath and walkCurve will give you a great head start for making some fun animated sprites for games.

Charm has bunch of other built-in, tween effects that you'll find a lot of use for in games and applications. Here's a quick round-up:

Fade-out and fade-in

Use fadeOut to make a sprite become gradually transparent, and fadeIn to make it re-appear. Here's their most basic usage:

c.fadeOut(anySprite);c.fadeIn(anySprite);

The optional second argument is the duration, in frames, that the fade should last (the default is 60 frames.)

Pulse

Use pulse to make a sprite fade out and in, continuously, at a steady rate.

c.pulse(anySprite);

The optional second argument is the duration, in frames, between each fade-in and fade-out. An optional 3rd argument lets you set the minimum alpha level that the sprite should be reduced to. For example, if you only want the sprite to become half-transparent before fading in again, set the 3rd argument to 0.5, like this:

c.pulse(anySprite,60,0.5);

Scale

You can tween a sprite's scale with the scale method. Here are the arguments you can use (only the first is required.)

c.scale(anySprite,//The spriteendScaleX,//The final x scale valueendScaleY,//The final y scale valuedurationInframes//The duration, in frames);

Breathe

If you want the scale tween effect to yoyo back and forth, use the breathe method. It's a scaling effect that makes a sprite look as though it's breathing in and out. Here's the full argument list (only the first is required.)

c.breathe(anySprite,//The spriteendScaleX,//The final scale x valueendScaleY,//The final scale y valueframes,//The duration, in framesyoyo,//Should the tween yoyo?delayBeforeRepeat,//Delay, in milliseconds, before yoyoing);

Strobe

Use the strobe method to make a sprite appear to flash like a strobe light by rapidly changing its scale.

c.strobe(sprite);

Wobble

Make a sprite wobble like a plate of jelly using the wobble method:

c.wobble(sprite);

If you use any of these scaling tween effects (scale, breathe, strobe or wobble), center the sprite's anchor point so that the scaling happens from the sprite's center.

Make your own custom tweens

These tweening effects will cover most of your needs for all kinds of games and applications. But, if you need a new effect, try writing your own. Use Charm's existing methods as your template, and if you create something really fun, let us know and we'll add it to the library!

About

No description, website, or topics provided.

Resources

Stars

121 stars

Watchers

7 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

16 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Charm - Tweening for Pixi (v3.0.11)

Charm is an easy to use tweening library for the Pixi 2D rendering engine.

(Important! this library targets Pixi v3.0.11, which is the most stable version of Pixi, and is the only version I can recommend using. This library will eventually be upgraded for Pixi v4 when the v4 branch matures.)

Table of contents

Setting up
Sliding tweens
Tween objects
Setting the easing type
Following curves
Following paths
Following connected curves
Fade-out and fade-in
Pulse
Scale
Breathe
Strobe
Wobble
Make your own custom tweens

Setting up and running Charm

To start using Charm, link to the charm.js file in your HTML document with a <script> tag. Next, create a new instance of Charm at the beginning of your program, and initialize it using the PIXI object in the constructor, like this:

c=newCharm(PIXI);

Charm needs to be updated each frame in your application's game loop. Call charm's update method in the game loop. Here's an example of a simple game loop that updates Charm:

functiongameLoop(){//Create the looprequestAnimationFrame(gameLoop);//Update charmc.update();//Optionally, you probably also need to render Pixi's root//container. If your root container is called `stage` you could//update it like this://PIXI.renderer.render(stage);}

Now you're ready to start tweening!

Let's learn how to use Charm by looking in-depth at one its most useful methods: slide.

Sliding tweens

Use Charm's slide method to make a sprite move smoothly from its current position on the canvas, to any other position. The slide method takes 7 arguments (but only the first 3 are required):

slide(anySprite,//A spritefinalXPosition,//The x position where the movement should endfinalYPosition,//The y position where the movement should enddurationInFrames,//How long the movement should last, in frameseasingType,//The easing style of the movementyoyo?,//A Boolean. Should the sprite yoyo?delayTimeBeforeRepeat//Delay time, in ms, before the sprite yoyos.)

durationInFrames determines the number of frames over which the tween should occur (the default is 60.) The easingType is a string which can be any of 15 different types, which you'll find listed ahead (the default is "smoothstep".) yoyo is a Boolean which determines whether the sprite should move back and forth, continuously between the tween's start and end points. delayTimeBeforeRepeat is a number, in milliseconds, that determines the amount of optional delay between before the sprite yoyos back.

Here's how you could use the slide method to make a sprite move from its original position to x/y point 128/128 over 120 frames:

c.slide(anySprite,128,128,120);

That's the only line of code you need to write – Charm's engine animates the sprite automatically for you. Here's the effect it produces:

Slide tween

If you want the sprite to yoyo back and forth between its start and end points, here's some code you could write:

c.slide(pixie,128,128,120,"smoothstep",true);

(true turns the yoyo effect on.)

Tween objects

All of Charm's tween methods return a tween object, that you can create like this:

letslideTween=c.slide(anySprite,128,128,120);

slideTween is the tween object in this example, and it contains some useful properties and methods that let you control the tween. One of these is a user-assignable onComplete method that will run as soon as the tween is finished. Here's how you could use onComplete to display a message in the console when the sprite has reached its destination.

letslideTween=c.slide(anySprite,128,128,120);slideTween.onComplete=()=>console.log("slide completed");

If you set yoyo to true, onComplete will run whenever the sprite reaches both its start and end points, continuously.

Tweens also have pause and play methods that let you stop and start the tween.

slideTween.pause();
slideTween.play();

Tween objects have a playing property that will be true if the tween is currently playing. All Charm's methods return tween objects that you can control and access like this.

Setting the easing types

The slide method's fourth argument is the easingType. It's a string that determines how quickly or slowly the tween speeds up and slows down. There are 15 of these types to choose from, and they're the same for all of Charm's different tween methods. The easing types fall in to 5 general categories, so you can pick one by first choosing the general category, and then the more specific type. Each category has a basic type, and then a squared and cubed version. The squared and cubed versions just exaggerate the basic effect to further degrees. The default easing type for most of Charm's tweens is "smoothstep".

  • Linear: "linear". No easing on the sprite at all; the sprite just starts and stops abruptly.
  • Smoothstep: "smoothstep", "smoothstepSquared", "smoothstepCubed". Speeds the sprite up and slows it down in a very natural looking way.
  • Acceleration: "acceleration", "accelerationCubed". Gradually speeds the sprite up and stops it abruptly. For a slightly more rounded acceleration effect, use "sine", "sineSquared", "sineCubed",
  • Deceleration: "deceleration", "decelerationCubed". Starts the sprite abruptly and gradually slows it down. For a slightly more rounded deceleration effect, use "inverseSine", "inverseSineSquared", "inverseSineCubed"
  • Bounce: "bounce 10 -10". This will make the sprite overshoot the start and end points and bounce slightly when it hits them. Try changing the multipliers, 10 and -10, to vary the effect.

Use any of these easing types in Charm's tween methods in the examples that follow.

Following curves

The slide method animates a sprite along a straight line, but you can use another method called followCurve to make a sprite move along a Bezier curve.

Follow a curve

First, define the Bezier curve as a 2D array of 4 x/y points, like this:

letcurve=[[anySprite.x,anySprite.y],//Start position[108,32],//Control point 1[176,32],//Control point 2[196,160]//End position];

The second and third set of points are the Bezier curve's control points.

Next, use Charm's followCurve method to make a sprite follow that curve. (Supply the curve array as the second argument.)

c.followCurve(anySprite,//The spritecurve,//The Bezier curve array120,//Duration, in milliseconds"smoothstep",//Easing typetrue,//Should the tween yoyo?1000//Delay, in milliseconds, before it yoyos);

Only the first two arguments are required.

You'll have the best result if you center the sprite over the curve. You can do that by centering the sprite's anchor point, like this:

anySprite.anchor.set(0.5,0.5);

The slide and followCurve methods are good for simple back and forth animation effects, but you can also connect them together to make sprites traverse complex paths.

Following paths

You can use Charm's walkPath method to connect a series of points together and make a sprite move to each of those points. Each point in the series is called a waypoint. First, start with a 2D array of x/y position waypoints that map out the path you want the sprite to follow.

letwaypoints=[[32,32],//First x/y point[32,128],//Next x/y point[300,128],//Next x/y point[300,32],//Next x/y point[32,32]//Last x/y point];

You can use as many waypoints as you need.

Next, use the walkPath method to make the sprite move to all those points, in sequence. (Only the first two arguments are required.)

c.walkPath(anySprite,//The spritewaypoints,//The array of waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path reverse?1000//Delay in milliseconds between segments);

If you set the 5th argument to true, the sprite will start again from the beginning when it reaches the end. If you set the 6th argument to true, the sprite will walk the path in reverse when it reaches the end. The last argument sets the delay, in milliseconds, that the sprite should wait before moving to the next section of the path.

Here's the effect of this code:

Following paths

Following connected curves

You can make a sprite follow a series of connected curves with the walkCurve method. First, create any array of Bezier curves that describe the path you want the sprite to follow.

letcurvedWaypoints=[//First curve[[anySprite.x,anySprite.y],[75,500],[200,500],[300,300]],//Second curve[[300,300],[250,100],[100,100],[anySprite.x,anySprite.y]]];

The four points for each curve are the same as in the followCurve method: the start position, control point 1, control point 2, and the end position. The last point in the first curve should be the same as the first point in the next curve. You can use as many curves as you need.

Next, supply the curvedWapoints array as the second argument in the walkCurve method:

letspritePath=c.walkCurve(anySprite,//The spritecurvedWaypoints,//Array of curved waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path yoyo?1000//Delay in milliseconds between segments);

Here's the effect of this code:

Following paths

Using walkPath and walkCurve will give you a great head start for making some fun animated sprites for games.

Charm has bunch of other built-in, tween effects that you'll find a lot of use for in games and applications. Here's a quick round-up:

Fade-out and fade-in

Use fadeOut to make a sprite become gradually transparent, and fadeIn to make it re-appear. Here's their most basic usage:

c.fadeOut(anySprite);c.fadeIn(anySprite);

The optional second argument is the duration, in frames, that the fade should last (the default is 60 frames.)

Pulse

Use pulse to make a sprite fade out and in, continuously, at a steady rate.

c.pulse(anySprite);

The optional second argument is the duration, in frames, between each fade-in and fade-out. An optional 3rd argument lets you set the minimum alpha level that the sprite should be reduced to. For example, if you only want the sprite to become half-transparent before fading in again, set the 3rd argument to 0.5, like this:

c.pulse(anySprite,60,0.5);

Scale

You can tween a sprite's scale with the scale method. Here are the arguments you can use (only the first is required.)

c.scale(anySprite,//The spriteendScaleX,//The final x scale valueendScaleY,//The final y scale valuedurationInframes//The duration, in frames);

Breathe

If you want the scale tween effect to yoyo back and forth, use the breathe method. It's a scaling effect that makes a sprite look as though it's breathing in and out. Here's the full argument list (only the first is required.)

c.breathe(anySprite,//The spriteendScaleX,//The final scale x valueendScaleY,//The final scale y valueframes,//The duration, in framesyoyo,//Should the tween yoyo?delayBeforeRepeat,//Delay, in milliseconds, before yoyoing);

Strobe

Use the strobe method to make a sprite appear to flash like a strobe light by rapidly changing its scale.

c.strobe(sprite);

Wobble

Make a sprite wobble like a plate of jelly using the wobble method:

c.wobble(sprite);

If you use any of these scaling tween effects (scale, breathe, strobe or wobble), center the sprite's anchor point so that the scaling happens from the sprite's center.

Make your own custom tweens

These tweening effects will cover most of your needs for all kinds of games and applications. But, if you need a new effect, try writing your own. Use Charm's existing methods as your template, and if you create something really fun, let us know and we'll add it to the library!

About

No description, website, or topics provided.

Resources

Stars

121 stars

Watchers

7 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

16 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Charm - Tweening for Pixi (v3.0.11)

Charm is an easy to use tweening library for the Pixi 2D rendering engine.

(Important! this library targets Pixi v3.0.11, which is the most stable version of Pixi, and is the only version I can recommend using. This library will eventually be upgraded for Pixi v4 when the v4 branch matures.)

Table of contents

Setting up
Sliding tweens
Tween objects
Setting the easing type
Following curves
Following paths
Following connected curves
Fade-out and fade-in
Pulse
Scale
Breathe
Strobe
Wobble
Make your own custom tweens

Setting up and running Charm

To start using Charm, link to the charm.js file in your HTML document with a <script> tag. Next, create a new instance of Charm at the beginning of your program, and initialize it using the PIXI object in the constructor, like this:

c=newCharm(PIXI);

Charm needs to be updated each frame in your application's game loop. Call charm's update method in the game loop. Here's an example of a simple game loop that updates Charm:

functiongameLoop(){//Create the looprequestAnimationFrame(gameLoop);//Update charmc.update();//Optionally, you probably also need to render Pixi's root//container. If your root container is called `stage` you could//update it like this://PIXI.renderer.render(stage);}

Now you're ready to start tweening!

Let's learn how to use Charm by looking in-depth at one its most useful methods: slide.

Sliding tweens

Use Charm's slide method to make a sprite move smoothly from its current position on the canvas, to any other position. The slide method takes 7 arguments (but only the first 3 are required):

slide(anySprite,//A spritefinalXPosition,//The x position where the movement should endfinalYPosition,//The y position where the movement should enddurationInFrames,//How long the movement should last, in frameseasingType,//The easing style of the movementyoyo?,//A Boolean. Should the sprite yoyo?delayTimeBeforeRepeat//Delay time, in ms, before the sprite yoyos.)

durationInFrames determines the number of frames over which the tween should occur (the default is 60.) The easingType is a string which can be any of 15 different types, which you'll find listed ahead (the default is "smoothstep".) yoyo is a Boolean which determines whether the sprite should move back and forth, continuously between the tween's start and end points. delayTimeBeforeRepeat is a number, in milliseconds, that determines the amount of optional delay between before the sprite yoyos back.

Here's how you could use the slide method to make a sprite move from its original position to x/y point 128/128 over 120 frames:

c.slide(anySprite,128,128,120);

That's the only line of code you need to write – Charm's engine animates the sprite automatically for you. Here's the effect it produces:

Slide tween

If you want the sprite to yoyo back and forth between its start and end points, here's some code you could write:

c.slide(pixie,128,128,120,"smoothstep",true);

(true turns the yoyo effect on.)

Tween objects

All of Charm's tween methods return a tween object, that you can create like this:

letslideTween=c.slide(anySprite,128,128,120);

slideTween is the tween object in this example, and it contains some useful properties and methods that let you control the tween. One of these is a user-assignable onComplete method that will run as soon as the tween is finished. Here's how you could use onComplete to display a message in the console when the sprite has reached its destination.

letslideTween=c.slide(anySprite,128,128,120);slideTween.onComplete=()=>console.log("slide completed");

If you set yoyo to true, onComplete will run whenever the sprite reaches both its start and end points, continuously.

Tweens also have pause and play methods that let you stop and start the tween.

slideTween.pause();
slideTween.play();

Tween objects have a playing property that will be true if the tween is currently playing. All Charm's methods return tween objects that you can control and access like this.

Setting the easing types

The slide method's fourth argument is the easingType. It's a string that determines how quickly or slowly the tween speeds up and slows down. There are 15 of these types to choose from, and they're the same for all of Charm's different tween methods. The easing types fall in to 5 general categories, so you can pick one by first choosing the general category, and then the more specific type. Each category has a basic type, and then a squared and cubed version. The squared and cubed versions just exaggerate the basic effect to further degrees. The default easing type for most of Charm's tweens is "smoothstep".

  • Linear: "linear". No easing on the sprite at all; the sprite just starts and stops abruptly.
  • Smoothstep: "smoothstep", "smoothstepSquared", "smoothstepCubed". Speeds the sprite up and slows it down in a very natural looking way.
  • Acceleration: "acceleration", "accelerationCubed". Gradually speeds the sprite up and stops it abruptly. For a slightly more rounded acceleration effect, use "sine", "sineSquared", "sineCubed",
  • Deceleration: "deceleration", "decelerationCubed". Starts the sprite abruptly and gradually slows it down. For a slightly more rounded deceleration effect, use "inverseSine", "inverseSineSquared", "inverseSineCubed"
  • Bounce: "bounce 10 -10". This will make the sprite overshoot the start and end points and bounce slightly when it hits them. Try changing the multipliers, 10 and -10, to vary the effect.

Use any of these easing types in Charm's tween methods in the examples that follow.

Following curves

The slide method animates a sprite along a straight line, but you can use another method called followCurve to make a sprite move along a Bezier curve.

Follow a curve

First, define the Bezier curve as a 2D array of 4 x/y points, like this:

letcurve=[[anySprite.x,anySprite.y],//Start position[108,32],//Control point 1[176,32],//Control point 2[196,160]//End position];

The second and third set of points are the Bezier curve's control points.

Next, use Charm's followCurve method to make a sprite follow that curve. (Supply the curve array as the second argument.)

c.followCurve(anySprite,//The spritecurve,//The Bezier curve array120,//Duration, in milliseconds"smoothstep",//Easing typetrue,//Should the tween yoyo?1000//Delay, in milliseconds, before it yoyos);

Only the first two arguments are required.

You'll have the best result if you center the sprite over the curve. You can do that by centering the sprite's anchor point, like this:

anySprite.anchor.set(0.5,0.5);

The slide and followCurve methods are good for simple back and forth animation effects, but you can also connect them together to make sprites traverse complex paths.

Following paths

You can use Charm's walkPath method to connect a series of points together and make a sprite move to each of those points. Each point in the series is called a waypoint. First, start with a 2D array of x/y position waypoints that map out the path you want the sprite to follow.

letwaypoints=[[32,32],//First x/y point[32,128],//Next x/y point[300,128],//Next x/y point[300,32],//Next x/y point[32,32]//Last x/y point];

You can use as many waypoints as you need.

Next, use the walkPath method to make the sprite move to all those points, in sequence. (Only the first two arguments are required.)

c.walkPath(anySprite,//The spritewaypoints,//The array of waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path reverse?1000//Delay in milliseconds between segments);

If you set the 5th argument to true, the sprite will start again from the beginning when it reaches the end. If you set the 6th argument to true, the sprite will walk the path in reverse when it reaches the end. The last argument sets the delay, in milliseconds, that the sprite should wait before moving to the next section of the path.

Here's the effect of this code:

Following paths

Following connected curves

You can make a sprite follow a series of connected curves with the walkCurve method. First, create any array of Bezier curves that describe the path you want the sprite to follow.

letcurvedWaypoints=[//First curve[[anySprite.x,anySprite.y],[75,500],[200,500],[300,300]],//Second curve[[300,300],[250,100],[100,100],[anySprite.x,anySprite.y]]];

The four points for each curve are the same as in the followCurve method: the start position, control point 1, control point 2, and the end position. The last point in the first curve should be the same as the first point in the next curve. You can use as many curves as you need.

Next, supply the curvedWapoints array as the second argument in the walkCurve method:

letspritePath=c.walkCurve(anySprite,//The spritecurvedWaypoints,//Array of curved waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path yoyo?1000//Delay in milliseconds between segments);

Here's the effect of this code:

Following paths

Using walkPath and walkCurve will give you a great head start for making some fun animated sprites for games.

Charm has bunch of other built-in, tween effects that you'll find a lot of use for in games and applications. Here's a quick round-up:

Fade-out and fade-in

Use fadeOut to make a sprite become gradually transparent, and fadeIn to make it re-appear. Here's their most basic usage:

c.fadeOut(anySprite);c.fadeIn(anySprite);

The optional second argument is the duration, in frames, that the fade should last (the default is 60 frames.)

Pulse

Use pulse to make a sprite fade out and in, continuously, at a steady rate.

c.pulse(anySprite);

The optional second argument is the duration, in frames, between each fade-in and fade-out. An optional 3rd argument lets you set the minimum alpha level that the sprite should be reduced to. For example, if you only want the sprite to become half-transparent before fading in again, set the 3rd argument to 0.5, like this:

c.pulse(anySprite,60,0.5);

Scale

You can tween a sprite's scale with the scale method. Here are the arguments you can use (only the first is required.)

c.scale(anySprite,//The spriteendScaleX,//The final x scale valueendScaleY,//The final y scale valuedurationInframes//The duration, in frames);

Breathe

If you want the scale tween effect to yoyo back and forth, use the breathe method. It's a scaling effect that makes a sprite look as though it's breathing in and out. Here's the full argument list (only the first is required.)

c.breathe(anySprite,//The spriteendScaleX,//The final scale x valueendScaleY,//The final scale y valueframes,//The duration, in framesyoyo,//Should the tween yoyo?delayBeforeRepeat,//Delay, in milliseconds, before yoyoing);

Strobe

Use the strobe method to make a sprite appear to flash like a strobe light by rapidly changing its scale.

c.strobe(sprite);

Wobble

Make a sprite wobble like a plate of jelly using the wobble method:

c.wobble(sprite);

If you use any of these scaling tween effects (scale, breathe, strobe or wobble), center the sprite's anchor point so that the scaling happens from the sprite's center.

Make your own custom tweens

These tweening effects will cover most of your needs for all kinds of games and applications. But, if you need a new effect, try writing your own. Use Charm's existing methods as your template, and if you create something really fun, let us know and we'll add it to the library!

About

No description, website, or topics provided.

Resources

Stars

121 stars

Watchers

7 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

16 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Charm - Tweening for Pixi (v3.0.11)

Charm is an easy to use tweening library for the Pixi 2D rendering engine.

(Important! this library targets Pixi v3.0.11, which is the most stable version of Pixi, and is the only version I can recommend using. This library will eventually be upgraded for Pixi v4 when the v4 branch matures.)

Table of contents

Setting up
Sliding tweens
Tween objects
Setting the easing type
Following curves
Following paths
Following connected curves
Fade-out and fade-in
Pulse
Scale
Breathe
Strobe
Wobble
Make your own custom tweens

Setting up and running Charm

To start using Charm, link to the charm.js file in your HTML document with a <script> tag. Next, create a new instance of Charm at the beginning of your program, and initialize it using the PIXI object in the constructor, like this:

c=newCharm(PIXI);

Charm needs to be updated each frame in your application's game loop. Call charm's update method in the game loop. Here's an example of a simple game loop that updates Charm:

functiongameLoop(){//Create the looprequestAnimationFrame(gameLoop);//Update charmc.update();//Optionally, you probably also need to render Pixi's root//container. If your root container is called `stage` you could//update it like this://PIXI.renderer.render(stage);}

Now you're ready to start tweening!

Let's learn how to use Charm by looking in-depth at one its most useful methods: slide.

Sliding tweens

Use Charm's slide method to make a sprite move smoothly from its current position on the canvas, to any other position. The slide method takes 7 arguments (but only the first 3 are required):

slide(anySprite,//A spritefinalXPosition,//The x position where the movement should endfinalYPosition,//The y position where the movement should enddurationInFrames,//How long the movement should last, in frameseasingType,//The easing style of the movementyoyo?,//A Boolean. Should the sprite yoyo?delayTimeBeforeRepeat//Delay time, in ms, before the sprite yoyos.)

durationInFrames determines the number of frames over which the tween should occur (the default is 60.) The easingType is a string which can be any of 15 different types, which you'll find listed ahead (the default is "smoothstep".) yoyo is a Boolean which determines whether the sprite should move back and forth, continuously between the tween's start and end points. delayTimeBeforeRepeat is a number, in milliseconds, that determines the amount of optional delay between before the sprite yoyos back.

Here's how you could use the slide method to make a sprite move from its original position to x/y point 128/128 over 120 frames:

c.slide(anySprite,128,128,120);

That's the only line of code you need to write – Charm's engine animates the sprite automatically for you. Here's the effect it produces:

Slide tween

If you want the sprite to yoyo back and forth between its start and end points, here's some code you could write:

c.slide(pixie,128,128,120,"smoothstep",true);

(true turns the yoyo effect on.)

Tween objects

All of Charm's tween methods return a tween object, that you can create like this:

letslideTween=c.slide(anySprite,128,128,120);

slideTween is the tween object in this example, and it contains some useful properties and methods that let you control the tween. One of these is a user-assignable onComplete method that will run as soon as the tween is finished. Here's how you could use onComplete to display a message in the console when the sprite has reached its destination.

letslideTween=c.slide(anySprite,128,128,120);slideTween.onComplete=()=>console.log("slide completed");

If you set yoyo to true, onComplete will run whenever the sprite reaches both its start and end points, continuously.

Tweens also have pause and play methods that let you stop and start the tween.

slideTween.pause();
slideTween.play();

Tween objects have a playing property that will be true if the tween is currently playing. All Charm's methods return tween objects that you can control and access like this.

Setting the easing types

The slide method's fourth argument is the easingType. It's a string that determines how quickly or slowly the tween speeds up and slows down. There are 15 of these types to choose from, and they're the same for all of Charm's different tween methods. The easing types fall in to 5 general categories, so you can pick one by first choosing the general category, and then the more specific type. Each category has a basic type, and then a squared and cubed version. The squared and cubed versions just exaggerate the basic effect to further degrees. The default easing type for most of Charm's tweens is "smoothstep".

  • Linear: "linear". No easing on the sprite at all; the sprite just starts and stops abruptly.
  • Smoothstep: "smoothstep", "smoothstepSquared", "smoothstepCubed". Speeds the sprite up and slows it down in a very natural looking way.
  • Acceleration: "acceleration", "accelerationCubed". Gradually speeds the sprite up and stops it abruptly. For a slightly more rounded acceleration effect, use "sine", "sineSquared", "sineCubed",
  • Deceleration: "deceleration", "decelerationCubed". Starts the sprite abruptly and gradually slows it down. For a slightly more rounded deceleration effect, use "inverseSine", "inverseSineSquared", "inverseSineCubed"
  • Bounce: "bounce 10 -10". This will make the sprite overshoot the start and end points and bounce slightly when it hits them. Try changing the multipliers, 10 and -10, to vary the effect.

Use any of these easing types in Charm's tween methods in the examples that follow.

Following curves

The slide method animates a sprite along a straight line, but you can use another method called followCurve to make a sprite move along a Bezier curve.

Follow a curve

First, define the Bezier curve as a 2D array of 4 x/y points, like this:

letcurve=[[anySprite.x,anySprite.y],//Start position[108,32],//Control point 1[176,32],//Control point 2[196,160]//End position];

The second and third set of points are the Bezier curve's control points.

Next, use Charm's followCurve method to make a sprite follow that curve. (Supply the curve array as the second argument.)

c.followCurve(anySprite,//The spritecurve,//The Bezier curve array120,//Duration, in milliseconds"smoothstep",//Easing typetrue,//Should the tween yoyo?1000//Delay, in milliseconds, before it yoyos);

Only the first two arguments are required.

You'll have the best result if you center the sprite over the curve. You can do that by centering the sprite's anchor point, like this:

anySprite.anchor.set(0.5,0.5);

The slide and followCurve methods are good for simple back and forth animation effects, but you can also connect them together to make sprites traverse complex paths.

Following paths

You can use Charm's walkPath method to connect a series of points together and make a sprite move to each of those points. Each point in the series is called a waypoint. First, start with a 2D array of x/y position waypoints that map out the path you want the sprite to follow.

letwaypoints=[[32,32],//First x/y point[32,128],//Next x/y point[300,128],//Next x/y point[300,32],//Next x/y point[32,32]//Last x/y point];

You can use as many waypoints as you need.

Next, use the walkPath method to make the sprite move to all those points, in sequence. (Only the first two arguments are required.)

c.walkPath(anySprite,//The spritewaypoints,//The array of waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path reverse?1000//Delay in milliseconds between segments);

If you set the 5th argument to true, the sprite will start again from the beginning when it reaches the end. If you set the 6th argument to true, the sprite will walk the path in reverse when it reaches the end. The last argument sets the delay, in milliseconds, that the sprite should wait before moving to the next section of the path.

Here's the effect of this code:

Following paths

Following connected curves

You can make a sprite follow a series of connected curves with the walkCurve method. First, create any array of Bezier curves that describe the path you want the sprite to follow.

letcurvedWaypoints=[//First curve[[anySprite.x,anySprite.y],[75,500],[200,500],[300,300]],//Second curve[[300,300],[250,100],[100,100],[anySprite.x,anySprite.y]]];

The four points for each curve are the same as in the followCurve method: the start position, control point 1, control point 2, and the end position. The last point in the first curve should be the same as the first point in the next curve. You can use as many curves as you need.

Next, supply the curvedWapoints array as the second argument in the walkCurve method:

letspritePath=c.walkCurve(anySprite,//The spritecurvedWaypoints,//Array of curved waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path yoyo?1000//Delay in milliseconds between segments);

Here's the effect of this code:

Following paths

Using walkPath and walkCurve will give you a great head start for making some fun animated sprites for games.

Charm has bunch of other built-in, tween effects that you'll find a lot of use for in games and applications. Here's a quick round-up:

Fade-out and fade-in

Use fadeOut to make a sprite become gradually transparent, and fadeIn to make it re-appear. Here's their most basic usage:

c.fadeOut(anySprite);c.fadeIn(anySprite);

The optional second argument is the duration, in frames, that the fade should last (the default is 60 frames.)

Pulse

Use pulse to make a sprite fade out and in, continuously, at a steady rate.

c.pulse(anySprite);

The optional second argument is the duration, in frames, between each fade-in and fade-out. An optional 3rd argument lets you set the minimum alpha level that the sprite should be reduced to. For example, if you only want the sprite to become half-transparent before fading in again, set the 3rd argument to 0.5, like this:

c.pulse(anySprite,60,0.5);

Scale

You can tween a sprite's scale with the scale method. Here are the arguments you can use (only the first is required.)

c.scale(anySprite,//The spriteendScaleX,//The final x scale valueendScaleY,//The final y scale valuedurationInframes//The duration, in frames);

Breathe

If you want the scale tween effect to yoyo back and forth, use the breathe method. It's a scaling effect that makes a sprite look as though it's breathing in and out. Here's the full argument list (only the first is required.)

c.breathe(anySprite,//The spriteendScaleX,//The final scale x valueendScaleY,//The final scale y valueframes,//The duration, in framesyoyo,//Should the tween yoyo?delayBeforeRepeat,//Delay, in milliseconds, before yoyoing);

Strobe

Use the strobe method to make a sprite appear to flash like a strobe light by rapidly changing its scale.

c.strobe(sprite);

Wobble

Make a sprite wobble like a plate of jelly using the wobble method:

c.wobble(sprite);

If you use any of these scaling tween effects (scale, breathe, strobe or wobble), center the sprite's anchor point so that the scaling happens from the sprite's center.

Make your own custom tweens

These tweening effects will cover most of your needs for all kinds of games and applications. But, if you need a new effect, try writing your own. Use Charm's existing methods as your template, and if you create something really fun, let us know and we'll add it to the library!

About

No description, website, or topics provided.

Resources

Stars

121 stars

Watchers

7 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

16 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Charm - Tweening for Pixi (v3.0.11)

Charm is an easy to use tweening library for the Pixi 2D rendering engine.

(Important! this library targets Pixi v3.0.11, which is the most stable version of Pixi, and is the only version I can recommend using. This library will eventually be upgraded for Pixi v4 when the v4 branch matures.)

Table of contents

Setting up
Sliding tweens
Tween objects
Setting the easing type
Following curves
Following paths
Following connected curves
Fade-out and fade-in
Pulse
Scale
Breathe
Strobe
Wobble
Make your own custom tweens

Setting up and running Charm

To start using Charm, link to the charm.js file in your HTML document with a <script> tag. Next, create a new instance of Charm at the beginning of your program, and initialize it using the PIXI object in the constructor, like this:

c=newCharm(PIXI);

Charm needs to be updated each frame in your application's game loop. Call charm's update method in the game loop. Here's an example of a simple game loop that updates Charm:

functiongameLoop(){//Create the looprequestAnimationFrame(gameLoop);//Update charmc.update();//Optionally, you probably also need to render Pixi's root//container. If your root container is called `stage` you could//update it like this://PIXI.renderer.render(stage);}

Now you're ready to start tweening!

Let's learn how to use Charm by looking in-depth at one its most useful methods: slide.

Sliding tweens

Use Charm's slide method to make a sprite move smoothly from its current position on the canvas, to any other position. The slide method takes 7 arguments (but only the first 3 are required):

slide(anySprite,//A spritefinalXPosition,//The x position where the movement should endfinalYPosition,//The y position where the movement should enddurationInFrames,//How long the movement should last, in frameseasingType,//The easing style of the movementyoyo?,//A Boolean. Should the sprite yoyo?delayTimeBeforeRepeat//Delay time, in ms, before the sprite yoyos.)

durationInFrames determines the number of frames over which the tween should occur (the default is 60.) The easingType is a string which can be any of 15 different types, which you'll find listed ahead (the default is "smoothstep".) yoyo is a Boolean which determines whether the sprite should move back and forth, continuously between the tween's start and end points. delayTimeBeforeRepeat is a number, in milliseconds, that determines the amount of optional delay between before the sprite yoyos back.

Here's how you could use the slide method to make a sprite move from its original position to x/y point 128/128 over 120 frames:

c.slide(anySprite,128,128,120);

That's the only line of code you need to write – Charm's engine animates the sprite automatically for you. Here's the effect it produces:

Slide tween

If you want the sprite to yoyo back and forth between its start and end points, here's some code you could write:

c.slide(pixie,128,128,120,"smoothstep",true);

(true turns the yoyo effect on.)

Tween objects

All of Charm's tween methods return a tween object, that you can create like this:

letslideTween=c.slide(anySprite,128,128,120);

slideTween is the tween object in this example, and it contains some useful properties and methods that let you control the tween. One of these is a user-assignable onComplete method that will run as soon as the tween is finished. Here's how you could use onComplete to display a message in the console when the sprite has reached its destination.

letslideTween=c.slide(anySprite,128,128,120);slideTween.onComplete=()=>console.log("slide completed");

If you set yoyo to true, onComplete will run whenever the sprite reaches both its start and end points, continuously.

Tweens also have pause and play methods that let you stop and start the tween.

slideTween.pause();
slideTween.play();

Tween objects have a playing property that will be true if the tween is currently playing. All Charm's methods return tween objects that you can control and access like this.

Setting the easing types

The slide method's fourth argument is the easingType. It's a string that determines how quickly or slowly the tween speeds up and slows down. There are 15 of these types to choose from, and they're the same for all of Charm's different tween methods. The easing types fall in to 5 general categories, so you can pick one by first choosing the general category, and then the more specific type. Each category has a basic type, and then a squared and cubed version. The squared and cubed versions just exaggerate the basic effect to further degrees. The default easing type for most of Charm's tweens is "smoothstep".

  • Linear: "linear". No easing on the sprite at all; the sprite just starts and stops abruptly.
  • Smoothstep: "smoothstep", "smoothstepSquared", "smoothstepCubed". Speeds the sprite up and slows it down in a very natural looking way.
  • Acceleration: "acceleration", "accelerationCubed". Gradually speeds the sprite up and stops it abruptly. For a slightly more rounded acceleration effect, use "sine", "sineSquared", "sineCubed",
  • Deceleration: "deceleration", "decelerationCubed". Starts the sprite abruptly and gradually slows it down. For a slightly more rounded deceleration effect, use "inverseSine", "inverseSineSquared", "inverseSineCubed"
  • Bounce: "bounce 10 -10". This will make the sprite overshoot the start and end points and bounce slightly when it hits them. Try changing the multipliers, 10 and -10, to vary the effect.

Use any of these easing types in Charm's tween methods in the examples that follow.

Following curves

The slide method animates a sprite along a straight line, but you can use another method called followCurve to make a sprite move along a Bezier curve.

Follow a curve

First, define the Bezier curve as a 2D array of 4 x/y points, like this:

letcurve=[[anySprite.x,anySprite.y],//Start position[108,32],//Control point 1[176,32],//Control point 2[196,160]//End position];

The second and third set of points are the Bezier curve's control points.

Next, use Charm's followCurve method to make a sprite follow that curve. (Supply the curve array as the second argument.)

c.followCurve(anySprite,//The spritecurve,//The Bezier curve array120,//Duration, in milliseconds"smoothstep",//Easing typetrue,//Should the tween yoyo?1000//Delay, in milliseconds, before it yoyos);

Only the first two arguments are required.

You'll have the best result if you center the sprite over the curve. You can do that by centering the sprite's anchor point, like this:

anySprite.anchor.set(0.5,0.5);

The slide and followCurve methods are good for simple back and forth animation effects, but you can also connect them together to make sprites traverse complex paths.

Following paths

You can use Charm's walkPath method to connect a series of points together and make a sprite move to each of those points. Each point in the series is called a waypoint. First, start with a 2D array of x/y position waypoints that map out the path you want the sprite to follow.

letwaypoints=[[32,32],//First x/y point[32,128],//Next x/y point[300,128],//Next x/y point[300,32],//Next x/y point[32,32]//Last x/y point];

You can use as many waypoints as you need.

Next, use the walkPath method to make the sprite move to all those points, in sequence. (Only the first two arguments are required.)

c.walkPath(anySprite,//The spritewaypoints,//The array of waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path reverse?1000//Delay in milliseconds between segments);

If you set the 5th argument to true, the sprite will start again from the beginning when it reaches the end. If you set the 6th argument to true, the sprite will walk the path in reverse when it reaches the end. The last argument sets the delay, in milliseconds, that the sprite should wait before moving to the next section of the path.

Here's the effect of this code:

Following paths

Following connected curves

You can make a sprite follow a series of connected curves with the walkCurve method. First, create any array of Bezier curves that describe the path you want the sprite to follow.

letcurvedWaypoints=[//First curve[[anySprite.x,anySprite.y],[75,500],[200,500],[300,300]],//Second curve[[300,300],[250,100],[100,100],[anySprite.x,anySprite.y]]];

The four points for each curve are the same as in the followCurve method: the start position, control point 1, control point 2, and the end position. The last point in the first curve should be the same as the first point in the next curve. You can use as many curves as you need.

Next, supply the curvedWapoints array as the second argument in the walkCurve method:

letspritePath=c.walkCurve(anySprite,//The spritecurvedWaypoints,//Array of curved waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path yoyo?1000//Delay in milliseconds between segments);

Here's the effect of this code:

Following paths

Using walkPath and walkCurve will give you a great head start for making some fun animated sprites for games.

Charm has bunch of other built-in, tween effects that you'll find a lot of use for in games and applications. Here's a quick round-up:

Fade-out and fade-in

Use fadeOut to make a sprite become gradually transparent, and fadeIn to make it re-appear. Here's their most basic usage:

c.fadeOut(anySprite);c.fadeIn(anySprite);

The optional second argument is the duration, in frames, that the fade should last (the default is 60 frames.)

Pulse

Use pulse to make a sprite fade out and in, continuously, at a steady rate.

c.pulse(anySprite);

The optional second argument is the duration, in frames, between each fade-in and fade-out. An optional 3rd argument lets you set the minimum alpha level that the sprite should be reduced to. For example, if you only want the sprite to become half-transparent before fading in again, set the 3rd argument to 0.5, like this:

c.pulse(anySprite,60,0.5);

Scale

You can tween a sprite's scale with the scale method. Here are the arguments you can use (only the first is required.)

c.scale(anySprite,//The spriteendScaleX,//The final x scale valueendScaleY,//The final y scale valuedurationInframes//The duration, in frames);

Breathe

If you want the scale tween effect to yoyo back and forth, use the breathe method. It's a scaling effect that makes a sprite look as though it's breathing in and out. Here's the full argument list (only the first is required.)

c.breathe(anySprite,//The spriteendScaleX,//The final scale x valueendScaleY,//The final scale y valueframes,//The duration, in framesyoyo,//Should the tween yoyo?delayBeforeRepeat,//Delay, in milliseconds, before yoyoing);

Strobe

Use the strobe method to make a sprite appear to flash like a strobe light by rapidly changing its scale.

c.strobe(sprite);

Wobble

Make a sprite wobble like a plate of jelly using the wobble method:

c.wobble(sprite);

If you use any of these scaling tween effects (scale, breathe, strobe or wobble), center the sprite's anchor point so that the scaling happens from the sprite's center.

Make your own custom tweens

These tweening effects will cover most of your needs for all kinds of games and applications. But, if you need a new effect, try writing your own. Use Charm's existing methods as your template, and if you create something really fun, let us know and we'll add it to the library!

About

No description, website, or topics provided.

Resources

Stars

121 stars

Watchers

7 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

16 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Charm - Tweening for Pixi (v3.0.11)

Charm is an easy to use tweening library for the Pixi 2D rendering engine.

(Important! this library targets Pixi v3.0.11, which is the most stable version of Pixi, and is the only version I can recommend using. This library will eventually be upgraded for Pixi v4 when the v4 branch matures.)

Table of contents

Setting up
Sliding tweens
Tween objects
Setting the easing type
Following curves
Following paths
Following connected curves
Fade-out and fade-in
Pulse
Scale
Breathe
Strobe
Wobble
Make your own custom tweens

Setting up and running Charm

To start using Charm, link to the charm.js file in your HTML document with a <script> tag. Next, create a new instance of Charm at the beginning of your program, and initialize it using the PIXI object in the constructor, like this:

c=newCharm(PIXI);

Charm needs to be updated each frame in your application's game loop. Call charm's update method in the game loop. Here's an example of a simple game loop that updates Charm:

functiongameLoop(){//Create the looprequestAnimationFrame(gameLoop);//Update charmc.update();//Optionally, you probably also need to render Pixi's root//container. If your root container is called `stage` you could//update it like this://PIXI.renderer.render(stage);}

Now you're ready to start tweening!

Let's learn how to use Charm by looking in-depth at one its most useful methods: slide.

Sliding tweens

Use Charm's slide method to make a sprite move smoothly from its current position on the canvas, to any other position. The slide method takes 7 arguments (but only the first 3 are required):

slide(anySprite,//A spritefinalXPosition,//The x position where the movement should endfinalYPosition,//The y position where the movement should enddurationInFrames,//How long the movement should last, in frameseasingType,//The easing style of the movementyoyo?,//A Boolean. Should the sprite yoyo?delayTimeBeforeRepeat//Delay time, in ms, before the sprite yoyos.)

durationInFrames determines the number of frames over which the tween should occur (the default is 60.) The easingType is a string which can be any of 15 different types, which you'll find listed ahead (the default is "smoothstep".) yoyo is a Boolean which determines whether the sprite should move back and forth, continuously between the tween's start and end points. delayTimeBeforeRepeat is a number, in milliseconds, that determines the amount of optional delay between before the sprite yoyos back.

Here's how you could use the slide method to make a sprite move from its original position to x/y point 128/128 over 120 frames:

c.slide(anySprite,128,128,120);

That's the only line of code you need to write – Charm's engine animates the sprite automatically for you. Here's the effect it produces:

Slide tween

If you want the sprite to yoyo back and forth between its start and end points, here's some code you could write:

c.slide(pixie,128,128,120,"smoothstep",true);

(true turns the yoyo effect on.)

Tween objects

All of Charm's tween methods return a tween object, that you can create like this:

letslideTween=c.slide(anySprite,128,128,120);

slideTween is the tween object in this example, and it contains some useful properties and methods that let you control the tween. One of these is a user-assignable onComplete method that will run as soon as the tween is finished. Here's how you could use onComplete to display a message in the console when the sprite has reached its destination.

letslideTween=c.slide(anySprite,128,128,120);slideTween.onComplete=()=>console.log("slide completed");

If you set yoyo to true, onComplete will run whenever the sprite reaches both its start and end points, continuously.

Tweens also have pause and play methods that let you stop and start the tween.

slideTween.pause();
slideTween.play();

Tween objects have a playing property that will be true if the tween is currently playing. All Charm's methods return tween objects that you can control and access like this.

Setting the easing types

The slide method's fourth argument is the easingType. It's a string that determines how quickly or slowly the tween speeds up and slows down. There are 15 of these types to choose from, and they're the same for all of Charm's different tween methods. The easing types fall in to 5 general categories, so you can pick one by first choosing the general category, and then the more specific type. Each category has a basic type, and then a squared and cubed version. The squared and cubed versions just exaggerate the basic effect to further degrees. The default easing type for most of Charm's tweens is "smoothstep".

  • Linear: "linear". No easing on the sprite at all; the sprite just starts and stops abruptly.
  • Smoothstep: "smoothstep", "smoothstepSquared", "smoothstepCubed". Speeds the sprite up and slows it down in a very natural looking way.
  • Acceleration: "acceleration", "accelerationCubed". Gradually speeds the sprite up and stops it abruptly. For a slightly more rounded acceleration effect, use "sine", "sineSquared", "sineCubed",
  • Deceleration: "deceleration", "decelerationCubed". Starts the sprite abruptly and gradually slows it down. For a slightly more rounded deceleration effect, use "inverseSine", "inverseSineSquared", "inverseSineCubed"
  • Bounce: "bounce 10 -10". This will make the sprite overshoot the start and end points and bounce slightly when it hits them. Try changing the multipliers, 10 and -10, to vary the effect.

Use any of these easing types in Charm's tween methods in the examples that follow.

Following curves

The slide method animates a sprite along a straight line, but you can use another method called followCurve to make a sprite move along a Bezier curve.

Follow a curve

First, define the Bezier curve as a 2D array of 4 x/y points, like this:

letcurve=[[anySprite.x,anySprite.y],//Start position[108,32],//Control point 1[176,32],//Control point 2[196,160]//End position];

The second and third set of points are the Bezier curve's control points.

Next, use Charm's followCurve method to make a sprite follow that curve. (Supply the curve array as the second argument.)

c.followCurve(anySprite,//The spritecurve,//The Bezier curve array120,//Duration, in milliseconds"smoothstep",//Easing typetrue,//Should the tween yoyo?1000//Delay, in milliseconds, before it yoyos);

Only the first two arguments are required.

You'll have the best result if you center the sprite over the curve. You can do that by centering the sprite's anchor point, like this:

anySprite.anchor.set(0.5,0.5);

The slide and followCurve methods are good for simple back and forth animation effects, but you can also connect them together to make sprites traverse complex paths.

Following paths

You can use Charm's walkPath method to connect a series of points together and make a sprite move to each of those points. Each point in the series is called a waypoint. First, start with a 2D array of x/y position waypoints that map out the path you want the sprite to follow.

letwaypoints=[[32,32],//First x/y point[32,128],//Next x/y point[300,128],//Next x/y point[300,32],//Next x/y point[32,32]//Last x/y point];

You can use as many waypoints as you need.

Next, use the walkPath method to make the sprite move to all those points, in sequence. (Only the first two arguments are required.)

c.walkPath(anySprite,//The spritewaypoints,//The array of waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path reverse?1000//Delay in milliseconds between segments);

If you set the 5th argument to true, the sprite will start again from the beginning when it reaches the end. If you set the 6th argument to true, the sprite will walk the path in reverse when it reaches the end. The last argument sets the delay, in milliseconds, that the sprite should wait before moving to the next section of the path.

Here's the effect of this code:

Following paths

Following connected curves

You can make a sprite follow a series of connected curves with the walkCurve method. First, create any array of Bezier curves that describe the path you want the sprite to follow.

letcurvedWaypoints=[//First curve[[anySprite.x,anySprite.y],[75,500],[200,500],[300,300]],//Second curve[[300,300],[250,100],[100,100],[anySprite.x,anySprite.y]]];

The four points for each curve are the same as in the followCurve method: the start position, control point 1, control point 2, and the end position. The last point in the first curve should be the same as the first point in the next curve. You can use as many curves as you need.

Next, supply the curvedWapoints array as the second argument in the walkCurve method:

letspritePath=c.walkCurve(anySprite,//The spritecurvedWaypoints,//Array of curved waypoints300,//Total duration, in frames"smoothstep",//Easing typetrue,//Should the path loop?true,//Should the path yoyo?1000//Delay in milliseconds between segments);

Here's the effect of this code:

Following paths

Using walkPath and walkCurve will give you a great head start for making some fun animated sprites for games.

Charm has bunch of other built-in, tween effects that you'll find a lot of use for in games and applications. Here's a quick round-up:

Fade-out and fade-in

Use fadeOut to make a sprite become gradually transparent, and fadeIn to make it re-appear. Here's their most basic usage:

c.fadeOut(anySprite);c.fadeIn(anySprite);

The optional second argument is the duration, in frames, that the fade should last (the default is 60 frames.)

Pulse

Use pulse to make a sprite fade out and in, continuously, at a steady rate.

c.pulse(anySprite);

The optional second argument is the duration, in frames, between each fade-in and fade-out. An optional 3rd argument lets you set the minimum alpha level that the sprite should be reduced to. For example, if you only want the sprite to become half-transparent before fading in again, set the 3rd argument to 0.5, like this:

c.pulse(anySprite,60,0.5);

Scale

You can tween a sprite's scale with the scale method. Here are the arguments you can use (only the first is required.)

c.scale(anySprite,//The spriteendScaleX,//The final x scale valueendScaleY,//The final y scale valuedurationInframes//The duration, in frames);

Breathe

If you want the scale tween effect to yoyo back and forth, use the breathe method. It's a scaling effect that makes a sprite look as though it's breathing in and out. Here's the full argument list (only the first is required.)

c.breathe(anySprite,//The spriteendScaleX,//The final scale x valueendScaleY,//The final scale y valueframes,//The duration, in framesyoyo,//Should the tween yoyo?delayBeforeRepeat,//Delay, in milliseconds, before yoyoing);

Strobe

Use the strobe method to make a sprite appear to flash like a strobe light by rapidly changing its scale.

c.strobe(sprite);

Wobble

Make a sprite wobble like a plate of jelly using the wobble method:

c.wobble(sprite);

If you use any of these scaling tween effects (scale, breathe, strobe or wobble), center the sprite's anchor point so that the scaling happens from the sprite's center.

Make your own custom tweens

These tweening effects will cover most of your needs for all kinds of games and applications. But, if you need a new effect, try writing your own. Use Charm's existing methods as your template, and if you create something really fun, let us know and we'll add it to the library!

About

No description, website, or topics provided.

Resources

Stars

121 stars

Watchers

7 watching

Forks

Releases

Packages

Contributors

Languages