针对单个游戏我们直接在初始化的时候修改Laya.stage.screenMode的值就可以了
Laya.stage.screenMode = "horizontal"//横屏
Laya.stage.screenMode = "vertical"//竖屏
如果想批量修改的话,首先我们需要重写库里的方法,这里封装了一个函数
const replaceProperty = (owner, properties) => {
if (owner == null)
return;
properties.forEach((item) => {
const target = item.target != null ? item.target : owner;
const newName = item.newName != null ? item.newName : item.name;
const sameTarget = target === owner;
if (item.customFunction != null) {
owner[item.name] = function () {
return item.customFunction.call(this, ...arguments);
};
}
else if (item.customSetter != null || item.customGetter != null) {
const hasSetter = item.customSetter != null;
const hasGetter = item.customGetter != null;
if (hasSetter && hasGetter) {
Object.defineProperty(owner, item.name, {
get() {
return item.customGetter.call(this);
},
set(v) {
item.customSetter.call(this, v);
},
enumerable: false,
});
}
else if (hasSetter) {
Object.defineProperty(owner, item.name, {
set(v) {
item.customSetter.call(this, v);
},
enumerable: false,
});
}
else if (hasGetter) {
Object.defineProperty(owner, item.name, {
get() {
return item.customGetter.call(this);
},
enumerable: false,
});
}
}
else {
Object.defineProperty(owner, item.name, {
get() {
return sameTarget ? this[newName] : target[newName];
},
set(v) {
if (sameTarget) {
this[newName] = v;
}
else {
target[newName] = v;
}
},
enumerable: false,
});
}
});
};
我们直接在进入游戏后去调用这个方法修改screenMode的值,就可以对游戏进行强制横屏了
replaceProperty(Laya.stage, [
{
name: 'screenMode',
customGetter() {
return "horizontal";//"vertical"
},
customSetter(value) {
console.log("customSetter")
},
},
])
后面再考虑到手机翻转,再设置一个监听就可以了
window.addEventListener('orientationchange', function (event) {
if (window.orientation == 180 || window.orientation == 0) {
// alert("竖屏"); //竖屏事件处理
Laya.stage.screenMode = "vertical";
Laya.stage._changeCanvasSize();
}
if (window.orientation == 90 || window.orientation == -90) {
// alert("横屏"); //横屏事件处理
Laya.stage.screenMode = "horizontal";
Laya.stage._changeCanvasSize();
}
});