sprites-and-images
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSprites 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: , , ,
Related skills: ../loading-assets/SKILL.md, ../animations/SKILL.md, ../physics-arcade/SKILL.md, ../game-object-components/SKILL.md
src/gameobjects/sprite/src/gameobjects/image/src/gameobjects/GameObject.jssrc/gameobjects/components/在Phaser 4中创建和操作Sprite与Image游戏对象——包括工厂方法、纹理/帧选择、组件混入系统,以及常见视觉操作(位置、缩放、旋转、着色、翻转、透明度、原点、深度)。
核心源码路径: , , ,
相关技能: ../loading-assets/SKILL.md, ../animations/SKILL.md, ../physics-arcade/SKILL.md, ../game-object-components/SKILL.md
src/gameobjects/sprite/src/gameobjects/image/src/gameobjects/GameObject.jssrc/gameobjects/components/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 and share the same set of component mixins. The only difference is that Sprite includes an instance () and animation convenience methods (, , , etc.).
GameObjectAnimationStatesprite.animsplaystopchain| Feature | Image | Sprite |
|---|---|---|
| Static texture display | Yes | Yes |
| Tint, alpha, flip, scale, rotate | Yes | Yes |
| Physics body | Yes | Yes |
| Input / hit area | Yes | Yes |
Animation ( | No | Yes |
| No | Yes (updates animation) |
Added to Scene | No | Yes |
Rule of thumb: Use for anything that does not need frame-by-frame animation. It skips the per-frame cost and has a smaller API surface. Use only when you need the Animation component.
ImagepreUpdateSprite两者均继承自,并共享相同的组件混入集合。唯一区别在于Sprite包含实例()以及动画便捷方法(、、等)。
GameObjectAnimationStatesprite.animsplaystopchain| 特性 | Image | Sprite |
|---|---|---|
| 静态纹理显示 | 是 | 是 |
| 着色、透明度、翻转、缩放、旋转 | 是 | 是 |
| 物理体 | 是 | 是 |
| 输入/碰撞区域 | 是 | 是 |
动画( | 否 | 是 |
每帧调用 | 否 | 是(更新动画) |
添加至场景 | 否 | 是 |
经验法则: 对于不需要逐帧动画的元素,使用。它跳过每帧的开销,且API更精简。仅在需要动画组件时使用。
ImagepreUpdateSpriteThe Component Mixin System
组件混入系统
Phaser builds Game Object classes by mixing component objects into the prototype. Both and share this identical Mixins array (sourced from and ):
SpriteImagesrc/gameobjects/sprite/Sprite.jssrc/gameobjects/image/Image.jsMixins: [
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 class itself mixes in:
GameObjectMixins: [
Components.Filters,
Components.RenderSteps
]Each component adds specific properties and methods to every instance. For example, adds , , , , , etc. The full list of available components is in .
Components.TransformxyscalerotationsetPosition()src/gameobjects/components/index.jsKey point for agents: When you see a method like on a Sprite, it comes from , not from the Sprite class itself. The component source file is the authoritative reference for that method's signature and behavior.
setAlpha()Components.AlphaPhaser通过将组件对象混入原型来构建游戏对象类。和共享完全相同的混入数组(源自和):
SpriteImagesrc/gameobjects/sprite/Sprite.jssrc/gameobjects/image/Image.jsMixins: [
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 // 渲染相关(两类对象不同)
]基础类自身混入了:
GameObjectMixins: [
Components.Filters,
Components.RenderSteps
]每个组件会为实例添加特定属性和方法。例如,添加了、、、、等属性和方法。完整组件列表可查看。
Components.TransformxyscalerotationsetPosition()src/gameobjects/components/index.jsAgent关键提示: 当你在Sprite上看到这类方法时,它来自而非Sprite类本身。组件源码文件是该方法签名和行为的权威参考。
setAlpha()Components.AlphaTexture and Frame
纹理与帧
Both Sprite and Image use the component which provides:
TextureCrop- -- the
textureinstancePhaser.Textures.Texture - -- the current
frameinstancePhaser.Textures.Frame - -- change the texture (and optionally the frame)
setTexture(key, frame) - -- change only the frame
setFrame(frame, updateSize, updateOrigin) - -- crop a rectangular region of the texture
setCrop(x, y, width, height) - -- boolean, toggle cropping on/off after
isCroppedsetCrop
The parameter in factory methods and constructors accepts either a string key (as registered in the Texture Manager) or a instance.
texturePhaser.Textures.TextureThe parameter accepts a string name or numeric index into the texture's frame collection. If omitted, the base frame (frame 0 / ) is used.
frame'__BASE'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
工厂方法和构造函数中的参数可接受字符串键(在纹理管理器中注册过)或实例。
texturePhaser.Textures.Textureframe'__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.jsjs
// 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} objectSize component ():
src/gameobjects/components/Size.jsjs
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 frameTransform组件():
src/gameobjects/components/Transform.jsjs
// 属性(均支持读写)
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.jsjs
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 0Transform组件(续):
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) // 默认值:0Tinting and Alpha
着色与透明度
Tint component () -- WebGL only:
src/gameobjects/components/Tint.jsjs
// 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 modePhaser 4 change: is removed. Use instead.
setTintFill()setTint(color).setTintMode(Phaser.TintModes.FILL)Alpha component ():
src/gameobjects/components/Alpha.jsjs
// 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 to 0 clears the render flag so the object is not drawn. Setting it back to any non-zero value restores it.
alphaTint组件()——仅支持WebGL:
src/gameobjects/components/Tint.jsjs
// 属性
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.jsjs
// 属性
sprite.alpha // 全局透明度0-1(默认值:1)
sprite.alphaTopLeft // 四角独立透明度(仅支持WebGL)
sprite.alphaTopRight
sprite.alphaBottomLeft
sprite.alphaBottomRight
// 方法
sprite.setAlpha(topLeft, topRight, bottomLeft, bottomRight)
// 若仅传入topLeft,则为整个对象统一应用该值
sprite.clearAlpha() // 重置为1(完全不透明)将设为0会清除渲染标记,对象将不再被绘制。将其设为任意非零值会恢复渲染。
alphaFlipping
翻转
Flip component ():
src/gameobjects/components/Flip.jsjs
// 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 falseFlipping 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.jsjs
// 属性
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.jsjs
// 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 normalizedDepth component ():
src/gameobjects/components/Depth.jsjs
// 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 listSetting queues a depth sort in the Scene. The /// methods change display list position without modifying the value.
depthsetToTopsetToBacksetAbovesetBelowdepthOrigin组件():
src/gameobjects/components/Origin.jsjs
// 属性(归一化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.jsjs
// 属性
sprite.depth // 默认值:0(值越大,渲染层级越靠上)
// 方法
sprite.setDepth(value)
sprite.setToTop() // 移至显示列表顶部(不改变depth值)
sprite.setToBack() // 移至显示列表底部(不改变depth值)
sprite.setAbove(gameObject) // 移至另一个对象上方
sprite.setBelow(gameObject) // 移至另一个对象下方设置会触发场景中的深度排序。///方法仅改变显示列表位置,不修改值。
depthsetToTopsetToBacksetAbovesetBelowdepthDestroying 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 calledFor Sprites, also calls to clean up the AnimationState.
destroy()this.anims.destroy()js
sprite.destroy(); // 从显示列表、更新列表中移除并清理资源
sprite.ignoreDestroy = true; // 阻止销毁(需手动管理生命周期)
sprite.isDestroyed // 布尔值,调用destroy()后为true对于Sprite,还会调用以清理AnimationState。
destroy()this.anims.destroy()Additional Components
其他组件
Visible ():
src/gameobjects/components/Visible.jsjs
sprite.visible // boolean (default: true)
sprite.setVisible(value) // invisible objects skip rendering but still updateScrollFactor ():
src/gameobjects/components/ScrollFactor.jsjs
sprite.scrollFactorX // default: 1 (moves with camera)
sprite.scrollFactorY // default: 1
sprite.setScrollFactor(x, y) // 0 = fixed to camera; y defaults to xBlendMode ():
src/gameobjects/components/BlendMode.jsjs
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.jsjs
sprite.visible // 布尔值(默认值:true)
sprite.setVisible(value) // 不可见对象会跳过渲染,但仍会更新ScrollFactor():
src/gameobjects/components/ScrollFactor.jsjs
sprite.scrollFactorX // 默认值:1(随相机移动)
sprite.scrollFactorY // 默认值:1
sprite.setScrollFactor(x, y) // 0=固定在相机上;若省略y,默认与x相同BlendMode():
src/gameobjects/components/BlendMode.jsjs
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.jsjs
// Signature
this.add.sprite(x, y, texture, frame);| Param | Type | Required | Description |
|---|---|---|---|
| | Yes | Horizontal position in world coordinates |
| | Yes | Vertical position in world coordinates |
| | Yes | Texture key or Texture instance |
| | No | Frame name or index within the texture |
Returns:
Phaser.GameObjects.SpriteInternally does:
this.displayList.add(new Sprite(this.scene, x, y, texture, frame))The Sprite constructor calls: -> -> -> -> .
setTexturesetPositionsetSizeToFramesetOriginFromFrameinitRenderNodes源码:
src/gameobjects/sprite/SpriteFactory.jsjs
// 签名
this.add.sprite(x, y, texture, frame);| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| | 是 | 世界坐标系中的水平位置 |
| | 是 | 世界坐标系中的垂直位置 |
| | 是 | 纹理键或Texture实例 |
| | 否 | 纹理中的帧名称或索引 |
返回值:
Phaser.GameObjects.Sprite内部执行逻辑:
this.displayList.add(new Sprite(this.scene, x, y, texture, frame))Sprite构造函数调用流程: -> -> -> -> 。
setTexturesetPositionsetSizeToFramesetOriginFromFrameinitRenderNodesthis.add.image
this.add.image
Source:
src/gameobjects/image/ImageFactory.jsjs
// Signature
this.add.image(x, y, texture, frame);| Param | Type | Required | Description |
|---|---|---|---|
| | Yes | Horizontal position in world coordinates |
| | Yes | Vertical position in world coordinates |
| | Yes | Texture key or Texture instance |
| | No | Frame name or index within the texture |
Returns:
Phaser.GameObjects.ImageInternally does:
this.displayList.add(new Image(this.scene, x, y, texture, frame))The Image constructor calls the same init sequence as Sprite: -> -> -> -> .
setTexturesetPositionsetSizeToFramesetOriginFromFrameinitRenderNodes源码:
src/gameobjects/image/ImageFactory.jsjs
// 签名
this.add.image(x, y, texture, frame);| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| | 是 | 世界坐标系中的水平位置 |
| | 是 | 世界坐标系中的垂直位置 |
| | 是 | 纹理键或Texture实例 |
| | 否 | 纹理中的帧名称或索引 |
返回值:
Phaser.GameObjects.Image内部执行逻辑:
this.displayList.add(new Image(this.scene, x, y, texture, frame))Image构造函数调用流程与Sprite相同: -> -> -> -> 。
setTexturesetPositionsetSizeToFramesetOriginFromFrameinitRenderNodesSpecialized 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 property.
tileRotationjs
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版本支持图集帧,并新增属性。
tileRotationjs
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参考表格和源码文件映射,请查看参考指南。