Object Pooling
class BulletPool {
constructor(scene, size) {
this.scene = scene;
this.pool = [];
for (let i = 0; i < size; i++) {
const bullet = scene.physics.add.sprite(-100, -100, 'bullet');
bullet.setActive(false);
bullet.setVisible(false);
this.pool.push(bullet);
}
}
spawn(x, y, velocityX, velocityY) {
const bullet = this.pool.find(b => !b.active);
if (bullet) {
bullet.setPosition(x, y);
bullet.setVelocity(velocityX, velocityY);
bullet.setActive(true);
bullet.setVisible(true);
return bullet;
}
return null;
}
despawn(bullet) {
bullet.setActive(false);
bullet.setVisible(false);
bullet.setVelocity(0, 0);
}
}
const bulletPool = new BulletPool(this, 50);
const bullet = bulletPool.spawn(player.x, player.y, 200, 0);
Texture Atlas
preload() {
this.load.atlas('sprites', 'sprites.png', 'sprites.json');
}
create() {
this.add.sprite(400, 300, 'sprites', 'player');
this.add.sprite(500, 300, 'sprites', 'enemy');
}
Culling
update() {
this.enemies.children.each((enemy) => {
const bounds = this.cameras.main.worldView;
if (bounds.contains(enemy.x, enemy.y)) {
enemy.update();
}
});
}
Reduce Draw Calls
const container = this.add.container(0, 0);
container.add([sprite1, sprite2, sprite3]);
const background = this.add.tileSprite(0, 0, 800, 600, 'bg');
Best Practices
- Object pooling per oggetti frequenti
- Texture atlas per ridurre draw calls
- Culling per oggetti fuori schermo
- Limita particelle attive
- Usa WebGL quando possibile
- Profiling con Chrome DevTools