PixiJS 6.x Invisible Sprites Performance Hit Example
by TobiasW
HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/browser/pixi.min.js"></script>
<!--<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/pixi.min.js"></script>-->
<!--<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/pixi.min.js"></script>-->
<script src="https://mrdoob.github.io/stats.js/build/stats.min.js"></script>
JavaScript
const app = new PIXI.Application();
document.body.appendChild(app.view);
const totalSprites = 300000;
const visibleSprites = 10;
const sprites = new PIXI.Container();
app.stage.addChild(sprites);
// create an array to store all the sprites
const maggots = [];
for (let i = 0; i < totalSprites; i++) {
// create a new Sprite
const dude = PIXI.Sprite.from('https://pixijs.io/examples/examples/assets/maggot_tiny.png');
// set the anchor point so the texture is centerd on the sprite
dude.anchor.set(0.5);
// different maggots, different sizes
dude.scale.set(0.8 + Math.random() * 0.3);
// scatter them all
dude.x = Math.random() * app.screen.width;
dude.y = Math.random() * app.screen.height;
dude.tint = Math.random() * 0x808080;
// create a random direction in radians
dude.direction = Math.random() * Math.PI * 2;
// this number will be used to modify the direction of the sprite over time
dude.turningSpeed = Math.random() - 0.8;
// create a random speed between 0 - 2, and these maggots are slooww
dude.speed = (2 + Math.random() * 2) * 2;
dude.offset = Math.random() * 100;
dude.visible = i < visibleSprites;
// finally we push the dude into the maggots array so it it can be easily accessed later
maggots.push(dude);
sprites.addChild(dude);
}
// create a bounding box box for the little maggots
const dudeBoundsPadding = 100;
const dudeBounds = new PIXI.Rectangle(
-dudeBoundsPadding,
-dudeBoundsPadding,
app.screen.width + dudeBoundsPadding * 2,
app.screen.height + dudeBoundsPadding * 2,
);
let tick = 0;
app.ticker.add(() => {
// iterate through the sprites and update their position
for (let i = 0; i < visibleSprites; i++) {
const dude = maggots[i];
dude.scale.y = 0.95 + Math.sin(tick + dude.offset) * 0.05;
dude.direction += dude.turningSpeed * 0.01;
dude.x += Math.sin(dude.direction) * (dude.speed *...