Index of every page on this site: llms.txt
All skills
Run it yourself

Build 2D games with Phaser 3 framework. Covers scene lifecycle, sprites, physics (Arcade/Matter), tilemaps, animations, input handling, and game architecture. Trigger: "create phaser game", "add phaser scene", "phaser sprite", "phaser physics", "game development with phaser".

Use this Skill: https://skilld.dev/gh/superstone-han/dotfiles/phaser-gamedev

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesperformance.md

≈2k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Performance Optimization

Strategies for maintaining smooth 60fps in Phaser 3 games.

Object Pooling

The most impactful optimization for games with many spawning/despawning objects.

Why Pool?

Creating/destroying objects causes:

  • Memory allocation overhead
  • Garbage collection pauses (stutters)
  • Texture rebinding costs

Implementation Pattern

class BulletPool {
  constructor(scene) {
    this.scene = scene;
    this.pool = scene.physics.add.group({
      defaultKey: 'bullet',
      maxSize: 100,
      runChildUpdate: true
    });
  }

  spawn(x, y, velocityX, velocityY) {
    const bullet = this.pool.get(x, y);

    if (!bullet) return null;  // Pool exhausted

    bullet.setActive(true);
    bullet.setVisible(true);
    bullet.body.enable = true;
    bullet.body.reset(x, y);
    bullet.setVelocity(velocityX, velocityY);

    return bullet;
  }

  kill(bullet) {
    bullet.setActive(false);
    bullet.setVisible(false);
    bullet.body.enable = false;
    bullet.body.stop();
  }
}

// Usage
this.bulletPool = new BulletPool(this);

// Spawn
const bullet = this.bulletPool.spawn(player.x, player.y, 500, 0);

// Kill (in collision callback or update)
this.bulletPool.kill(bullet);

Built-in Group Pooling

// Configure group for pooling
const enemies = this.physics.add.group({
  maxSize: 50,
  classType: Enemy,
  createCallback: (enemy) => {
    enemy.setName('enemy' + enemies.getLength());
  },
  removeCallback: (enemy) => {
    enemy.setName('');
  }
});

// Get inactive member (or create if under maxSize)
const enemy = enemies.get(x, y);

// Return to pool (don't destroy)
enemy.setActive(false);
enemy.setVisible(false);

Texture Atlases

Combine sprites into atlases to reduce draw calls.

Why Atlases?

  • Single texture bind per atlas
  • Reduced HTTP requests
  • Better GPU memory usage

Using TexturePacker

Export as Phaser 3 JSON Hash format.

// Load atlas
this.load.atlas('sprites', 'atlas/sprites.png', 'atlas/sprites.json');

// Use frames
this.add.sprite(x, y, 'sprites', 'player-idle-1');

// Animation from atlas
this.anims.create({
  key: 'walk',
  frames: this.anims.generateFrameNames('sprites', {
    prefix: 'player-walk-',
    start: 1,
    end: 8,
    zeroPad: 2
  }),
  frameRate: 10,
  repeat: -1
});

Camera Culling

Only render what's visible.

Automatic Culling

Phaser culls off-camera objects by default for:

  • Sprites
  • Images
  • TileSprites

Disable if needed:

sprite.setScrollFactor(0);  // Fixed to camera (no culling)

Manual Culling for Custom Objects

update() {
  const cam = this.cameras.main;
  const bounds = cam.worldView;

  this.enemies.children.iterate(enemy => {
    if (Phaser.Geom.Rectangle.Contains(bounds, enemy.x, enemy.y)) {
      enemy.setActive(true);
      enemy.setVisible(true);
    } else {
      enemy.setActive(false);
      enemy.setVisible(false);
    }
  });
}

Physics Optimization

Reduce Collision Checks

// Only check relevant collisions
this.physics.add.collider(player, groundLayer);
this.physics.add.collider(enemies, groundLayer);
this.physics.add.overlap(player, enemies, hitEnemy);

// DON'T: enemies vs enemies if not needed
// this.physics.add.collider(enemies, enemies);

Disable Physics When Not Needed

// Disable body temporarily
sprite.body.enable = false;

// Re-enable
sprite.body.enable = true;

// For off-screen objects
if (!cam.worldView.contains(enemy.x, enemy.y)) {
  enemy.body.enable = false;
} else {
  enemy.body.enable = true;
}

Use Spatial Hash for Many Objects

physics: {
  arcade: {
    useTree: true,      // Enable quadtree (default)
    maxEntries: 16      // Tune for your object count
  }
}

// For >5000 dynamic bodies, disable tree
// useTree: false

Simplify Collision Shapes

// Use circles for round objects (faster than rectangles)
sprite.body.setCircle(16);

