sprites-and-images

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Sprites and Images

Sprite与Image

Creating and manipulating Sprite and Image game objects in Phaser 4 -- factory methods, texture/frame selection, the component mixin system, and common visual operations (position, scale, rotation, tint, flip, alpha, origin, depth).
Key source paths:
src/gameobjects/sprite/
,
src/gameobjects/image/
,
src/gameobjects/GameObject.js
,
src/gameobjects/components/
Related skills: ../loading-assets/SKILL.md, ../animations/SKILL.md, ../physics-arcade/SKILL.md, ../game-object-components/SKILL.md
在Phaser 4中创建和操作Sprite与Image游戏对象——包括工厂方法、纹理/帧选择、组件混入系统,以及常见视觉操作(位置、缩放、旋转、着色、翻转、透明度、原点、深度)。
核心源码路径:
src/gameobjects/sprite/
,
src/gameobjects/image/
,
src/gameobjects/GameObject.js
,
src/gameobjects/components/
相关技能: ../loading-assets/SKILL.md, ../animations/SKILL.md, ../physics-arcade/SKILL.md, ../game-object-components/SKILL.md

Quick Start

快速入门

js
// In a Scene's create() method:

// Static image (no animation support, slightly cheaper)
const bg = this.add.image(400, 300, 'background');

// Sprite (supports animations)
const player = this.add.sprite(100, 200, 'player', 'idle-0');

// Common operations -- all methods return `this` for chaining
player.setPosition(200, 300);
player.setScale(2);
player.setAngle(45);
player.setTint(0xff0000);
player.setAlpha(0.8);
player.setOrigin(0, 1);       // bottom-left
player.setDepth(10);
player.setFlip(true, false);  // flip horizontally
player.setVisible(false);

// Chained
this.add.sprite(100, 100, 'coin')
    .setScale(0.5)
    .setTint(0xffff00)
    .play('spin');
js
// 在场景的create()方法中:

// 静态图片(不支持动画,性能开销略低)
const bg = this.add.image(400, 300, 'background');

// Sprite(支持动画)
const player = this.add.sprite(100, 200, 'player', 'idle-0');

// 常见操作——所有方法均返回`this`以支持链式调用
player.setPosition(200, 300);
player.setScale(2);
player.setAngle(45);
player.setTint(0xff0000);
player.setAlpha(0.8);
player.setOrigin(0, 1);       // 左下角
player.setDepth(10);
player.setFlip(true, false);  // 水平翻转
player.setVisible(false);

// 链式调用示例
this.add.sprite(100, 100, 'coin')
    .setScale(0.5)
    .setTint(0xffff00)
    .play('spin');

Core Concepts

核心概念

Sprite vs Image

Sprite与Image对比

Both extend
GameObject
and share the same set of component mixins. The only difference is that Sprite includes an
AnimationState
instance (
sprite.anims
) and animation convenience methods (
play
,
stop
,
chain
, etc.).
FeatureImageSprite
Static texture displayYesYes
Tint, alpha, flip, scale, rotateYesYes
Physics bodyYesYes
Input / hit areaYesYes
Animation (
play
,
stop
,
chain
)
NoYes
preUpdate
called each frame
NoYes (updates animation)
Added to Scene
updateList
NoYes
Rule of thumb: Use
Image
for anything that does not need frame-by-frame animation. It skips the per-frame
preUpdate
cost and has a smaller API surface. Use
Sprite
only when you need the Animation component.
两者均继承自
GameObject
,并共享相同的组件混入集合。唯一区别在于Sprite包含
AnimationState
实例(
sprite.anims
)以及动画便捷方法(
play
、
stop
、
chain
等)。
特性ImageSprite
静态纹理显示是是
着色、透明度、翻转、缩放、旋转是是
物理体是是
输入/碰撞区域是是
动画(
play
、
stop
、
chain
)
否是
每帧调用
preUpdate
否是(更新动画)
添加至场景
updateList
否是
经验法则: 对于不需要逐帧动画的元素,使用
Image
。它跳过每帧的
preUpdate
开销,且API更精简。仅在需要动画组件时使用
Sprite
。

The Component Mixin System

组件混入系统

