Phaser AnimationFrame尺寸不一致时如何设置帧相对显示位置
解决Phaser动画帧尺寸不一致时的自定义偏移问题
Phaser的Animation配置本身不支持直接给单帧加px/py这类偏移参数,但可以通过以下两种方式实现你要的效果:
方法一:监听动画更新事件,动态调整精灵偏移
先把每个帧的偏移数据单独存起来,然后在动画播放时,根据当前帧的key来设置精灵的位置偏移。
示例代码:
// 1. 定义各帧的偏移数据 const frameOffsets = { cat1: { px: -100, py: 0 }, cat2: { px: -50, py: -30 }, cat3: { px: -50, py: -30 }, cat4: { px: -50, py: -30 } }; // 2. 创建动画(和原代码基本一致) this.anims.create({ key: 'snooze', frames: [ { key: 'cat1' }, { key: 'cat2' }, { key: 'cat3' }, { key: 'cat4', duration: 50 } ], frameRate: 8, repeat: -1 }); // 3. 创建精灵并播放动画 const catSprite = this.add.sprite(400, 300, 'cat1'); catSprite.play('snooze'); // 4. 监听动画更新事件,动态设置偏移 catSprite.on('animationupdate', (anim, frame) => { const offset = frameOffsets[frame.key]; if (offset) { // 基于精灵原点调整偏移,或直接修改绝对位置二选一 catSprite.setOrigin(0.5 + offset.px / frame.width, 0.5 + offset.py / frame.height); // 或者直接调整绝对位置: // catSprite.x = 400 + offset.px; // catSprite.y = 300 + offset.py; } });
方法二:使用容器承载精灵,调整容器内的精灵位置
把精灵放到Phaser.Container里,动画切换帧时,调整精灵在容器内的坐标,容器作为对外的显示对象,位置保持不变。
示例代码:
// 1. 定义各帧的偏移数据 const frameOffsets = { cat1: { px: -100, py: 0 }, cat2: { px: -50, py: -30 }, cat3: { px: -50, py: -30 }, cat4: { px: -50, py: -30 } }; // 2. 创建动画 this.anims.create({ key: 'snooze', frames: [ { key: 'cat1' }, { key: 'cat2' }, { key: 'cat3' }, { key: 'cat4', duration: 50 } ], frameRate: 8, repeat: -1 }); // 3. 创建容器和精灵 const catContainer = this.add.container(400, 300); const catSprite = this.add.sprite(0, 0, 'cat1'); catContainer.add(catSprite); catSprite.play('snooze'); // 4. 监听动画更新,调整精灵在容器内的位置 catSprite.on('animationupdate', (anim, frame) => { const offset = frameOffsets[frame.key]; if (offset) { catSprite.x = offset.px; catSprite.y = offset.py; } });
额外提示
如果你的图集是用TexturePacker这类工具打包的,可以在打包时直接给每个帧设置offset属性,Phaser加载图集时会自动读取这些偏移值,这样就不用手动定义frameOffsets,直接使用即可。
内容的提问来源于stack exchange,提问作者loosir
相关产品推荐
相关产品推荐

