Sprites and Images
Image, Sprite and the other texture-based display objects. The shared components (transform, alpha, tint, origin, depth, flip, scroll factor, blend mode) are covered once in game-object-components; this skill covers what is specific to these objects.
Source: src/gameobjects/image/Image.js, src/gameobjects/sprite/Sprite.js, src/gameobjects/components/TextureCrop.js, src/gameobjects/nineslice/NineSlice.js, src/gameobjects/tilesprite/TileSprite.js, src/gameobjects/blitter/. Related: game-object-components, animations, loading-assets, physics-arcade, v4-new-features.
Quick start
const bg = this.add.image(0, 0, 'background').setOrigin(0); // origin defaults to 0.5
const player = this.add.sprite(this.scale.width / 2, 600, 'hero', 'idle-0'); // key, frame name or index
player.setScale(2).setFlipX(true).setDepth(10);
player.setTint(0xff0000).setTintMode(Phaser.TintModes.FILL); // v3's setTintFill(0xff0000)
player.play('walk'); // Sprite only
Image or Sprite?
They have the same components. A Sprite also has anims (an AnimationState) and is put on the Scene's update list so its preUpdate advances animations. Use Image for anything that never animates by frames.
Textures and frames
const enemy = this.add.sprite(300, 200, 'enemies', 'goblin-1');
enemy.setTexture('enemies', 'goblin-2'); // texture key (or a Texture), optional frame
enemy.setFrame('goblin-3'); // frame of the current texture; resizes to it
enemy.setFrame('goblin-small', false, false); // updateSize, updateOrigin (pixel origin, or the frame's pivot)
enemy.setCrop(0, 0, 32, 16); // show part of the frame; setCrop() with no args removes it
enemy.setDisplaySize(64, 64); // visual size, by changing scale
- With no frame, the texture's first frame is used (
texture.firstFrame), not the whole atlas. - An unknown texture key silently shows the
__MISSINGtexture. An unknown frame logs a warning and uses the first frame. width/heightare the frame size;displayWidth/displayHeightinclude scale.setSizechanges the internal size (input, physics), not how it looks.setFramealso takes a Frame object. Spritesheet frames are numbers.
Custom classes
class Player extends Phaser.GameObjects.Sprite
{
constructor (scene, x, y)
{
super(scene, x, y, 'hero');
scene.add.existing(this); // display list, plus update list because it has preUpdate
scene.physics.add.existing(this); // only with Arcade Physics enabled
}
preUpdate (time, delta)
{
super.preUpdate(time, delta); // without this, animations stop
// per-frame logic
}
}
const hero = new Player(this, 100, 100);
Use scene.add.existing(this), not this.add.existing(this): inside the class, this is the Sprite. To make this.add.player(...) work, register a factory with Phaser.GameObjects.GameObjectFactory.register (see game-object-components).
Objects placed edge to edge
With roundPixels on (the game config, or pixelArt: true), the default vertexRoundMode of 'safeAuto' rounds an object's vertices only when it isn't scaled or rotated. Tiles of a background where some are scaled and some aren't then round differently and show thin gaps as the Camera moves. Give all of them the same mode:
for (let i = 0; i < 8; i++)
{
this.add.image(i * 128, 0, 'ground').setOrigin(0).setScale(2).setVertexRoundMode('fullAuto'); // or 'off'
}
Modes: 'off', 'safe', 'safeAuto' (default), 'full', 'fullAuto'. The Auto modes only round when the Camera has roundPixels. See GameObject.vertexRoundMode and docs/Phaser 4 Pixel Art Guide.
Tint
setTint(color) or setTint(tl, tr, bl, br) sets the color; setTintMode(mode) sets how it applies (MULTIPLY, FILL, ADD, SCREEN, OVERLAY, HARD_LIGHT, and MULTIPLY_TWO / MULTIPLY_ADD with setTint2). Tint is WebGL only. The full table is in game-object-components.
NineSlice
A panel or button that resizes without stretching its corners.
// nineslice(x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight, tileX, tileY)
const panel = this.add.nineslice(this.scale.width / 2, 300, 'ui', 'panel', 320, 200, 24, 24, 24, 24);
panel.setSize(480, 260); // corners stay the same size
const bar = this.add.nineslice(400, 500, 'ui', 'bar', 300, 0, 16, 16); // left/right only = a 3-slice, width only
const tiled = this.add.nineslice(400, 400, 'ui', 'frame', 300, 200, 20, 20, 20, 20, true, true); // repeat edges, don't stretch
- The minimum size is
leftWidth + rightWidthbytopHeight + bottomHeight. Scale it to go smaller. - Slice sizes can come from a Texture Packer (7.1+) atlas, so
this.add.nineslice(x, y, 'ui', 'panel')may be enough. Trimmed frames aren't supported. setSlices(width, height, leftWidth, rightWidth, topHeight, bottomHeight)changes the slices later.- It has one tint color for the whole object (
setTint(color)) andsetTintMode. Its alpha is single (AlphaSingle).
TileSprite
A repeating texture across a fixed-size quad: scrolling backgrounds and parallax.
const sky = this.add.tileSprite(0, 0, this.scale.width, this.scale.height, 'clouds').setOrigin(0).setScrollFactor(0);
// in update(time, delta):
sky.tilePositionX += 0.05 * delta; // scroll the texture, not the object
sky.setTileScale(2, 2);
sky.setTileRotation(0.1); // radians; also the tileRotation property
- Make it the size of the view and scroll
tilePosition. Don't make it the size of the world. - In v4 it works with atlas frames and textures of any size, not just powers of two.
- It has the Texture component, not TextureCrop, so
setCropisn't available.
Blitter
Thousands of simple images from one texture, batched. Bobs have position, frame, flip, alpha, tint and visibility, but no rotation, scale or physics.
const blitter = this.add.blitter(0, 0, 'particles');
const bob = blitter.create(100, 100, 'spark'); // x, y, frame, visible, index
bob.setAlpha(0.5);
Other texture objects
- Video:
this.add.video(x, y, key)afterthis.load.video(key, url), thenvideo.play(). A video from another domain needs CORS to be used as a WebGL texture:this.load.setCORS('anonymous'), from a server that allows it. - Rope (WebGL only):
this.add.rope(x, y, texture, frame, points, horizontal, colors, alphas), a texture bent along a list of points. - Mesh2D (4.2, WebGL only):
this.add.mesh2d(x, y, texture, vertices, indices), textured 2D triangles that batch with sprites. It replaces v3's Mesh for 2D. See v4-new-features. - SpriteGPULayer (WebGL only):
this.add.spriteGPULayer(texture, size)for very large numbers of mostly static sprites. See v4-new-features.
Gotchas
- Alpha or scale of 0 stops rendering. It clears a render flag. Use
setVisible(false)to hide on purpose. - Flip is visual only. It doesn't flip a physics body or hit area.
setFrameresizes the object to the new frame, and applies the frame's pivot if it has one, unless you passfalse, false. This matters when frames differ in size, such as for a physics body or hit area.setTintFillis gone. It only logs an error. UsesetTint(c).setTintMode(Phaser.TintModes.FILL).- Default game size is 1024x768. Position from
this.scale.widthandthis.scale.heightrather than 800x600 habits. - Overriding
preUpdateon a Sprite without callingsuper.preUpdate(time, delta)freezes its animation.
