我正在使用 PIXI.js 构建一个游戏,它在我的桌面上看起来不错,但在我的手机上玩时,FOV 非常小,所以我几乎看不到周围的环境。同样,在大显示器上,用户可以看到太多内容,这很不公平。
有没有办法可以利用显示窗口大小来缩小摄像头,以便每个人都能公平地看到相同的周围环境?
在 this Github 问题上找到答案。
阅读 pixi-viewport 的源代码后,我想出了一个非常适合我的目的的解决方案。以下函数将根据提供的虚拟分辨率将舞台及其内容缩放到目标设备窗口。虚拟分辨率决定了视图的像素缩放因子和纵横比,无论目标设备窗口尺寸如何,虚拟分辨率都将始终保持不变。当 center = true 时,全局原点将始终位于屏幕中间。
function fit(center: boolean, stage: PIXI.Container, screenWidth: number, screenHeight: number, virtualWidth: number, virtualHeight: number) {
stage.scale.x = screenWidth / virtualWidth
stage.scale.y = screenHeight / virtualHeight
if (stage.scale.x < stage.scale.y) {
stage.scale.y = stage.scale.x
} else {
stage.scale.x = stage.scale.y
}
const virtualWidthInScreenPixels = virtualWidth * stage.scale.x
const virtualHeightInScreenPixels = virtualHeight * stage.scale.y
const centerXInScreenPixels = screenWidth * 0.5;
const centerYInScreenPixels = screenHeight * 0.5;
if (center) {
stage.position.x = centerXInScreenPixels;
stage.position.y = centerYInScreenPixels;
} else {
stage.position.x = centerXInScreenPixels - virtualWidthInScreenPixels * 0.5;
stage.position.y = centerYInScreenPixels - virtualHeightInScreenPixels * 0.5;
}
}
在窗口调整大小功能上,您可以这样调用它:
window.onresize = () => {
this.pixiInstance.renderer.resize(pixiDiv.clientWidth, pixiDiv.clientHeight)
fit(true, this.pixiInstance.stage, pixiDiv.clientWidth, pixiDiv.clientHeight, this.virtual_w, this.virtual_h)
}