Phaser builds Game Object classes by mixing component objects into the prototype. Both
Sprite
and
Image
share this identical Mixins array (sourced from
src/gameobjects/sprite/Sprite.js
and
src/gameobjects/image/Image.js
):
Mixins: [
    Components.Alpha,
    Components.BlendMode,
    Components.Depth,
    Components.Flip,
    Components.GetBounds,
    Components.Lighting,
    Components.Mask,
    Components.Origin,
    Components.RenderNodes,
    Components.ScrollFactor,
    Components.Size,
    Components.TextureCrop,
    Components.Tint,
    Components.Transform,
    Components.Visible,
    SpriteRender / ImageRender   // render-specific (differs per class)
]
The base
GameObject
class itself mixes in:
Mixins: [
    Components.Filters,
    Components.RenderSteps
]
Each component adds specific properties and methods to every instance. For example,
Components.Transform
adds
x
,
y
,
scale
,
rotation
,
setPosition()
, etc. The full list of available components is in
src/gameobjects/components/index.js
.
Key point for agents: When you see a method like
setAlpha()
on a Sprite, it comes from
Components.Alpha
, not from the Sprite class itself. The component source file is the authoritative reference for that method's signature and behavior.
Phaser通过将组件对象混入原型来构建游戏对象类。
Sprite
和
Image
共享完全相同的混入数组(源自
src/gameobjects/sprite/Sprite.js
和
src/gameobjects/image/Image.js
):
Mixins: [
    Components.Alpha,
    Components.BlendMode,
    Components.Depth,
    Components.Flip,
    Components.GetBounds,
    Components.Lighting,
    Components.Mask,
    Components.Origin,
    Components.RenderNodes,
    Components.ScrollFactor,
    Components.Size,
    Components.TextureCrop,
    Components.Tint,
    Components.Transform,
    Components.Visible,
    SpriteRender / ImageRender   // 渲染相关(两类对象不同)
]
基础
GameObject
类自身混入了:
Mixins: [
    Components.Filters,
    Components.RenderSteps
]
每个组件会为实例添加特定属性和方法。例如,
Components.Transform
添加了
x
、
y
、
scale
、
rotation
、
setPosition()
等属性和方法。完整组件列表可查看
src/gameobjects/components/index.js
。
Agent关键提示: 当你在Sprite上看到
setAlpha()
这类方法时,它来自
Components.Alpha
而非Sprite类本身。组件源码文件是该方法签名和行为的权威参考。

Texture and Frame

纹理与帧

Both Sprite and Image use the
TextureCrop
component which provides:
  • texture
    -- the
    Phaser.Textures.Texture
    instance
  • frame
    -- the current
    Phaser.Textures.Frame
    instance
  • setTexture(key, frame)
    -- change the texture (and optionally the frame)
  • setFrame(frame, updateSize, updateOrigin)
    -- change only the frame
  • setCrop(x, y, width, height)
    -- crop a rectangular region of the texture
  • isCropped
    -- boolean, toggle cropping on/off after
    setCrop
The
texture
parameter in factory methods and constructors accepts either a string key (as registered in the Texture Manager) or a
Phaser.Textures.Texture
instance.
The
frame
parameter accepts a string name or numeric index into the texture's frame collection. If omitted, the base frame (frame 0 /
'__BASE'
) is used.
js
// Change texture at runtime
sprite.setTexture('enemies', 'goblin-walk-1');

// Change only the frame (must belong to current texture)
sprite.setFrame('goblin-walk-2');

// setFrame signature:
// setFrame(frame, updateSize=true, updateOrigin=true)
// Pass false to prevent automatic resize/origin recalculation
sprite.setFrame('small-frame', false, false);

// Crop to show only a 50x50 region starting at (10, 10)
sprite.setCrop(10, 10, 50, 50);
// Reset crop
sprite.setCrop();
Sprite和Image均使用
TextureCrop
组件,该组件提供以下功能:
  • texture
    ——
    Phaser.Textures.Texture
    实例
  • frame
    —— 当前
    Phaser.Textures.Frame
    实例
  • setTexture(key, frame)
    —— 更换纹理(可同时指定帧)
  • setFrame(frame, updateSize, updateOrigin)
    —— 仅更换帧
  • setCrop(x, y, width, height)
    —— 裁剪纹理的矩形区域
  • isCropped
    —— 布尔值,调用
    setCrop
    后可切换裁剪开关
