Phaser 3中如何检测角色站立的Tiles是否属于指定Tiled图层?
解决Phaser 3中仅对指定图层启用向下跳穿平台的问题
你已经实现了Phaser 3中单向平台的向上穿透和向下跳穿逻辑,但当前按下S键时会全局禁用角色下方碰撞,导致所有图层的平台都能被向下穿。要解决这个问题,核心是检测角色当前站立的tile是否属于指定的'platform'图层,只有满足条件时才触发跳穿逻辑。
修改后的实现代码
针对向下跳穿的逻辑部分,调整如下:
// Import map from Tiled this.map = this.make.tilemap({ key: 'myBeautifulMap' }); this.platform = this.map.createLayer('platform', this.tileset); // Apply collision to ALL tiles from this Layer this.platform.setCollisionByExclusion(-1, true); // disable one side collision so character can jump up trough it this.platform.forEachTile(tile => { if (tile.index > 0){ tile.setCollision(false, false, true, false); } }); // Allow jump down - 仅在站在platform图层的平台上时生效 if (this.keyboard.S.isDown) { // 获取角色脚下的世界坐标(向下偏移身体高度,精准检测接触的tile) const footX = this.x; const footY = this.y + this.body.height; // 从platform图层获取对应位置的tile const standingTile = this.platform.getTileAtWorldXY(footX, footY); // 确认是platform图层的有效tile时,才禁用下方碰撞 if (standingTile && standingTile.index > 0) { this.body.checkCollision.down = false; this.scene.time.addEvent({ delay: 400, callback: () => { this.body.checkCollision.down = true; }, callbackScope: this }); } }
关键说明
footY设置为this.y + this.body.height,是为了精准定位角色脚下与平台接触的位置,避免误检测到角色身体区域的tile。standingTile.index > 0用于排除空tile(Tiled中空tile的index通常为-1或0),确保检测到的是实际存在的平台tile。- 经过修改后,只有当角色站在'platform'图层的平台上时,按下S键才会触发向下跳穿,其他图层的tile不会受此逻辑影响。
内容的提问来源于stack exchange,提问作者Koffee
相关产品推荐
相关产品推荐

