Phaser3js forceLandscapeScene实现强制横屏

1,559 阅读1分钟

Phaser3js forceLandscapeScene实现强制横屏效果

# 原理

基于phaser3网上没有相关的横屏效果,研究了下文档,开发了横屏插件

根据移动端横竖屏状态来旋转游戏场景(scene)
根据初始化横竖屏状态来旋转角度,进行缩放比例调整
# 使用方法
1.npm install phaser-forcelandscape
**Boot.js 继承ForceLandscapeScene**

class BootScene extends ForceLandscapeScene {  
    constructor(props) {    
        super();  
    }  
    preload() {    
        this.load.image("logo", logoImg);  
    }  
    renderStartText() {    
        const { width, height } = this.scale.baseSize;    
        const startText = this.add.text( width / 2, height / 1.2, "PUSH ENTER TO START");
        startText.setOrigin(0.5, 0.5);    
        startText.alpha = 1;    
        //绑定事件前提,开启交互功能   
        startText.setInteractive();  
        startText.on("pointerup", function () {
            console.log("start game");      
            window.game.scene.sleep("boot");    
        });    
        const flash = this.tweens.add({ 
            targets: [startText],     
            props: {        alpha: 0,      },      
            loop: -1,      
            duration: 1000,    
        });  
    }  
    create() {    
        const { width, height } = this.scale.baseSize;    
        this.add.image(width / 2, height / 2.4, "logo");    
        this.renderStartText();  
    }
}
**index.html**

移动端header信息

...
<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"    name="viewport">
 <style>
  body {      display: flex;      align-items: center;      justify-content: center;    }    canvas {      margin: 0 auto;      display: block;    }</style>
...
**index.js**
// 判断初始化时候是否屏幕横竖状态 
const isLandscape = window.orientation == 90 || window.orientation == -90;  
// 移动端高宽比例  
let windowRatio =    document.documentElement.clientWidth / document.documentElement.clientHeight;  
windowRatio = isLandscape ? 1 / windowRatio : windowRatio;    

// 根据移动端实际高度选择横屏时候合适的canvas宽度 
//const width =document.documentElement.clientWidth-100 
const width = 650;//相对750  
const height = width * windowRatio;    
const config = {    
    type: Phaser.AUTO,    
    physics: {      default: "arcade",    },    
    scale: {      
        model: Phaser.Scale.FIT,      
        width,      
        height,      
        parent: "root",   
    },  
};  
const game = new Phaser.Game(config);  
game.scene.add("boot", BootScene, true);
#效果
横竖屏切换保持横屏状态
1.竖屏

2.横屏