工厂方法和构造函数中的
texture
参数可接受字符串键(在纹理管理器中注册过)或
Phaser.Textures.Texture
实例。
frame
参数可接受纹理帧集合中的字符串名称或数字索引。若省略,则使用基础帧(帧0 /
'__BASE'
)。
js
// 运行时更换纹理
sprite.setTexture('enemies', 'goblin-walk-1');

// 仅更换帧(必须属于当前纹理)
sprite.setFrame('goblin-walk-2');

// setFrame签名:
// setFrame(frame, updateSize=true, updateOrigin=true)
// 传入false可阻止自动重新计算尺寸/原点
sprite.setFrame('small-frame', false, false);

// 裁剪为仅显示从(10,10)开始的50x50区域
sprite.setCrop(10, 10, 50, 50);
// 重置裁剪
sprite.setCrop();

Common Patterns

常见模式

Creating and Positioning

创建与定位

Transform component (
src/gameobjects/components/Transform.js
):
js
// Properties (all read/write)
sprite.x           // horizontal position (default: 0)
sprite.y           // vertical position (default: 0)
sprite.z           // z position (does NOT control render order -- use depth)
sprite.w           // w position

// Methods
sprite.setPosition(x, y, z, w)        // y defaults to x if omitted
sprite.setRandomPosition(x, y, w, h)  // random within area; defaults to game size
sprite.copyPosition(source)            // copy from any {x, y} object
Size component (
src/gameobjects/components/Size.js
):
js
sprite.width            // native (un-scaled) width
sprite.height           // native (un-scaled) height
sprite.displayWidth      // scaled width (read/write -- setting adjusts scaleX)
sprite.displayHeight     // scaled height (read/write -- setting adjusts scaleY)

sprite.setSize(width, height)           // set internal size (not visual)
sprite.setDisplaySize(width, height)    // set visual size (adjusts scale)
sprite.setSizeToFrame(frame)            // reset size to match frame
Transform组件(
src/gameobjects/components/Transform.js
):
js
// 属性(均支持读写)
sprite.x           // 水平位置(默认值:0)
sprite.y           // 垂直位置(默认值:0)
sprite.z           // z轴位置(不控制渲染顺序——使用depth)
sprite.w           // w轴位置

// 方法
sprite.setPosition(x, y, z, w)        // 若省略y,默认与x相同
sprite.setRandomPosition(x, y, w, h)  // 在指定区域内随机定位;默认使用游戏尺寸
sprite.copyPosition(source)            // 从任意{x, y}对象复制位置
Size组件(
src/gameobjects/components/Size.js
):
js
sprite.width            // 原生(未缩放)宽度
sprite.height           // 原生(未缩放)高度
sprite.displayWidth      // 缩放后宽度(可读可写——设置时会调整scaleX)
sprite.displayHeight     // 缩放后高度(可读可写——设置时会调整scaleY)

sprite.setSize(width, height)           // 设置内部尺寸(非视觉尺寸)
sprite.setDisplaySize(width, height)    // 设置视觉尺寸(调整缩放比例)
sprite.setSizeToFrame(frame)            // 将尺寸重置为与帧匹配

Scaling and Rotation

缩放与旋转

Transform component (continued):
js
// Scale properties
sprite.scale       // uniform scale (getter returns average of scaleX+scaleY)
sprite.scaleX      // horizontal scale (default: 1)
sprite.scaleY      // vertical scale (default: 1)

// Scale methods
sprite.setScale(x, y)    // y defaults to x if omitted

// Rotation properties
sprite.rotation    // in radians (right-hand clockwise: 0=right, PI/2=down)
sprite.angle       // in degrees (0=right, 90=down, 180/-180=left, -90=up)

// Rotation methods
sprite.setRotation(radians)   // defaults to 0
sprite.setAngle(degrees)      // defaults to 0
Transform组件(续):
js
// 缩放属性
sprite.scale       // 统一缩放比例(getter返回scaleX与scaleY的平均值)
sprite.scaleX      // 水平缩放比例(默认值:1)
sprite.scaleY      // 垂直缩放比例(默认值:1)

