Pixi.js Tutorial #2: Move It, Sprite! πŸš€

Welcome back to our magical journey into browser game dev! In Part 1, we added Pixi.js to the page, created a canvas, and displayed a spinning bunny. Now, let’s load your own sprite and make it move!


πŸ“· Loading an Image with Pixi.js

Pixi has a built-in asset loader called PIXI.Assets.load. Let’s use it to load an image.

<script>
  await PIXI.Assets.load('my-sprite.png');
</script>

But we’ll make it more useful by waiting for the image, then displaying it:

<script>
  const app = new PIXI.Application({ width: 360, height: 540 });
  document.body.appendChild(app.view);

  const texture = await PIXI.Assets.load('https://pixijs.io/examples/examples/assets/bunny.png');
  const sprite = new PIXI.Sprite(texture);

  sprite.anchor.set(0.5);
  sprite.x = app.screen.width / 2;
  sprite.y = app.screen.height / 2;

  app.stage.addChild(sprite);
</script>

πŸ’ƒ Make It Dance (Or Move)

To animate the sprite, use Pixi's ticker to update its position every frame.

app.ticker.add(() => {
  sprite.x += 1; // move right by 1 pixel each frame
});

This will make the sprite slide smoothly to the right! You can use sprite.x, sprite.y, sprite.rotation, or sprite.scale to animate anything.


πŸš€ Bonus: Bouncy Movement

Try this for a little bounce:

let direction = 1;
app.ticker.add(() => {
  sprite.x += 2 * direction;
  if (sprite.x > 330 || sprite.x < 30) direction *= -1;
});

βœ… What You’ve Learned

  • How to load image assets with PIXI.Assets.load
  • How to create a PIXI.Sprite
  • How to move your sprite using ticker

Next up: Let’s make that sprite run like a proper character with animation frames! πŸš—