You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Phaser中Tiled地图无法加载,仅显示背景色求助

解决方案

问题出在等距地图的坐标系统与正交地图不同,默认的图层定位和画布尺寸设置导致瓦片处于可视区域之外,调整相机和画布配置即可解决:

修改后的index.html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Phaser Tilemap</title>
    <script src="https://cdn.jsdelivr.net/npm/phaser@3.60.0/dist/phaser.min.js"></script>
</head>
<body>
    <button id="startButton">Start Game</button>
    <script>
        class TilemapScene extends Phaser.Scene {
            preload() {
                this.load.image('tiles', 'assets/tilesets/emp_1.png');
                this.load.tilemapTiledJSON('tilemap', 'assets/maps/demo.json');
            }
            create() {
                const map = this.make.tilemap({ key: 'tilemap' });
                const tileset = map.addTilesetImage('emp_1', 'tiles');
                const layer = map.createLayer('layer', tileset);

                // 设置相机边界为地图实际像素范围
                this.cameras.main.setBounds(0, 0, map.widthInPixels, map.heightInPixels);
                // 定位相机到唯一瓦片的位置(对应地图第15行第2列)
                this.cameras.main.centerOn(64, map.heightInPixels - 32);

                // 可选:添加相机拖拽功能,方便查看地图
                this.input.on('pointerdown', () => this.cameras.main.startFollow(this.input.activePointer));
                this.input.on('pointerup', () => this.cameras.main.stopFollow());
            }
        }

        const config = {
            type: Phaser.AUTO,
            width: 800,
            height: 600,
            backgroundColor: '#87CEEB',
            scene: TilemapScene,
            input: { mouse: true }
        };

        document.getElementById('startButton').addEventListener('click', () => {
            document.getElementById('startButton').style.display = 'none';
            new Phaser.Game(config);
        });
    </script>
</body>
</html>

关键调整说明

  1. 相机边界与定位:

    • 用map.widthInPixels和map.heightInPixels获取等距地图的实际像素尺寸,设置相机可移动范围。
    • 通过centerOn将相机定位到瓦片所在的像素坐标,确保瓦片出现在可视区域内。
  2. 画布尺寸优化:

    • 放弃硬套瓦片数量×单瓦片尺寸的正交地图计算方式,设置更合理的窗口尺寸,配合相机拖拽查看全地图。
  3. 可选交互增强:

    • 添加鼠标拖拽相机的功能,方便自由查看地图的不同区域。

内容的提问来源于stack exchange,提问作者greaye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 11:23:09