// 缩放方法
sprite.setScale(x, y)    // 若省略y,默认与x相同

// 旋转属性
sprite.rotation    // 弧度制(右手顺时针:0=向右,PI/2=向下)
sprite.angle       // 角度制(0=向右,90=向下,180/-180=向左,-90=向上)

// 旋转方法
sprite.setRotation(radians)   // 默认值:0
sprite.setAngle(degrees)      // 默认值:0

Tinting and Alpha

着色与透明度

Tint component (
src/gameobjects/components/Tint.js
) -- WebGL only:
js
// Properties
sprite.tint             // overall tint (getter returns tintTopLeft)
sprite.tintTopLeft      // default: 0xffffff
sprite.tintTopRight     // default: 0xffffff
sprite.tintBottomLeft   // default: 0xffffff
sprite.tintBottomRight  // default: 0xffffff
sprite.tintMode         // default: Phaser.TintModes.MULTIPLY
sprite.isTinted         // read-only boolean

// Methods
sprite.setTint(topLeft, topRight, bottomLeft, bottomRight)
// If only topLeft given, applies uniformly to all four corners
sprite.setTintMode(mode)   // Phaser.TintModes.MULTIPLY | FILL | ADD | SCREEN | OVERLAY | HARD_LIGHT
sprite.clearTint()         // resets to 0xffffff + MULTIPLY mode
Phaser 4 change:
setTintFill()
is removed. Use
setTint(color).setTintMode(Phaser.TintModes.FILL)
instead.
Alpha component (
src/gameobjects/components/Alpha.js
):
js
// Properties
sprite.alpha             // global alpha 0-1 (default: 1)
sprite.alphaTopLeft      // per-corner alpha (WebGL only)
sprite.alphaTopRight
sprite.alphaBottomLeft
sprite.alphaBottomRight

// Methods
sprite.setAlpha(topLeft, topRight, bottomLeft, bottomRight)
// If only topLeft given, applies uniformly to whole object
sprite.clearAlpha()     // resets to 1 (fully opaque)
Setting
alpha
to 0 clears the render flag so the object is not drawn. Setting it back to any non-zero value restores it.
Tint组件(
src/gameobjects/components/Tint.js
)——仅支持WebGL:
js
// 属性
sprite.tint             // 整体着色(getter返回tintTopLeft)
sprite.tintTopLeft      // 默认值:0xffffff
sprite.tintTopRight     // 默认值:0xffffff
sprite.tintBottomLeft   // 默认值:0xffffff
sprite.tintBottomRight  // 默认值:0xffffff
sprite.tintMode         // 默认值:Phaser.TintModes.MULTIPLY
sprite.isTinted         // 只读布尔值

// 方法
sprite.setTint(topLeft, topRight, bottomLeft, bottomRight)
// 若仅传入topLeft,则为四个角统一应用该值
sprite.setTintMode(mode)   // Phaser.TintModes.MULTIPLY | FILL | ADD | SCREEN | OVERLAY | HARD_LIGHT
sprite.clearTint()         // 重置为0xffffff + MULTIPLY模式
Phaser 4变更:
setTintFill()
已移除。请使用
setTint(color).setTintMode(Phaser.TintModes.FILL)
替代。
Alpha组件(
src/gameobjects/components/Alpha.js
):
js
// 属性
sprite.alpha             // 全局透明度0-1(默认值:1)
sprite.alphaTopLeft      // 四角独立透明度(仅支持WebGL)
sprite.alphaTopRight
sprite.alphaBottomLeft
sprite.alphaBottomRight

// 方法
sprite.setAlpha(topLeft, topRight, bottomLeft, bottomRight)
// 若仅传入topLeft,则为整个对象统一应用该值
sprite.clearAlpha()     // 重置为1(完全不透明)
将
alpha
设为0会清除渲染标记,对象将不再被绘制。将其设为任意非零值会恢复渲染。

Flipping

翻转

Flip component (
src/gameobjects/components/Flip.js
):
js
// Properties
sprite.flipX    // boolean (default: false)
sprite.flipY    // boolean (default: false)