// Reduce body size for tighter collisions
sprite.body.setSize(24, 32);  // Smaller than sprite

Rendering Optimization

Batch Similar Sprites

Group sprites using same texture for batching:

// Good: All use same atlas
const coins = this.add.group({
  key: 'atlas',
  frame: 'coin',
  repeat: 100
});

// Bad: Mixed textures break batching

Reduce Blend Modes

// Normal blend mode is fastest
sprite.setBlendMode(Phaser.BlendModes.NORMAL);

// Avoid if possible:
// - ADD, MULTIPLY, SCREEN cause extra draw calls

Use Static Images for Backgrounds

// TileSprite for repeating backgrounds (efficient)
this.add.tileSprite(0, 0, 800, 600, 'background').setOrigin(0);

// Don't animate large backgrounds in update()

Limit Particle Count

const emitter = this.add.particles(x, y, 'particle', {
  speed: 100,
  lifespan: 500,
  quantity: 2,       // Particles per emit
  maxParticles: 100, // Hard limit
  frequency: 50      // ms between emits
});

Memory Management

Destroy Unused Objects

// Properly destroy sprites
sprite.destroy();

// Clear groups
group.clear(true, true);  // Remove from scene, destroy

// Scene cleanup
shutdown() {
  this.enemies.destroy(true);
  this.bulletPool.destroy(true);
}

Unload Unused Assets

// Remove texture
this.textures.remove('unused-texture');

// Remove audio
this.sound.remove('unused-sound');

// In scene shutdown
shutdown() {
  this.cache.tilemap.remove('level1');
}

Monitor Memory

// Check texture memory (approximate)
console.log(this.textures.list);

// Chrome DevTools:
// - Memory tab for heap snapshots
// - Performance tab for frame timing

Update Loop Optimization

Throttle Expensive Operations

create() {
  this.lastAIUpdate = 0;
  this.aiUpdateInterval = 100; // ms
}

update(time, delta) {
  // Every frame (required for smooth movement)
  this.updatePlayerMovement();

  // Throttled (AI, pathfinding)
  if (time - this.lastAIUpdate > this.aiUpdateInterval) {
    this.updateEnemyAI();
    this.lastAIUpdate = time;
  }
}

Avoid Creating Objects in Update

// BAD: Creates new object every frame
update() {
  const velocity = { x: 100, y: 0 };  // GC pressure
  sprite.setVelocity(velocity.x, velocity.y);
}

// GOOD: Reuse or use primitives
update() {
  sprite.setVelocity(100, 0);
}

// Or pre-create
create() {
  this.tempVec = new Phaser.Math.Vector2();
}

update() {
  this.tempVec.set(100, 0);
  sprite.body.velocity.copy(this.tempVec);
}

Use Delta Time

// Framerate-independent movement
update(time, delta) {
  const speed = 200;  // pixels per second
  sprite.x += speed * (delta / 1000);
}

Profiling

Built-in Stats

const config = {
  // ...
  fps: {
    target: 60,
    forceSetTimeOut: false,
    smoothStep: true
  }
};

// Add FPS display
this.add.text(10, 10, '', { fontSize: '16px' }).setScrollFactor(0);
this.fpsText = this.add.text(10, 10, '');

update() {
  this.fpsText.setText('FPS: ' + Math.round(this.game.loop.actualFps));
}

Chrome DevTools

  1. Performance Tab: Record gameplay, identify frame drops
  2. Memory Tab: Track heap size, find leaks
  3. Console: Phaser.GAMES[0].loop.actualFps

Common Bottlenecks

Symptom Likely Cause Solution
Gradual slowdown Memory leak Check destroy() calls
Periodic stutters GC pauses Object pooling
Low FPS always Too many objects Culling, pooling
Spikes on spawn Object creation Pre-pool objects
Slow collisions Too many checks Spatial partitioning

Quick Wins Checklist

  • Use texture atlases (not individual images)
  • Pool frequently spawned objects
  • Disable physics for off-screen objects
  • Use appropriate physics shapes (circles are faster)
  • Throttle AI/pathfinding updates
  • Avoid object creation in update loop
  • Use delta time for movement
  • Destroy objects when done
  • Limit particle counts
  • Profile before optimizing

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts27d3 checks · Risk SAFE
  • Gen Agent Trust Hub27d

    The skill is a technical guide for Phaser 3 game development, providing patterns for physics, performance, and asset management. No malicious behaviors were detected.

  • Socket27d

    No alerts

  • Snyk27d

    Risk: LOW · No issues

Signed by skilld at f5f9792. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Dormantupdated 10 months ago

README badge

README badge for superstone-han/dotfiles/phaser-gamedev