## Getting Started with PixiJS and TypeScript for Game Dev
PixiJS is a powerhouse for 2D web graphics, leveraging WebGL for buttery-smooth rendering. Pairing it with TypeScript supercharges your workflow with type safety, better IDE support, and fewer runtime bugs. Whether you're crafting a simple platformer or a complex RPG, these rules will guide you from novice to ninja.
For official docs and source, check out the [PixiJS GitHub repo](https://github.com/pixijs/pixijs). You'll also find tons of inspiration in the [PixiJS examples repo](https://github.com/pixijs/examples).
### Why These Rules Matter
These guidelines are battle-tested for use with AI tools like Cursor, ensuring consistent, performant code. They emphasize modularity, performance, and modern TypeScript features. Follow them to avoid common pitfalls like memory leaks or unresponsive games.
## Core Setup Rules: Lay a Solid Foundation
### 1. Always Initialize with PixiJS Application
Kick off every project with a typed PixiJS Application. This handles the renderer, ticker, and stage automatically.
```typescript
import * as PIXI from 'pixi.js';
const app = new PIXI.Application({
width: 800,
height: 600,
backgroundColor: 0x1099bb,
antialias: true,
});
document.body.appendChild(app.view as HTMLCanvasElement);
```
**Pro Tip:** Use `resizeTo` for responsive games: `app.stage.hitArea = app.renderer.screen;` to enable full-screen interactions.
### 2. Embrace Containers for Organization
Group sprites, text, and effects into Containers. They're like folders for your scene graph, making updates and destruction efficient.
```typescript
const playerContainer = new PIXI.Container();
app.stage.addChild(playerContainer);
// Add children
playerContainer.addChild(playerSprite);
playerContainer.addChild(healthBar);
```
Containers support pivots for rotation around centers—crucial for characters and UI.
### 3. Load Assets Properly with Loaders
Never hardcode assets. Use `PIXI.Assets` for async loading with progress tracking.
```typescript
await PIXI.Assets.load([
{ alias: 'player', src: 'player.png' },
{ alias: 'bg', src: 'background.jpg' },
]);
const playerTexture = PIXI.Assets.get('player');
```
**Beginner Note:** Aliases prevent typos. For atlases, load JSON + PNG together.
## Sprite and Texture Mastery
### 4. Create Sprites from Textures Only
Sprites are your workhorses. Instantiate from loaded textures for optimal caching.
```typescript
const sprite = new PIXI.Sprite(playerTexture);
sprite.anchor.set(0.5); // Center pivot
playerContainer.addChild(sprite);
```
Set `anchor` early for consistent positioning. Use `scale` over resizing source images.
### 5. Handle Animations with Sprite Sheets
For smooth animations, parse sprite sheets. Recommend [SpriteSheetAnimator](https://github.com/ourcade/spriteSheetAnimator) for frame-by-frame control.
```typescript
import SpriteSheetAnimator from 'spritesheet-animator';
const animator = new SpriteSheetAnimator(textures);
playerContainer.addChild(animator.sprite);
animator.gotoAndPlay(0);
```
**Advanced:** Sync with `app.ticker` for frame-rate independent playback.
## UI and Text Essentials
### 6. Use TextMetrics for Dynamic Text
PIXI.Text is great, but measure with `PIXI.TextMetrics.measureText()` for perfect fitting.
```typescript
const style = new PIXI.TextStyle({ fontSize: 24, fill: 0xffffff });
const text = new PIXI.Text('Score: 1000', style);
text.anchor.set(1, 0); // Right-align
```
For bitmaps, use BitmapText—faster and scalable.
### 7. Build Menus with Graphics and Containers
Draw buttons with `PIXI.Graphics` for vectors.
```typescript
const button = new PIXI.Graphics();
button.beginFill(0x00ff00);
button.drawRoundedRect(0, 0, 200, 50, 10);
button.endFill();
button.interactive = true;
button.buttonMode = true;
```
Add Text as child and handle `pointertap` events.
## Input and Interactivity
### 8. Enable Interactions Globally
Set `app.stage.interactive = true;` once. Use event modes like `'static'` for performance.
```typescript
sprite.eventMode = 'static';
sprite.cursor = 'pointer';
sprite.on('pointerdown', () => jump());
```
**Real-World:** For mobile, add `pointerover` simulations with touches.
### 9. Keyboard and Gamepad Support
Track keys with a custom manager:
```typescript
const keys = {
ArrowLeft: false,
};
window.addEventListener('keydown', (e) => keys[e.key] = true);
window.addEventListener('keyup', (e) => keys[e.key] = false);
// In ticker
if (keys.ArrowLeft) player.x -= 5;
```
Extend to Gamepad API for consoles.
## Performance Optimization Rules
### 10. Leverage Ticker for Updates
Use `app.ticker.add()` for game loops. Pass deltaTime for smooth 60fps.
```typescript
let speed = 200;
app.ticker.add((delta) => {
player.x += speed * delta;
});
```
**Pitfall Alert:** Remove listeners on destroy to prevent leaks.
### 11. Batching and Sorting
Call `app.stage.sortChildren()` if z-order changes. Use `renderable` flags to skip hidden objects.
### 12. Particles and Filters
PIXI.ParticleContainer for hordes of enemies. Filters like DisplacementFilter for water effects.
```typescript
const particles = new PIXI.ParticleContainer(1000, {
scale: true,
position: true,
});
```
Limit to 10k particles max.
## State Management and Scenes
### 13. Implement Scene Stacking
Create a SceneManager class:
```typescript
class SceneManager {
private currentScene: PIXI.Container;
changeScene(newScene: PIXI.Container) {
if (this.currentScene) app.stage.removeChild(this.currentScene);
this.currentScene = newScene;
app.stage.addChild(newScene);
}
}
```
**Advanced Value:** Add transitions with Tweens (use GSAP or PixiJS built-ins).
### 14. Collision Detection
Use SAT or simple AABB:
```typescript
function checkCollision(a: PIXI.Sprite, b: PIXI.Sprite): boolean {
return a.x < b.x + b.width && a.x + a.width > b.x &&
a.y < b.y + b.height && a.y + a.height > b.y;
}
```
For precision, leverage PixiJS Graphics intersection.
## Audio and Effects
### 15. Integrate Howler.js or Web Audio
PixiJS doesn't handle sound—pair with Howler for spatial audio.
```typescript
import { Howl } from 'howler';
const jumpSound = new Howl({ src: ['jump.mp3'] });
jumpSound.play();
```
Sync volumes with PIXI.SimpleRope for trails.
## Advanced Techniques: Level Up
### Custom Shaders
Write GLSL for post-processing:
```glsl
precision mediump float;
uniform vec2 u_resolution;
void main() {
vec2 uv = gl_FragCoord.xy / u_resolution;
gl_FragColor = vec4(uv, 0.0, 1.0);
}
```
Load via `PIXI.Filter`.
### Spine and DragonBones
For skeletal animations, import runtimes. Follow PixiJS plugins.
### Physics Integration
Hook Matter.js or Planck.js:
```typescript
import Matter from 'matter-js';
const engine = Matter.Engine.create();
```
Update positions from bodies to sprites.
## Deployment and Best Practices
- Bundle with Vite + tsx for fast HMR.
- Minify assets with TexturePacker.
- Test on low-end devices—target 60fps.
- Version PixiJS at ^8.0.0 for stability.
**Final Tip:** Prototype fast, profile often with PixiJS dev tools. Share your games on itch.io!
These rules scale from a Pong clone to full titles. Experiment, iterate, and have fun building!
<div style="text-align: center; margin-top: 2rem;">
<a href="https://cursor.directory/pixijs-typescript-game-development-rules" target="_blank" rel="noopener noreferrer" class="view-full-resource-btn" style="display: inline-block; background-color: #f97316; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; transition: background-color 0.2s;">View Full Resource</a>
</div>