// Methods
sprite.setFlipX(value)        // set horizontal flip
sprite.setFlipY(value)        // set vertical flip
sprite.setFlip(x, y)          // set both at once
sprite.toggleFlipX()          // invert current horizontal flip
sprite.toggleFlipY()          // invert current vertical flip
sprite.resetFlip()            // set both to false
Flipping is a rendering toggle only. It does not affect physics bodies or hit areas. Flip occurs from the middle of the texture and does not change the scale value.
Flip组件(
src/gameobjects/components/Flip.js
):
js
// 属性
sprite.flipX    // 布尔值(默认值:false)
sprite.flipY    // 布尔值(默认值:false)

// 方法
sprite.setFlipX(value)        // 设置水平翻转
sprite.setFlipY(value)        // 设置垂直翻转
sprite.setFlip(x, y)          // 同时设置水平和垂直翻转
sprite.toggleFlipX()          // 反转当前水平翻转状态
sprite.toggleFlipY()          // 反转当前垂直翻转状态
sprite.resetFlip()            // 将两者均设为false
翻转仅为渲染层面的切换,不影响物理体或碰撞区域。翻转以纹理中心为轴进行,不会改变缩放值。

Origin and Depth

原点与深度

Origin component (
src/gameobjects/components/Origin.js
):
js
// Properties (normalized 0-1)
sprite.originX          // default: 0.5 (center)
sprite.originY          // default: 0.5 (center)
sprite.displayOriginX   // pixel value (originX * width)
sprite.displayOriginY   // pixel value (originY * height)

// Methods
sprite.setOrigin(x, y)           // y defaults to x; defaults to 0.5
sprite.setDisplayOrigin(x, y)    // set origin in pixels; y defaults to x
sprite.setOriginFromFrame()      // use Frame pivot if set, else 0.5
sprite.updateDisplayOrigin()     // recalculate pixel origin from normalized
Depth component (
src/gameobjects/components/Depth.js
):
js
// Properties
sprite.depth    // default: 0 (higher = renders on top)

// Methods
sprite.setDepth(value)
sprite.setToTop()              // move to top of display list (no depth change)
sprite.setToBack()             // move to back of display list (no depth change)
sprite.setAbove(gameObject)    // position above another object in the list
sprite.setBelow(gameObject)    // position below another object in the list
Setting
depth
queues a depth sort in the Scene. The
setToTop
/
setToBack
/
setAbove
/
setBelow
methods change display list position without modifying the
depth
value.
Origin组件(
src/gameobjects/components/Origin.js
):
js
// 属性(归一化0-1)
sprite.originX          // 默认值:0.5(中心)
sprite.originY          // 默认值:0.5(中心)
sprite.displayOriginX   // 像素值(originX * width)
sprite.displayOriginY   // 像素值(originY * height)

// 方法
sprite.setOrigin(x, y)           // 若省略y,默认与x相同;默认值为0.5
sprite.setDisplayOrigin(x, y)    // 以像素为单位设置原点;若省略y,默认与x相同
sprite.setOriginFromFrame()      // 使用帧的支点(若已设置),否则为0.5
sprite.updateDisplayOrigin()     // 根据归一化值重新计算像素原点
Depth组件(
src/gameobjects/components/Depth.js
):
js
// 属性
sprite.depth    // 默认值:0(值越大,渲染层级越靠上)

// 方法
sprite.setDepth(value)
sprite.setToTop()              // 移至显示列表顶部(不改变depth值)
sprite.setToBack()             // 移至显示列表底部(不改变depth值)
sprite.setAbove(gameObject)    // 移至另一个对象上方
sprite.setBelow(gameObject)    // 移至另一个对象下方
设置
depth
会触发场景中的深度排序。
setToTop
/
setToBack
/
setAbove
/
setBelow
方法仅改变显示列表位置,不修改
depth
值。

Destroying Game Objects

销毁游戏对象

js
sprite.destroy();           // removes from display list, update list, and cleans up
sprite.ignoreDestroy = true; // prevent destruction (you manage lifecycle manually)
sprite.isDestroyed           // boolean, true after destroy() has been called
For Sprites,
destroy()
also calls
this.anims.destroy()
to clean up the AnimationState.
js
sprite.destroy();           // 从显示列表、更新列表中移除并清理资源
sprite.ignoreDestroy = true; // 阻止销毁(需手动管理生命周期)
sprite.isDestroyed           // 布尔值,调用destroy()后为true
对于Sprite,
destroy()
还会调用
this.anims.destroy()
以清理AnimationState。

