DEV Community

Cover image for Phaser 4 Texture Atlases: Fix the Pivot Bug That Misaligns Your Weapons
Teki Solves
Teki Solves

Posted on Originally published at tekisolves.github.io

Phaser 4 Texture Atlases: Fix the Pivot Bug That Misaligns Your Weapons

Loading a texture atlas in Phaser takes one line. Getting a weapon to sit in a character's hand, fire from the right spot and upgrade without jumping around takes more, and that's the part most tutorials skip.

This guide covers both, for Phaser 4. Most atlas tutorials out there are still for Phaser 2 or 3.

TL;DR

  • Atlas frame names often end in .png. Leave it off and Phaser silently shows the first frame instead.
  • Phaser applies the JSON pivot automatically, measured from the top-left. Unity-style atlases measure from the bottom-left, so your weapon floats off the hand.
  • setFrame(name, false, false) keeps your origin when you swap frames. The default resets it.
  • Store a muzzle point in the atlas and bullets come out of the barrel at any angle.

Follow along with real files: the Laser Pistol from my pack Retro Arsenal, all 3 tiers, as an atlas + JSON with a working Phaser 4 demo.

๐Ÿ‘‰ Download the free sample (ZIP, 210 KB) ยท Try the live demo

The live demo has all five weapons, each behaving like what it is: hold to fire the rifle, get close with the shotgun, swing the blade onto a target, lob a grenade. Press D to see every pivot and muzzle point while you play, and resize the window to watch it re-lay itself out.

What a texture atlas is (and why bother)

A texture atlas is one big image with lots of sprites packed into it, plus a data file that says where each sprite is. Instead of loading 15 separate PNGs, the game loads one image and one JSON file.

Why it's worth it:

  • Fewer downloads. One request instead of dozens, which matters on mobile.
  • Faster rendering. Sprites that share a texture can be drawn together.
  • Extra data travels with the art. This is the underrated part. The JSON can carry pivot points, muzzle points, tier names, anything you want. We'll use that below.

Loading the atlas in Phaser 4

In your scene's preload, point Phaser at the image and the JSON:

preload() {
  this.load.atlas('arsenal', 'retro_arsenal_sample.png', 'retro_arsenal_sample.json');
}
Enter fullscreen mode Exit fullscreen mode

Phaser reads the two common TexturePacker formats, JSON Hash and JSON Array, so most packers work out of the box.

Then in create, add a sprite using the atlas key and a frame name:

create() {
  this.gun = this.add.image(260, 260, 'arsenal', 'weapon_laser_pistol_t1_scrap.png');
}
Enter fullscreen mode Exit fullscreen mode

Gotcha 1: frame names often include ".png"

Look at your JSON before you guess frame names. Many packers keep the original file name as the key, extension and all:

"frames": {
  "weapon_laser_pistol_t1_scrap.png": { "frame": { "x": 0, "y": 0, "w": 1024, "h": 1024 }, ... }
}
Enter fullscreen mode Exit fullscreen mode

If you write 'weapon_laser_pistol_t2_military' without .png, Phaser doesn't crash. It logs a warning (Texture "arsenal" has no frame ...) and quietly shows the first frame in the atlas instead. So you get a real sprite, just the wrong one, which is easy to miss. Keep the console open and it's a four-character fix.

Putting the weapon in the hand: pivots

A pivot (or origin) is the point of a sprite that sits on its x and y position, and the point it rotates around. For a gun, you want that to be the grip, not the middle of the image. Otherwise the gun swings around its own centre like a propeller.

