360 Secure SkillHub
360 安全技能中心

sprites-and-images

面向 Phaser 4 开发者的纹理游戏对象参考,讲解 Image、Sprite、NineSlice、TileSprite、Blitter 的创建、纹理与帧切换、裁剪、平铺、自定义类继承及常见迁移陷阱,并附代码示例。

分类:开发
phaserjs
热度 0.00
最近更新 2026-12-03 17:40:32

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/sprites-and-images
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
sprites-and-images
description
Create and use texture-based Game Objects in Phaser 4: Image and Sprite (this.add.image, this.add.sprite, setTexture, setFrame, setCrop, setDisplaySize, custom classes with scene.add.existing), NineSlice panels, TileSprite scrolling backgrounds (tilePosition, tileScale, tileRotation), Blitter, and pointers to Rope, Mesh2D, Video and SpriteGPULayer. Covers vertexRoundMode for tiles placed edge to edge. Use when adding a player, enemy, pickup, background, parallax layer, button or UI panel, swapping frames, or subclassing Sprite. Corrects v3 habits: setTintFill is gone (use setTint plus setTintMode), this.add.existing(this) inside a class is wrong (use scene.add.existing), TileSprite can't be cropped. Triggers on: Sprite, Image, this.add.sprite, this.add.image, setTexture, setFrame, NineSlice, TileSprite, Blitter, extends Phaser.GameObjects.Sprite.
metadata
{"phaser-version":"4.3.0"}

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 __MISSING texture. An unknown frame logs a warning and uses the first frame.
  • width / height are the frame size; displayWidth / displayHeight include scale. setSize changes the internal size (input, physics), not how it looks.
  • setFrame also 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 + rightWidth by topHeight + 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)) and setTintMode. 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 setCrop isn'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) after this.load.video(key, url), then video.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

  1. Alpha or scale of 0 stops rendering. It clears a render flag. Use setVisible(false) to hide on purpose.
  2. Flip is visual only. It doesn't flip a physics body or hit area.
  3. setFrame resizes the object to the new frame, and applies the frame's pivot if it has one, unless you pass false, false. This matters when frames differ in size, such as for a physics body or hit area.
  4. setTintFill is gone. It only logs an error. Use setTint(c).setTintMode(Phaser.TintModes.FILL).
  5. Default game size is 1024x768. Position from this.scale.width and this.scale.height rather than 800x600 habits.
  6. Overriding preUpdate on a Sprite without calling super.preUpdate(time, delta) freezes its animation.