Additional Components

其他组件

Visible (
src/gameobjects/components/Visible.js
):
js
sprite.visible              // boolean (default: true)
sprite.setVisible(value)    // invisible objects skip rendering but still update
ScrollFactor (
src/gameobjects/components/ScrollFactor.js
):
js
sprite.scrollFactorX        // default: 1 (moves with camera)
sprite.scrollFactorY        // default: 1
sprite.setScrollFactor(x, y)  // 0 = fixed to camera; y defaults to x
BlendMode (
src/gameobjects/components/BlendMode.js
):
js
sprite.blendMode            // default: Phaser.BlendModes.NORMAL
sprite.setBlendMode(value)  // Phaser.BlendModes.ADD, MULTIPLY, SCREEN, ERASE, etc.
Performance note: Changing blend mode breaks WebGL batches. Group objects by blend mode when possible (e.g., render all ADD-mode sprites together) to minimize draw calls.
Visible(
src/gameobjects/components/Visible.js
):
js
sprite.visible              // 布尔值(默认值:true)
sprite.setVisible(value)    // 不可见对象会跳过渲染,但仍会更新
ScrollFactor(
src/gameobjects/components/ScrollFactor.js
):
js
sprite.scrollFactorX        // 默认值:1(随相机移动)
sprite.scrollFactorY        // 默认值:1
sprite.setScrollFactor(x, y)  // 0=固定在相机上;若省略y,默认与x相同
BlendMode(
src/gameobjects/components/BlendMode.js
):
js
sprite.blendMode            // 默认值:Phaser.BlendModes.NORMAL
sprite.setBlendMode(value)  // Phaser.BlendModes.ADD, MULTIPLY, SCREEN, ERASE等
性能提示: 更改混合模式会中断WebGL批处理。尽可能按混合模式分组对象(例如,将所有ADD模式的Sprite放在一起渲染),以最小化绘制调用次数。

Factory Methods

工厂方法

this.add.sprite

this.add.sprite

Source:
src/gameobjects/sprite/SpriteFactory.js
js
// Signature
this.add.sprite(x, y, texture, frame);
ParamTypeRequiredDescription
x
number
YesHorizontal position in world coordinates
y
number
YesVertical position in world coordinates
texture
string | Phaser.Textures.Texture
YesTexture key or Texture instance
frame
string | number
NoFrame name or index within the texture
Returns:
Phaser.GameObjects.Sprite
Internally does:
this.displayList.add(new Sprite(this.scene, x, y, texture, frame))
The Sprite constructor calls:
setTexture
->
setPosition
->
setSizeToFrame
->
setOriginFromFrame
->
initRenderNodes
.
源码:
src/gameobjects/sprite/SpriteFactory.js
js
// 签名
this.add.sprite(x, y, texture, frame);
参数类型是否必填描述
x
number
是世界坐标系中的水平位置
y
number
是世界坐标系中的垂直位置
texture
string | Phaser.Textures.Texture
是纹理键或Texture实例
frame
string | number
否纹理中的帧名称或索引
返回值:
Phaser.GameObjects.Sprite
内部执行逻辑:
this.displayList.add(new Sprite(this.scene, x, y, texture, frame))
Sprite构造函数调用流程:
setTexture
->
setPosition
->
setSizeToFrame
->
setOriginFromFrame
->
initRenderNodes
。

this.add.image

this.add.image

