pixijs-gamedev

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

PixiJS Game Development

PixiJS 游戏开发

When to Use

适用场景

When the user is building 2D games or interactive graphics with PixiJS, asks about sprite management, animation loops, event handling, or says "create a PixiJS app" or "add sprites" or "animate this".
当用户使用PixiJS构建2D游戏或交互式图形、询问精灵管理、动画循环、事件处理,或者提到「创建PixiJS应用」、「添加精灵」、「为这个内容添加动画」时使用。

Instructions

使用指南

1. Application Setup

1. 应用初始化

  • Create an
    Application
    instance and append its canvas to the DOM
  • Always
    await app.init({ width, height, background })
    before using the app
  • Use
    Application.resize()
    or
    resizeTo: window
    for responsive canvas
  • Prefer WebGL renderer (default); PixiJS falls back to Canvas automatically
  • Set
    antialias: true
    for smoother edges at a slight performance cost
  • Use
    resolution: window.devicePixelRatio
    for sharp rendering on HiDPI displays
  • 创建
    Application
    实例并将它的canvas元素挂载到DOM中
  • 使用应用前必须先执行
    await app.init({ width, height, background })
    初始化
  • 使用
    Application.resize()
    或者配置
    resizeTo: window
    实现响应式canvas
  • 优先使用WebGL渲染器(默认选项),PixiJS会自动降级到Canvas渲染
  • 设置
    antialias: true
    以获得更平滑的边缘,会带来轻微的性能损耗
  • 配置
    resolution: window.devicePixelRatio
    以在高DPI显示屏上实现清晰渲染

2. Sprites and Textures

2. 精灵与纹理

  • Load textures via
    Assets.load('path/to/image.png')
    — returns a promise
  • Create sprites with
    Sprite.from(texture)
    or
    new Sprite(texture)
  • Set
    anchor.set(0.5)
    to center the sprite's origin for rotation and scaling
  • Use
    Spritesheet
    for atlas-based animations — define frames in a JSON descriptor
  • Avoid creating textures from the same source repeatedly;
    Assets
    caches automatically
  • Use
    Texture.EMPTY
    as a placeholder while assets load
  • 通过
    Assets.load('path/to/image.png')
    加载纹理,该方法返回一个promise
  • 使用
    Sprite.from(texture)
    或者
    new Sprite(texture)
    创建精灵
  • 设置
    anchor.set(0.5)
    将精灵的原点设为中心,方便旋转和缩放操作
  • 使用
    Spritesheet
    实现图集动画,在JSON描述文件中定义帧信息
  • 避免重复从相同源创建纹理,
    Assets
    会自动缓存资源
  • 资源加载过程中使用
    Texture.EMPTY
    作为占位符

3. Containers and Display Hierarchy

3. 容器与显示层级

  • Container
    is the base display object — use it to group and transform children
  • Children inherit parent transforms (position, scale, rotation, alpha)
  • Use
    sortableChildren: true
    and set
    zIndex
    for draw-order control
  • Remove off-screen objects from the stage to avoid unnecessary rendering
  • Use
    ParticleContainer
    for thousands of identical sprites (limited features, high speed)
  • Container
    是基础显示对象,可用于对子元素进行分组和变换操作
  • 子元素会继承父元素的变换属性(位置、缩放、旋转、透明度)
  • 配置
    sortableChildren: true
    并设置
    zIndex
    来控制绘制顺序
  • 将不在屏幕内的对象从舞台移除,避免不必要的渲染
  • 针对数千个相同精灵的场景使用
    ParticleContainer
    ,功能有限但性能极高

4. Animation

4. 动画

  • Use
    app.ticker.add((ticker) => { ... })
    for the main game loop
  • ticker.deltaTime
    gives frame-time-normalized delta (1.0 at target FPS)
  • For complex tweening, integrate GSAP:
    gsap.to(sprite, { x: 200, duration: 1 })
  • Use
    AnimatedSprite
    for frame-based animations from spritesheets
  • Control playback:
    animatedSprite.play()
    ,
    .stop()
    ,
    .gotoAndPlay(frame)
  • Set
    animationSpeed
    to control frame rate independently of the ticker
  • 使用
    app.ticker.add((ticker) => { ... })
    实现主游戏循环
  • ticker.deltaTime
    提供按帧率归一化的时间差(目标帧率下数值为1.0)
  • 复杂补间动画可集成GSAP:
    gsap.to(sprite, { x: 200, duration: 1 })
  • 使用
    AnimatedSprite
    实现基于精灵图集的帧动画
  • 控制播放的方法:
    animatedSprite.play()
    .stop()
    .gotoAndPlay(frame)
  • 设置
    animationSpeed
    可以独立于ticker控制动画帧率

5. Interaction and Events

5. 交互与事件

  • Set
    eventMode = 'static'
    on any display object to receive pointer events
  • Listen with
    .on('pointerdown', handler)
    — works for mouse and touch
  • Use
    hitArea
    to define custom interaction regions (Circle, Rectangle, Polygon)
  • For drag: track
    pointerdown
    globalpointermove
    pointerup
    on
    app.stage
  • Set
    cursor = 'pointer'
    for interactive elements
  • Disable interaction on non-interactive children to improve event performance
  • 为任意显示对象设置
    eventMode = 'static'
    即可接收指针事件
  • 通过
    .on('pointerdown', handler)
    监听事件,同时适配鼠标和触摸操作
  • 使用
    hitArea
    定义自定义交互区域(圆形、矩形、多边形)
  • 拖拽实现逻辑:在
    app.stage
    上监听
    pointerdown
    globalpointermove
    pointerup
    事件序列
  • 为可交互元素设置
    cursor = 'pointer'
  • 禁用不可交互子元素的交互能力以提升事件处理性能

