pixijs-input-devices 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +578 -0
  3. package/package.json +64 -0
package/LICENSE ADDED
@@ -0,0 +1,8 @@
1
+ The MIT License (MIT)
2
+ Copyright © 2024 Reece Como, Sunil Patel.
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,578 @@
1
+ # 🕹️ pixijs-input-devices  [![NPM version](https://img.shields.io/npm/v/pixijs-input-devices.svg)](https://www.npmjs.com/package/pixijs-input-devices) [![Minzipped](https://badgen.net/bundlephobia/minzip/pixijs-input-devices@latest)](https://bundlephobia.com/package/pixijs-input-devices) [![Downloads per month](https://img.shields.io/npm/dm/pixijs-input-devices.svg)](https://www.npmjs.com/package/pixijs-input-devices) [![Tests](https://github.com/reececomo/pixijs-input-devices/actions/workflows/tests.yml/badge.svg)](https://github.com/reececomo/pixijs-input-devices/actions/workflows/tests.yml) [![License](https://badgen.net/npm/license/pixijs-input-devices)](https://github.com/reececomo/pixijs-input-devices/blob/main/LICENSE)
2
+
3
+ WIP
4
+
5
+ - Adds support for ⌨️ keyboards, 🎮 gamepads, and other human interface devices
6
+ - Built-in event API for navigating user-focusable elements
7
+ - Built-in polling API for real-time inputs
8
+
9
+ <hr/>
10
+
11
+ ```ts
12
+ // set up ticker (or put in your main update loop):
13
+ Ticker.shared.add( () => InputDeviceManager.shared.update() );
14
+ ```
15
+
16
+ ### Realtime API (polling)
17
+
18
+ Simple example
19
+
20
+ ```ts
21
+ let jump = false;
22
+ let hide = false;
23
+ let moveX = 0.0;
24
+
25
+ for ( const device of InputDeviceManager.shared.devices )
26
+ {
27
+ if ( device.type === "keyboard" )
28
+ {
29
+ if ( device.key["ArrowUp"] ) jump = true
30
+ if ( device.key["ArrowDown"] ) hide = true
31
+ if ( device.key["ArrowLeft"] ) moveX = -1.0
32
+ if ( device.key["ArrowRight"] ) moveX = 1.0
33
+ }
34
+ else if ( device.type === "gamepad" )
35
+ {
36
+ if ( device.button[Button.A] ) jump = true
37
+ if ( device.rightTrigger >= 0.25 ) hide = true
38
+ if ( device.leftJoystick.x !== 0.0 ) moveX = device.leftJoystick.x
39
+ }
40
+ }
41
+ ```
42
+
43
+ > [!NOTE]
44
+ > You can use `device.button[Button.RightTrigger]` to detect triggers too.
45
+
46
+ > [!NOTE]
47
+ > You can use `device.pressingAll([...])` and `device.pressingAny([...])` to check groups of keys/buttons.
48
+
49
+ > [!NOTE]
50
+ > You can use `device.assignee` to store any device assignment-related data (such as a user ID).
51
+
52
+
53
+ ### Event-driven API
54
+
55
+ ```
56
+ InputDeviceManager.shared.keyboard.bindGlobal({
57
+ { key: "KeyA", action}
58
+ })
59
+ ```
60
+
61
+ By default, any element with "mousedown" or "pointerdown" will
62
+
63
+ Container events | description
64
+ ------------------|--------------------------------------------------------
65
+ `focus` | Target became focused. args: direction: { x, y }
66
+ `blur` | Target lost focus. args: direction: { x, y }
67
+ `focusHinted` | Target may be about to become focused. args: direction: { x, y }
68
+ `blurHinted` | Target may be about to lose focus. args: direction: { x, y }
69
+
70
+ Container properties | description
71
+ ---------------------|-----------------------------------------------------
72
+ `focusable` | boolean?, default: `undefined`
73
+ `isFocusGroup` | boolean?, default: `false`
74
+ `focusPriority` | number?, default: `0`
75
+ `focusGroup` | PIXI.Container?, default: `app.stage ?? undefined`
76
+ `focusTransform` | `{ x, y }`, default: `{ x: 5, y: 5 }`
77
+ `isFocusable` | get () => boolean, returns true if "focusable" = true, or InputDevice.defaultOptions.autoFocusable and has "mousedown", "pointerdown"
78
+
79
+ Device gesture | Keyboard (primary) | Keyboard (alt) | Gamepad
80
+ -----------------|--------------------|-----------------|------------------
81
+ `"moveFocusLeft"` | Left Arrow Key | A Key | Left Stick Left
82
+ `"moveFocusRight"` | Right Arrow Key | D Key | Left Stick Right
83
+ `"moveFocusUp"` | Up Arrow Key | W Key | Left Stick Up
84
+ `"moveFocusDown"` | Down Arrow Key | S Key | Left Stick Down
85
+ `"focusover"` | Return Key | Space | A Button
86
+ `"moveUpOneLevel"` | Escape Key | Backspace | B Button
87
+
88
+
89
+ ### Global defaults:
90
+
91
+ ```ts
92
+ InputDevice.defaultOptions = {
93
+ /** Globally enable/disable the navigation API. (i.e. if the browser loses focus). */
94
+ focusEnabled: true,
95
+ /**
96
+ * (default: true) When enabled, any element with "mousedown" or "pointerdown"
97
+ * is considered focusable. The "focusableTransform" will also apply.
98
+ */
99
+ autoFocusable: true,
100
+ focusableTransform: { x: 5, y: 5 },
101
+ keyboard: {
102
+ enabled: true,
103
+ layouts: [ "qwerty", "azerty", "jcuken", "qwertz" ],
104
+ autoLanguageLayout: true, // fr*/nl-BE* -> azerty, uk*/ru* -> jcuken
105
+ internationalization: {
106
+ /** when true, labels are mapped to their layout */
107
+ mapLabels: true,
108
+ }
109
+ },
110
+ gamepad: {
111
+ enabled: true,
112
+ layouts: [ "standard", "nintendo" ],
113
+ firstIntentCooldownMs: 400,
114
+ intentCooldownMs: 100,
115
+ },
116
+ }
117
+ ```
118
+
119
+ ```ts
120
+ class InputDevice {
121
+
122
+ }
123
+
124
+ ```
125
+
126
+
127
+ <hr/>
128
+
129
+ <hr/>
130
+
131
+
132
+ ⚡ Powerful, high-performance animations for PixiJS
133
+
134
+ | | |
135
+ | ------ | ------ |
136
+ | 🔮 Simple, declarative API | 🎬 Based on [Cocos2d](https://docs.cocos2d-x.org/cocos2d-x/v3/en/actions/getting_started.html)/[SKActions](https://developer.apple.com/documentation/spritekit/getting_started_with_actions) |
137
+ | 🚀 35+ [built-in actions](#action-initializers), 30+ [timing modes](#timing-modes) | 🔀 Reuseable, chainable & reversible |
138
+ | 🍃 No dependencies & tree-shakeable | ⌚ Full speed/pausing control |
139
+ | 🤏 `~4.3kb` minzipped | ✨ Supports PixiJS 8+, 7+, 6.3+ |
140
+
141
+
142
+ ## Sample Usage
143
+
144
+ *Create, configure, and run animations & actions.*
145
+
146
+ ```ts
147
+ // Define an action
148
+ const spinAndRemove = Action.sequence([
149
+ Action.rotateByDegrees(360, 0.2).easeInOut(),
150
+ Action.fadeOut(0.2).easeIn(),
151
+ Action.removeFromParent(),
152
+ Action.run(() => console.info('✨ done!'))
153
+ ]);
154
+
155
+ // Run an action
156
+ mySprite.run(spinAndRemove);
157
+ ```
158
+
159
+ ## Getting Started with PixiJS Actions
160
+
161
+ *Everything you need to quickly build beautiful animations.*
162
+
163
+ **PixiJS Actions** is based off the idiomatic and expressive [**SKActions API**](https://developer.apple.com/documentation/spritekit/getting_started_with_actions), extending `Container` to add first-class support for running and managing actions.
164
+
165
+ The core concepts are:
166
+
167
+ 1. **Nodes:** _Any container (e.g. `Container`, `Sprite`, `Graphics`)_
168
+ 2. **Actions:** _Stateless, reusable recipes_ (e.g. animations, triggers, and more)
169
+ 3. **TimingMode & speed:** _Controls for the speed & smoothness of actions and animations_
170
+
171
+ > [!NOTE]
172
+ > _See [Timing Modes](#timing-modes) and [Manipulating Action Speed](#manipulating-action-speed) for more information._
173
+
174
+
175
+ ## Installation
176
+
177
+ *Quick start guide.*
178
+
179
+ **1.** Install the latest `pixijs-input-devices` package:
180
+
181
+ ```sh
182
+ # npm
183
+ npm install pixijs-input-devices -D
184
+
185
+ # yarn
186
+ yarn add pixijs-input-devices --dev
187
+ ```
188
+
189
+ **2.** Register the mixin & ticker:
190
+
191
+ ```ts
192
+ import * as PIXI from 'pixi.js';
193
+ import { Action, registerPixiJSActionsMixin } from 'pixijs-input-devices';
194
+
195
+ // register container mixin
196
+ registerPixiJSActionsMixin(PIXI.Container);
197
+
198
+ // register `Action.tick(...)` with shared ticker
199
+ Ticker.shared.add(ticker => Action.tick(ticker.elapsedMS));
200
+ ```
201
+
202
+ > [!TIP]
203
+ > **PixiJS 7 / 6.3+:**
204
+ >
205
+ > ```ts
206
+ > Ticker.shared.add(() => Action.tick(Ticker.shared.elapsedMS));
207
+ > // or
208
+ > Ticker.shared.add((dt) => Action.tick(dt));
209
+ > ```
210
+
211
+ > [!NOTE]
212
+ > _If not using a PixiJS ticker, then just put `Action.tick(elapsedMs)` in the appropriate equivalent place (i.e. your `requestAnimationFrame()` render loop)._
213
+
214
+ **3.** Done!
215
+
216
+ ✨ You are now ready to run your first action!
217
+
218
+ ## Running Actions
219
+
220
+ *Running actions in your canvas.*
221
+
222
+ ```ts
223
+ // Hide me instantly!
224
+ mySprite.run(Action.hide(), () => {
225
+ console.log('where did I go?');
226
+ });
227
+ ```
228
+
229
+ Nodes are extended with a few new methods and properties to make it easy to interact with actions.
230
+
231
+ | Property | Description |
232
+ | :----- | :------ |
233
+ | `speed` | A speed modifier applied to all actions executed by the node and its descendants. Defaults to `1.0`. |
234
+ | `isPaused` | A boolean value that determines whether actions on the node and its descendants are processed. Defaults to `false`. |
235
+
236
+ | Method | Description |
237
+ | :----- | :------ |
238
+ | `run(action)` | Run an action. |
239
+ | `run(action, completion)` | Run an action with a completion handler. |
240
+ | `runWithKey(action, withKey)` | Run an action, and store it so it can be retrieved later. |
241
+ | `runAsPromise(action): Promise<void>` | Run an action as a promise. |
242
+ | `action(forKey): Action \| undefined` | Return an action associated with a specified key. |
243
+ | `hasActions(): boolean` | Return a boolean indicating whether the node is executing actions. |
244
+ | `removeAllActions(): void` | End and removes all actions from the node. |
245
+ | `removeAction(forKey): void` | Remove an action associated with a specified key. |
246
+
247
+ ### Running Identifiable Actions
248
+
249
+ ```ts
250
+ // Repeat an action forever!
251
+ const spin = Action.repeatForever(Action.rotateBy(5, 1.0));
252
+ mySprite.runWithKey(spin, 'spinForever');
253
+
254
+ // Or remove it later.
255
+ mySprite.removeAction('spinForever');
256
+ ```
257
+
258
+ ### Pausing All Actions
259
+
260
+ ```ts
261
+ mySprite.isPaused = true;
262
+ // All actions will stop running.
263
+ ```
264
+
265
+ ### Manipulating Action Speed
266
+
267
+ Speed can be manipulated on both actions and nodes.
268
+
269
+ ```ts
270
+ const moveAction = Action.moveByX(10, 4.0);
271
+ moveAction.speed = 2.0;
272
+ // moveAction will now take only 2 seconds instead of 4.
273
+
274
+ const repeatAction = Action.repeat(moveAction, 5);
275
+ repeatAction.speed = 2.0;
276
+ // Each moveAction will only take 1 second, for a total of 5 seconds.
277
+
278
+ mySprite.run(moveAction);
279
+ mySprite.speed = 2.0;
280
+ // mySprite is running at 2x speed!
281
+ // The entire action should now take ~2.5 seconds.
282
+
283
+ mySprite.parent!.speed = 1 / 4;
284
+ // Now we've slowed down mySprite's parent.
285
+ // The entire action will now take ~10 seconds.
286
+ ```
287
+
288
+ > [!NOTE]
289
+ > Changes to nodes' `speed` will take effect immediately, however changes to an `Action` initializer's `speed` or `timingMode` will not affect any actions that have already begun running.
290
+
291
+ ## Action Initializers
292
+
293
+ *Combine these initializers to create expressive animations and behaviors.*
294
+
295
+ Most actions implement specific predefined animations that are ready to use. If your animation needs fall outside of the suite provided here, then you should implement a custom action (see [Creating Custom Actions](#creating-custom-actions)).
296
+
297
+ | Action | Description | Reversible? |
298
+ | :----- | :---------- | :---------- |
299
+ |***Chaining Actions***|||
300
+ | `Action.group(actions)` | Run multiple actions in parallel. | Yes |
301
+ | `Action.sequence(actions)` | Run multiple actions sequentially. | Yes |
302
+ | `Action.repeat(action, count)` | Repeat an action a specified number of times. | Yes |
303
+ | `Action.repeatForever(action)` | Repeat an action indefinitely. | Yes |
304
+ |***Animating a Node's Position in a Linear Path***|||
305
+ | `Action.moveBy(vector, duration)` | Move a node by a relative vector `{ x, y }` (e.g. `PIXI.Point`). | Yes |
306
+ | `Action.moveBy(dx, dy, duration)` | Move a node by relative values. | Yes |
307
+ | `Action.moveByX(dx, duration)` | Move a node horizontally by a relative value. | Yes |
308
+ | `Action.moveByY(dy, duration)` | Move a node vertically by a relative value. | Yes |
309
+ | `Action.moveTo(position, duration)` | Move a node to a specified position `{ x, y }` (e.g. `PIXI.Point`, `PIXI.Container`). | _*No_ |
310
+ | `Action.moveTo(x, y, duration)` | Move a node to a specified position. | _*No_ |
311
+ | `Action.moveToX(x, duration)` | Move a node to a specified horizontal position. | _*No_ |
312
+ | `Action.moveToY(y, duration)` | Move a node to a specified vertical position. | _*No_ |
313
+ |***Animating a Node's Position Along a Custom Path***|||
314
+ | `Action.follow(path, duration)` | Move a node along a path, optionally orienting the node to the path. | Yes | Yes |
315
+ | `Action.followAtSpeed(path, speed)` | Move a node along a path at a specified speed, optionally orienting the node to the path. | Yes |
316
+ |***Animating the Rotation of a Node***|||
317
+ | `Action.rotateBy(delta, duration)` | Rotate a node by a relative value (in radians). | Yes |
318
+ | `Action.rotateByDegrees(delta, duration)` | Rotate a node by a relative value (in degrees). | Yes |
319
+ | `Action.rotateTo(radians, duration)` | Rotate a node to a specified value (in radians). | _*No_ |
320
+ | `Action.rotateToDegrees(degrees, duration)` | Rotate a node to a specified value (in degrees). | _*No_ |
321
+ |***Animating the Scaling of a Node***|||
322
+ | `Action.scaleBy(vector, duration)` | Scale a node by a relative vector `{ x, y }` (e.g. `PIXI.Point`). | Yes |
323
+ | `Action.scaleBy(scale, duration)` | Scale a node by a relative value. | Yes |
324
+ | `Action.scaleBy(dx, dy, duration)` | Scale a node in each axis by relative values. | Yes |
325
+ | `Action.scaleByX(dx, duration)` | Scale a node horizontally by a relative value. | Yes |
326
+ | `Action.scaleByY(dy, duration)` | Scale a node vertically by a relative value. | Yes |
327
+ | `Action.scaleTo(size, duration)` | Scale a node to achieve a specified size `{ width, height }` (e.g. `PIXI.ISize`, `PIXI.Container`). | _*No_ |
328
+ | `Action.scaleTo(scale, duration)` | Scale a node to a specified value. | _*No_ |
329
+ | `Action.scaleTo(x, y, duration)` | Scale a node in each axis to specified values. | _*No_ |
330
+ | `Action.scaleToX(x, duration)` | Scale a node horizontally to a specified value. | _*No_ |
331
+ | `Action.scaleToY(y, duration)` | Scale a node vertically to a specified value. | _*No_ |
332
+ |***Animating the Transparency of a Node***|||
333
+ | `Action.fadeIn(duration)` | Fade the alpha to `1.0`. | Yes |
334
+ | `Action.fadeOut(duration)` | Fade the alpha to `0.0`. | Yes |
335
+ | `Action.fadeAlphaBy(delta, duration)` | Fade the alpha by a relative value. | Yes |
336
+ | `Action.fadeAlphaTo(alpha, duration)` | Fade the alpha to a specified value. | _*No_ |
337
+ |***Controlling a Node's Visibility***|||
338
+ | `Action.unhide()` | Set a node's `visible` property to `true`. | Yes |
339
+ | `Action.hide()` | Set a node's `visible` property to `false`. | Yes |
340
+ |***Removing a Node from the Canvas***|||
341
+ | `Action.removeFromParent()` | Remove a node from its parent. | _†Identical_ |
342
+ |***Running Actions on Children***|||
343
+ | `Action.runOnChild(nameOrLabel, action)` | Add an action to a child node. | Yes |
344
+ |***Delaying Actions***|||
345
+ | `Action.waitForDuration(duration)` | Idle for a specified period of time. | _†Identical_ |
346
+ | `Action.waitForDurationWithRange(duration, range)` | Idle for a randomized period of time. | _†Identical_ |
347
+ |***Triggers and Custom Actions***|||
348
+ | `Action.run(callback)` | Execute a block (i.e. trigger another action). | _†Identical_ |
349
+ | `Action.customAction(duration, stepHandler)` | Execute a custom stepping function over the action duration. | _†Identical_ |
350
+ |***Manipulating the Action Speed of a Node***|||
351
+ | `Action.speedBy(delta, duration)` | Change how fast a node executes its actions by a relative value. | Yes |
352
+ | `Action.speedTo(speed, duration)` | Set how fast a node executes actions to a specified value. | _*No_ |
353
+
354
+ > [!IMPORTANT]
355
+ > #### Reversing Actions
356
+ > Every action initializer has a `.reversed()` method which will return a new action. Some actions are **not reversible**, and these cases are noted in the table above:
357
+ > - _**†Identical**_ &mdash; The reversed action is identical to the original action.
358
+ > - _**\*No**_ &mdash; The reversed action will idle for the equivalent duration.
359
+
360
+ ### Action Chaining
361
+
362
+ Many actions can be joined together using `Action.sequence()`, `Action.group()`, `Action.repeat()` and `Action.repeatForever()` to quickly create complex animations:
363
+
364
+ ```ts
365
+ import { Action } from 'pixijs-input-devices';
366
+
367
+ // Expand and contract smoothly over 2 seconds
368
+ const pulsate = Action.sequence([
369
+ Action.scaleTo(1.5, 1.0).easeOut(),
370
+ Action.scaleTo(1, 1.0).easeIn()
371
+ ]);
372
+
373
+ // Follow a complex path (e.g. a bezier curve)
374
+ const path = [
375
+ { x: 0, y: 0 },
376
+ { x: 100, y: 0 },
377
+ { x: 100, y: 100 },
378
+ { x: 200, y: 200 }
379
+ ];
380
+ const followPath = Action.follow(path, 5.0);
381
+
382
+ // Create a 10 second loop that goes back and forth
383
+ const moveBackAndForthWhilePulsating = Action.group([
384
+ Action.repeat(pulsate, 5),
385
+ Action.sequence([followPath, followPath.reversed()]),
386
+ ]);
387
+
388
+ // ✨ Animate continuously
389
+ mySprite.run(Action.repeatForever(moveBackAndForthWhilePulsating));
390
+ ```
391
+
392
+ ## Timing Modes
393
+
394
+ Every action has a `timingMode` which controls the timing curve of its execution.
395
+
396
+ The default timingMode for all actions is `TimingMode.linear`, which causes an animation to occur evenly over its duration.
397
+
398
+ You can customize the speed curve of actions in many ways:
399
+
400
+ ```ts
401
+ // Default easings:
402
+ Action.fadeIn(0.3).easeIn();
403
+ Action.fadeIn(0.3).easeOut();
404
+ Action.fadeIn(0.3).easeInOut();
405
+
406
+ // Set a specific TimingMode:
407
+ Action.fadeIn(0.3).setTimingMode(TimingMode.easeInOutCubic);
408
+
409
+ // Set a custom timing function:
410
+ Action.fadeIn(0.3).setTimingMode(x => x * x);
411
+ ```
412
+
413
+ > [!IMPORTANT]
414
+ > **Timing Mutators:** The `.easeIn()`, `.easeOut()`, `.easeInOut()`, `setTimingMode(…)`, `setSpeed(…)` methods mutate the underlying action.
415
+
416
+ ### Built-in TimingMode Options
417
+
418
+ See the following table for default `TimingMode` options.
419
+
420
+ | Pattern | Ease In, Ease Out | Ease In | Ease Out | Description |
421
+ | --------------- | ----- | -- | --- | ----------- |
422
+ | **Linear** | `linear` | - | - | Constant motion with no acceleration or deceleration. |
423
+ | **Sine** | `easeInOutSine` | `easeInSine` | `easeOutSine` | Gentle start and end, with accelerated motion in the middle. |
424
+ | **Circular** | `easeInOutCirc` | `easeInCirc` | `easeOutCirc` | Smooth start and end, faster acceleration in the middle, circular motion. |
425
+ | **Cubic** | `easeInOutCubic` | `easeInCubic` | `easeOutCubic` | Gradual acceleration and deceleration, smooth motion throughout. |
426
+ | **Quadratic** | `easeInOutQuad` | `easeInQuad` | `easeOutQuad` | Smooth acceleration and deceleration, starts and ends slowly, faster in the middle. |
427
+ | **Quartic** | `easeInOutQuart` | `easeInQuart` | `easeOutQuart` | Slower start and end, increased acceleration in the middle. |
428
+ | **Quintic** | `easeInOutQuint` | `easeInQuint` | `easeOutQuint` | Very gradual start and end, smoother acceleration in the middle. |
429
+ | **Exponential** | `easeInOutExpo` | `easeInExpo` | `easeOutExpo` | Very slow start, exponential acceleration, slow end. |
430
+ | **Back** | `easeInOutBack` | `easeInBack` | `easeOutBack` | Starts slowly, overshoots slightly, settles into final position. |
431
+ | **Bounce** | `easeInOutBounce` | `easeInBounce` | `easeOutBounce` | Bouncy effect at the start or end, with multiple rebounds. |
432
+ | **Elastic** | `easeInOutElastic` | `easeInElastic` | `easeOutElastic` | Stretchy motion with overshoot and multiple oscillations. |
433
+
434
+ ### Default Timing Modes
435
+
436
+ The `.easeIn()`, `.easeOut()`, `.easeInOut()`, and `.linear()` mutator methods on `Action` instances will set the timing mode of that action to the global default timing mode for that curve type.
437
+
438
+ | TimingMode mutator | Global setting | Default value |
439
+ | :--- | :--- | :--- |
440
+ | `action.easeIn()` | `Action.DefaultTimingModeEaseIn` | `TimingMode.easeInSine` |
441
+ | `action.easeOut()` | `Action.DefaultTimingModeEaseOut` | `TimingMode.easeOutSine` |
442
+ | `action.easeInOut()` | `Action.DefaultTimingModeEaseInOut` | `TimingMode.easeInOutSine` |
443
+ | `action.linear()` | _(n/a)_ | `TimingMode.linear` |
444
+
445
+ Global default timing modes can be set like so:
446
+
447
+ ```ts
448
+ // set default
449
+ Action.DefaultTimingModeEaseIn = TimingMode.easeInQuad;
450
+
451
+ // apply
452
+ myNode.run(myAction.easeIn());
453
+
454
+ myAction.timingMode
455
+ // TimingMode.easeInQuad
456
+ ```
457
+
458
+ ## Creating Custom Actions
459
+
460
+ Beyond combining chaining actions like `sequence()`, `group()`, `repeat()` and `repeatForever()`, you can provide code that implements your own action.
461
+
462
+ ### Composite Actions
463
+
464
+ Actions are stateless and reusable, so you can create complex animations once, and then run them on many nodes.
465
+
466
+ ```ts
467
+ /** A nice gentle rock back and forth. */
468
+ const rockBackAndForth = Action.repeatForever(
469
+ Action.group([
470
+ Action.sequence([
471
+ Action.moveByX(5, 0.33).easeOut(),
472
+ Action.moveByX(-10, 0.34).easeInOut(),
473
+ Action.moveByX(5, 0.33).easeIn(),
474
+ ]),
475
+ Action.sequence([
476
+ Action.rotateByDegrees(-2, 0.33).easeOut(),
477
+ Action.rotateByDegrees(4, 0.34).easeInOut(),
478
+ Action.rotateByDegrees(-2, 0.33).easeIn(),
479
+ ]),
480
+ ])
481
+ );
482
+
483
+ // Run it over here
484
+ someSprite.run(rockBackAndForth);
485
+
486
+ // Run it somewhere else
487
+ someOtherContainer.run(rockBackAndForth);
488
+ ```
489
+
490
+ You can combine these with dynamic actions for more variety:
491
+
492
+ ```ts
493
+ const MyActions = {
494
+ squash: (amount: number, duration: number = 0.3) => Action.sequence([
495
+ Action.scaleTo(amount, 1 / amount, duration / 2).easeOut(),
496
+ Action.scaleTo(1, duration / 2).easeIn()
497
+ ]),
498
+ stretch: (amount: number, duration: number = 0.3) => Action.sequence([
499
+ Action.scaleTo(1 / amount, amount, duration / 2).easeOut(),
500
+ Action.scaleTo(1, duration / 2).easeIn()
501
+ ]),
502
+ squashAndStretch: (amount: number, duration: number = 0.3) => Action.sequence([
503
+ MyActions.squash(amount, duration / 2),
504
+ MyActions.stretch(amount, duration / 2),
505
+ ]),
506
+ };
507
+
508
+ // Small squish!
509
+ mySprite.run(MyActions.squashAndStretch(1.25));
510
+
511
+ // Big squish!
512
+ mySprite.run(MyActions.squashAndStretch(2.0));
513
+ ```
514
+
515
+ ### Custom Action (Basic)
516
+
517
+ You can use the built-in `Action.customAction(duration, stepHandler)` to provide custom actions:
518
+
519
+ ```ts
520
+ const rainbowColors = Action.customAction(5.0, (target, t, dt) => {
521
+ // Calculate color based on time "t".
522
+ const colorR = Math.sin(0.3 * t + 0) * 127 + 128;
523
+ const colorG = Math.sin(0.3 * t + 2) * 127 + 128;
524
+ const colorB = Math.sin(0.3 * t + 4) * 127 + 128;
525
+
526
+ // Apply random color with time-based variation.
527
+ target.tint = (colorR << 16) + (colorG << 8) + colorB;
528
+ });
529
+
530
+ // Start rainbow effect
531
+ mySprite.runWithKey(Action.repeatForever(rainbowColors), 'rainbow');
532
+
533
+ // Stop rainbow effect
534
+ mySprite.removeAction('rainbow');
535
+ ```
536
+
537
+ > **Step functions:**
538
+ > - `target` = The node the aciton is runnning against.
539
+ > - `t` = Progress of time from 0 to 1, which has been passed through the `timingMode` function.
540
+ > - `dt` = delta/change in `t` since last step. Use for relative actions.
541
+ >
542
+ > _Note: `t` can be outside of 0 and 1 in timing mode functions which overshoot, such as `TimingMode.easeInOutBack`._
543
+
544
+ This function will be called as many times as the renderer asks over the course of its duration.
545
+
546
+ ### Custom Action (with State)
547
+
548
+ Here is a practical example:
549
+
550
+ ```ts
551
+ // Create a custom action that relies on
552
+ // state (radius, inital target position).
553
+ const makeOrbitAction = (
554
+ radius: number,
555
+ duration: number
556
+ ): Action => {
557
+ let startPos: PIXI.IPointData;
558
+
559
+ return Action.customAction(duration, (target, t, td) => {
560
+ if (!startPos) {
561
+ // Capture on first run
562
+ startPos = { x: target.x, y: target.y };
563
+ }
564
+
565
+ const angle = Math.PI * 2 * t;
566
+
567
+ target.position.set(
568
+ startPos.x + radius * Math.cos(angle),
569
+ startPos.y + radius * Math.sin(angle)
570
+ );
571
+ });
572
+ };
573
+
574
+ // Run the custom action
575
+ mySprite.run(
576
+ Action.repeatForever(makeOrbitAction(10, 15.0))
577
+ );
578
+ ```
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "pixijs-input-devices",
3
+ "version": "0.1.0",
4
+ "author": "Reece Como <reece.como@gmail.com>",
5
+ "authors": [
6
+ "Reece Como <reece.como@gmail.com>"
7
+ ],
8
+ "repository": "https://github.com/reececomo/pixijs-input-devices",
9
+ "homepage": "https://github.com/reececomo/pixijs-input-devices#readme",
10
+ "license": "MIT",
11
+ "description": "Keyboard and Gamepad interactivity APIs for PixiJS 6, 7, 8+",
12
+ "main": "dist/index.cjs",
13
+ "module": "dist/index.mjs",
14
+ "types": "./dist/index.d.ts",
15
+ "files": ["./dist"],
16
+ "scripts": {
17
+ "build:rollup": "rimraf dist && echo 'rollup (1/2):' && rollup -c --bundleConfigAsCjs",
18
+ "build:rm-dts": "rimraf dist/*.d.ts dist/actions dist/lib",
19
+ "build:dts-gen": "echo 'dts-bundle-generator (2/2):' && ./node_modules/.bin/dts-bundle-generator -o dist/index.d.ts src/index.ts --sort --no-banner --export-referenced-types --external-imports pixi.js --no-check",
20
+ "build:export-globals": "(cat src/globals.d.ts && cat dist/index.d.ts) > tmp.d.ts && mv tmp.d.ts dist/index.d.ts",
21
+ "build": "npm run build:rollup && npm run build:rm-dts && npm run build:dts-gen && npm run build:export-globals",
22
+ "coverage": "jest --runInBand --collectCoverage",
23
+ "lint": "eslint src --ext .ts",
24
+ "lint:fix": "eslint src --ext .ts --fix",
25
+ "test": "jest --runInBand"
26
+ },
27
+ "peerDependencies": {
28
+ "pixi.js": "^6.3.0 || ^7.0.0 || ^8.0.0"
29
+ },
30
+ "devDependencies": {
31
+ "@rollup/plugin-commonjs": "^26.0.1",
32
+ "@rollup/plugin-node-resolve": "^15.2.3",
33
+ "@rollup/plugin-terser": "^0.4.4",
34
+ "@rollup/plugin-typescript": "^11.1.6",
35
+ "@types/jest": "^29.2.6",
36
+ "@typescript-eslint/eslint-plugin": "^7.1.0",
37
+ "@typescript-eslint/parser": "^7.1.0",
38
+ "dts-bundle-generator": "^9.5.1",
39
+ "eslint-plugin-disable-autofix": "^4.2.0",
40
+ "eslint": "^8.57.0",
41
+ "jest": "^29.3.1",
42
+ "pixi.js": "6.3.x",
43
+ "rimraf": "^6.0.1",
44
+ "rollup": "^4.20.0",
45
+ "ts-jest": "^29.0.5",
46
+ "tslib": "^2.6.3",
47
+ "typescript": "4.9.5"
48
+ },
49
+ "keywords": [
50
+ "actions",
51
+ "animate",
52
+ "animation",
53
+ "interpolation",
54
+ "lerp",
55
+ "phaser",
56
+ "pixi-action",
57
+ "pixi",
58
+ "pixijs",
59
+ "skaction",
60
+ "transition",
61
+ "tween",
62
+ "tweening"
63
+ ]
64
+ }