Source:
src/gameobjects/image/ImageFactory.js
js
// Signature
this.add.image(x, y, texture, frame);
ParamTypeRequiredDescription
x
number
YesHorizontal position in world coordinates
y
number
YesVertical position in world coordinates
texture
string | Phaser.Textures.Texture
YesTexture key or Texture instance
frame
string | number
NoFrame name or index within the texture
Returns:
Phaser.GameObjects.Image
Internally does:
this.displayList.add(new Image(this.scene, x, y, texture, frame))
The Image constructor calls the same init sequence as Sprite:
setTexture
->
setPosition
->
setSizeToFrame
->
setOriginFromFrame
->
initRenderNodes
.
源码:
src/gameobjects/image/ImageFactory.js
js
// 签名
this.add.image(x, y, texture, frame);
参数类型是否必填描述
x
number
是世界坐标系中的水平位置
y
number
是世界坐标系中的垂直位置
texture
string | Phaser.Textures.Texture
是纹理键或Texture实例
frame
string | number
否纹理中的帧名称或索引
返回值:
Phaser.GameObjects.Image
内部执行逻辑:
this.displayList.add(new Image(this.scene, x, y, texture, frame))
Image构造函数调用流程与Sprite相同:
setTexture
->
setPosition
->
setSizeToFrame
->
setOriginFromFrame
->
initRenderNodes
。

Specialized Game Objects

特殊游戏对象

NineSlice

NineSlice

Scalable UI panels with fixed-size corners and stretchable edges/center. Ideal for buttons, panels, and dialog boxes that need to resize without distorting borders.
js
// nineslice(x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight)
const panel = this.add.nineslice(400, 300, 'panel', null, 300, 200, 20, 20, 20, 20);

// Resize at runtime -- corners stay fixed, edges stretch
panel.setSize(500, 400);
可缩放的UI面板,边角尺寸固定,边缘和中心可拉伸。非常适合按钮、面板和对话框等需要调整尺寸但不扭曲边框的元素。
js
// nineslice(x, y, texture, frame, width, height, leftWidth, rightWidth, topHeight, bottomHeight)
const panel = this.add.nineslice(400, 300, 'panel', null, 300, 200, 20, 20, 20, 20);

// 运行时调整尺寸——边角保持固定,边缘拉伸
panel.setSize(500, 400);

TileSprite

TileSprite

Repeating texture that fills an area. Supports atlas frames in v4 and a new
tileRotation
property.
js
const bg = this.add.tileSprite(400, 300, 800, 600, 'grass');

// Scroll the tile in update() for parallax backgrounds
bg.tilePositionX += 0.5;
bg.tilePositionY += 0.25;

// v4: rotate the tile pattern
bg.tileRotation = 0.1;
重复填充区域的纹理。v4版本支持图集帧,并新增
tileRotation
属性。
js
const bg = this.add.tileSprite(400, 300, 800, 600, 'grass');

// 在update()中滚动纹理以实现视差背景
bg.tilePositionX += 0.5;
bg.tilePositionY += 0.25;

// v4特性:旋转纹理图案
bg.tileRotation = 0.1;

Blitter

Blitter

High-performance batched rendering for large numbers of static or semi-static sprites. Blitter children (Bobs) have no rotation, scale, or physics, but render significantly faster than individual Sprites.
js
const blitter = this.add.blitter(0, 0, 'particles');

// Create Bobs (lightweight display objects)
for (let i = 0; i < 1000; i++) {
    const bob = blitter.create(
        Phaser.Math.Between(0, 800),
        Phaser.Math.Between(0, 600),
        'particle_01'   // frame name within the texture
    );
    bob.setAlpha(Math.random());
}
用于大量静态或半静态Sprite的高性能批处理渲染。Blitter的子对象(Bob)不支持旋转、缩放或物理,但渲染速度远快于单个Sprite。
js
const blitter = this.add.blitter(0, 0, 'particles');

// 创建Bob(轻量级显示对象)
for (let i = 0; i < 1000; i++) {
    const bob = blitter.create(
        Phaser.Math.Between(0, 800),
        Phaser.Math.Between(0, 600),
        'particle_01'   // 纹理中的帧名称
    );
    bob.setAlpha(Math.random());
}

Video

Video

Video playback as a game object with position, scale, and filter support.
js
// Load in preload:
this.load.video('intro', 'intro.mp4');

// Create in create:
const video = this.add.video(400, 300, 'intro');
video.play();
For detailed configuration options, API reference tables, and source file maps, see the reference guide.
作为游戏对象的视频播放组件,支持位置、缩放和滤镜。
js
// 在preload中加载:
this.load.video('intro', 'intro.mp4');

// 在create中创建:
const video = this.add.video(400, 300, 'intro');
video.play();
如需详细配置选项、API参考表格和源码文件映射,请查看参考指南。