Good asset packs store the pivot for you. Retro Arsenal stores two versions per frame:

  • pivot: normalised 0 to 1, measured from the bottom-left (Unity's convention)
  • custom.pivot_px: in pixels, measured from the top-left

Gotcha 2: Phaser applies the pivot for you, upside down

This one is sneaky. When Phaser loads a JSON atlas, it looks for a pivot on each frame, and if it finds one, every sprite using that frame gets that origin automatically.

The catch: Phaser measures origin from the top-left. If your atlas was exported with a bottom-left pivot, like many Unity-friendly packs, Phaser applies it without complaint and your weapon ends up noticeably above or below the hand. No error, just a gun floating in the wrong place.

The fix is to set the origin yourself from the top-left pixel values:

const data = this.gun.frame.customData.custom;   // everything from the JSON frame
this.gun.setOrigin(data.pivot_px.x / 1024, data.pivot_px.y / 1024);
Enter fullscreen mode Exit fullscreen mode

frame.customData is Phaser's copy of the whole JSON entry for that frame, so any extra data your atlas carries is right there.

If your atlas only has a bottom-left pivot, flip the y yourself:

this.gun.setOrigin(frame.pivotX, 1 - frame.pivotY);
Enter fullscreen mode Exit fullscreen mode

Aiming and firing from the muzzle

Rotating towards the pointer is one line:

this.input.on('pointermove', (p) => {
  const angle = Phaser.Math.Angle.Between(this.gun.x, this.gun.y, p.worldX, p.worldY);
  this.gun.setRotation(angle);
  // Pointing left? Flip vertically so the gun isn't upside down.
  this.gun.setScale(0.25, Math.abs(angle) > Math.PI / 2 ? -0.25 : 0.25);
});
Enter fullscreen mode Exit fullscreen mode

Now the interesting bit. Bullets should come out of the barrel, not the hand. Retro Arsenal stores a muzzle_px point per frame, so we can work out where it is in the world, whatever the rotation and scale:

muzzle() {
  const c = this.gun.frame.customData.custom;
  const dx = (c.muzzle_px.x - c.pivot_px.x) * this.gun.scaleX;
  const dy = (c.muzzle_px.y - c.pivot_px.y) * this.gun.scaleY;
  const cos = Math.cos(this.gun.rotation);
  const sin = Math.sin(this.gun.rotation);
  return { x: this.gun.x + dx * cos - dy * sin, y: this.gun.y + dx * sin + dy * cos };
}
Enter fullscreen mode Exit fullscreen mode

That's the offset from the grip to the muzzle, scaled, then rotated. Spawn your projectile there:

fire() {
  const m = this.muzzle();
  const r = this.gun.rotation;
  const bolt = this.add.rectangle(m.x, m.y, 26, 5, 0xb2dd31).setRotation(r);
  this.tweens.add({
    targets: bolt,
    x: m.x + Math.cos(r) * 900,
    y: m.y + Math.sin(r) * 900,
    duration: 600,
    onComplete: () => bolt.destroy(),
  });
}
Enter fullscreen mode Exit fullscreen mode

The same idea works for any attachment point: a blade tip for hit effects, a grenade pin, a muzzle flash.

Swapping weapon tiers at runtime

Every weapon in Retro Arsenal comes in three tiers (Scrap, Military, Prototype) drawn on the same shape, with the same pivot and muzzle point. So an upgrade is just a frame swap:

this.gun.setFrame('weapon_laser_pistol_t2_military.png', false, false);
Enter fullscreen mode Exit fullscreen mode

Gotcha 3: setFrame resets your origin

Look at that last false. By default, setFrame re-applies the frame's pivot from the JSON, which brings Gotcha 2 straight back and undoes your setOrigin. Passing false as the third argument (updateOrigin) keeps the origin you set.

Will a 4096px atlas work on a cheap phone?

The full Retro Arsenal atlas is 4096 ร— 4096. Most phones from the last several years handle that, but older or budget GPUs can top out lower. You can check the device limit with plain WebGL:

const gl = document.createElement('canvas').getContext('webgl');
console.log(gl.getParameter(gl.MAX_TEXTURE_SIZE)); // e.g. 4096, 8192 or 16384
Enter fullscreen mode Exit fullscreen mode

If you need to support very old devices, repack into smaller atlases (2048 is a safe size) and load them with this.load.multiatlas(). The free sample is 3072 ร— 1024, so it runs anywhere.

Phaser 3 vs Phaser 4: what changed for atlases?

Very little for this workflow. this.load.atlas, frame.customData, the automatic pivot and setFrame(frame, updateSize, updateOrigin) all work the same way in both, so this guide applies to Phaser 3 too.

The new thing in Phaser 4 is the Phaser Compact Texture Atlas (.pct), a text format that's typically 90 to 95% smaller than the JSON, loaded with this.load.atlasPCT(). Worth a look once you're shipping lots of atlases.

Bonus: aim through the barrel, not the grip

The aim code above points the grip at the cursor. Because the muzzle sits above the grip, shots land a little above where you click. The fix is to tilt the gun until the line out of the muzzle passes through the pointer:

aimAt(p) {
  const c = this.gun.frame.customData.custom;
  const px = p.worldX - this.gun.x, py = p.worldY - this.gun.y;
  const dist = Math.hypot(px, py);
  const phi = Math.atan2(py, px);
  const flip = Math.abs(phi) > Math.PI / 2 ? -1 : 1;              // pointing left?
  const off = (c.muzzle_px.y - c.pivot_px.y) * 0.25 * flip;          // muzzle height above the grip, scaled
  const angle = dist > Math.abs(off) ? phi - Math.asin(off / dist) : phi;
  this.gun.setRotation(angle).setScale(0.25, 0.25 * flip);
}
Enter fullscreen mode Exit fullscreen mode

off / dist is the angle the barrel has to tilt so its line still hits the target. It matters most up close, which is exactly where players notice.

Grab the code

The free sample includes everything in this post as one working file (main.js), plus the pistol in all 3 tiers. Use the sprites in your own games, commercial ones included. Just don't resell the files.

๐Ÿ‘‰ Download the free sample (ZIP) ยท Try the live demo

If you want the other four weapons (laser rifle, shotgun, energy blade and plasma grenade), each in the same three tiers with pivot and muzzle data, that's Retro Arsenal. I made it, so I'm biased, but it's built for exactly this setup.


Which of the three gotchas has caught you before? Or if you've hit an atlas bug I didn't cover, drop it in the comments. I'll test it and add the fix.

How this post was made: Written by Khaya, drafted with help from Claude (AI). The demo was tested in Phaser 4.2.1 on a low-end Android phone before publishing. It was first published on the Teki Solves blog.

Top comments (0)