使用Phaser.Scale.EXACT_FIT创建等比例正方形遇宽度过长问题求解决方案
Phaser中使用EXACT_FIT模式创建等比例正方形的解决办法
1. 固定游戏基础尺寸为正方形
先将游戏的原生尺寸设为正方形(可根据需求调整数值,比如800x800),确保游戏内容的基准比例为正方形:
const config = { type: Phaser.CANVAS, width: 800, height: 800, scale: { mode: Phaser.Scale.EXACT_FIT, parent: 'game-container', width: 800, height: 800 }, physics: { default: 'arcade' }, scene: [PreloadScene, PlayScene, QuestionScene] };
2. 动态适配屏幕的正方形容器
如果需要适配不同尺寸的屏幕,动态计算屏幕的最小边作为正方形边长,同时设置父容器和游戏的显示尺寸:
// 取屏幕宽高中的较小值作为正方形边长 const squareSize = Math.min(window.screen.width, window.screen.height); // 调整父容器为正方形并居中(可选) const gameContainer = document.getElementById('game-container'); gameContainer.style.width = `${squareSize}px`; gameContainer.style.height = `${squareSize}px`; gameContainer.style.margin = '0 auto'; // 更新游戏配置 const config = { type: Phaser.CANVAS, width: 800, height: 800, scale: { mode: Phaser.Scale.EXACT_FIT, parent: 'game-container', width: squareSize, height: squareSize }, physics: { default: 'arcade' }, scene: [PreloadScene, PlayScene, QuestionScene] };
3. 场景内通过相机限制可视区域(无需修改容器)
如果不想调整父容器尺寸,可在场景中设置相机,只渲染正方形区域:
在对应场景的create方法中添加:
create() { const gameWidth = this.game.config.width; const gameHeight = this.game.config.height; const squareSide = Math.min(gameWidth, gameHeight); // 设置相机视口为正方形,居中显示 this.cameras.main.setViewport( (gameWidth - squareSide) / 2, (gameHeight - squareSide) / 2, squareSide, squareSide ); }
内容的提问来源于stack exchange,提问作者Newboy11
相关产品推荐
相关产品推荐