6. Graphics and Drawing

6. 图形与绘制

  • new Graphics()
    for vector shapes —
    rect()
    ,
    circle()
    ,
    moveTo()
    /
    lineTo()
  • Chain drawing calls:
    graphics.rect(0, 0, 100, 50).fill(0xff0000).stroke(0x000000)
  • Use
    GraphicsContext
    to share drawing instructions across multiple Graphics objects
  • For static shapes, consider rendering to a texture with
    app.renderer.generateTexture()
  • 使用
    new Graphics()
    绘制矢量图形,支持
    rect()
    circle()
    moveTo()
    /
    lineTo()
    等方法
  • 支持链式调用绘制方法:
    graphics.rect(0, 0, 100, 50).fill(0xff0000).stroke(0x000000)
  • 使用
    GraphicsContext
    可以在多个Graphics对象之间共享绘制指令
  • 针对静态图形,可以考虑使用
    app.renderer.generateTexture()
    渲染为纹理使用

7. Filters and Effects

7. 滤镜与效果

  • Apply filters via
    displayObject.filters = [new BlurFilter(4)]
  • Common filters:
    BlurFilter
    ,
    ColorMatrixFilter
    ,
    DisplacementFilter
  • Chain multiple filters in the array — they apply in order
  • Filters are GPU-intensive; limit their use on mobile or low-end devices
  • Use
    AlphaFilter
    for fading groups without affecting individual child alpha
  • 通过
    displayObject.filters = [new BlurFilter(4)]
    为对象应用滤镜
  • 常用滤镜:
    BlurFilter
    ColorMatrixFilter
    DisplacementFilter
  • 可以在数组中串联多个滤镜,会按顺序生效
  • 滤镜对GPU性能消耗较高,在移动端或低端设备上需控制使用量
  • 使用
    AlphaFilter
    实现组透明度渐变,不会影响子元素自身的透明度设置

8. Asset Loading

8. 资源加载

  • Use
    Assets.add({ alias, src })
    then
    Assets.load(alias)
    for named assets
  • Bundle assets:
    Assets.addBundle('game', { bg: 'bg.png', hero: 'hero.png' })
  • Load bundles with
    await Assets.loadBundle('game')
    — shows progress via callback
  • Supported formats: PNG, JPG, WebP, SVG, JSON (spritesheets), MP3/OGG (via plugins)
  • Preload critical assets before showing the game; lazy-load secondary assets
  • 使用
    Assets.add({ alias, src })
    注册资源,之后可通过
    Assets.load(alias)
    按别名加载
  • 资源打包方法:
    Assets.addBundle('game', { bg: 'bg.png', hero: 'hero.png' })
  • 使用
    await Assets.loadBundle('game')
    加载资源包,可通过回调获取加载进度
  • 支持的格式:PNG、JPG、WebP、SVG、JSON(精灵图集)、MP3/OGG(需插件支持)
  • 展示游戏前预加载核心资源,非核心资源可延迟加载

9. Performance Tips

9. 性能优化建议

  • Use
    ParticleContainer
    for large numbers of simple sprites (10k+)
  • Minimize filter usage; each filter causes a render-texture pass
  • Pool and reuse objects instead of creating/destroying frequently
  • Use texture atlases to reduce draw calls (batch rendering)
  • Call
    destroy()
    on removed display objects to free GPU memory
  • Profile with
    app.ticker.FPS
    and browser DevTools Performance tab
  • Avoid changing
    blendMode
    frequently — it breaks batching
  • 针对大量简单精灵(1万以上)使用
    ParticleContainer
  • 减少滤镜使用,每个滤镜都会触发一次渲染纹理流程
  • 采用对象池复用对象,避免频繁创建和销毁对象
  • 使用纹理图集减少绘制调用(批处理渲染)
  • 对移除的显示对象调用
    destroy()
    释放GPU内存
  • 使用
    app.ticker.FPS
    和浏览器开发者工具的性能面板进行性能分析
  • 避免频繁修改
    blendMode
    ,会中断批处理

References

参考资料

Examples

示例

User: "Set up a basic PixiJS game with a moving character" Agent: Creates an Application, loads a character spritesheet via Assets, creates an AnimatedSprite, adds it to the stage, and uses
app.ticker.add()
to update position based on keyboard input. Sets
eventMode
on the stage for input handling.
User: "Add particle effects when the player collects a coin" Agent: Creates a ParticleContainer, spawns small sprites on collection events with randomized velocity and alpha, updates particles in the ticker loop, and removes them when alpha reaches zero. Pools particle sprites for reuse.
User: "Make the game responsive to window resize" Agent: Sets
resizeTo: window
on the Application, recalculates game object positions relative to
app.screen.width/height
, and uses a resize observer to reposition UI elements proportionally.
用户: "搭建一个带有可移动角色的基础PixiJS游戏" Agent: 创建Application实例,通过Assets加载角色精灵图集,创建AnimatedSprite并添加到舞台,使用
app.ticker.add()
根据键盘输入更新角色位置。为舞台设置
eventMode
支持输入处理。
用户: "玩家收集金币时添加粒子效果" Agent: 创建ParticleContainer,在收集事件触发时生成带有随机速度和透明度的小型精灵,在ticker循环中更新粒子状态,透明度降为0时移除粒子。使用对象池复用粒子精灵提升性能。
用户: "让游戏适配窗口大小变化" Agent: 在Application上配置
resizeTo: window
,相对于
app.screen.width/height
重新计算游戏对象位置,使用resize observer按比例重新定位UI元素。",