动态自动缩放Phaser 3游戏

4

我想知道是否有一种方法可以使用预设分辨率开发我的游戏,例如:

width: 1000,
height: 600,

接下来,无论是HTML还是Phaser,都能够在窗口大小改变时自动缩放画布元素。

我尝试使用了以下代码:

width: window.innerWidth / 2,
height: window.innerHeight / 2,

但这种方法不能保持纵横比,不能正确缩放精灵/图像,需要重新加载页面进行调整,也无法使用特定的x/y坐标。
我已经研究了Phaser 3的缩放管理器和Flex Boxes,但它们似乎不能改变画布大小。

你能为此生成一个虚拟且可用的 fiddle 吗? - SaurabhLP
你尝试如何使用ScaleManager?它应该调整画布大小。 - brae
2个回答

4

我找到的最简单的解决方案如下:

  • 首先,添加以下CSS样式规则:
html, body {
  height: 100%;
}

body {
  margin: 0;
  padding: 0;
  background: #111;
  color: #eee;
  font: caption;
}

canvas {
  /* And see postBoot() in JS */
  width: 100%;
  height: 100%;
  object-fit: contain;
  /* <https://caniuse.com/#feat=object-fit> */
}

#version {
  position: absolute;
  left: 5px;
  top: 605px;
}
  • 第二步,在config对象中添加回调函数以覆盖Phaser默认的样式,代码如下:
var config = {
  type: Phaser.AUTO,
  width: 800,
  height: 600,
  physics: {
    default: "arcade",
    arcade: {
      gravity: { y: 200 }
    }
  },
  scene: {
    preload: preload,
    create: create
  },
  callbacks: {
    postBoot: function (game) {
      // In v3.15, you have to override Phaser's default styles
      game.canvas.style.width = '100%';
      game.canvas.style.height = '100%';
    }
  }
};

我在这里找到了代码示例:这里编辑: 如果您想要游戏能够在执行过程中改变窗口大小,您可以在更新循环中创建类似的函数,如下所示:
function update(){
    (function() {
        const gameId = document.getElementById("game"); // Target div that wraps the phaser game
        gameId.style.width = '100%'; // set width to 100%
        gameId.style.height = '100%'; // set height to 100%
    })(); // run function
}

1
谢谢Manuel,这非常接近我想要的。我稍微修改了一下,将您的函数添加到我的更新循环中。这样它就可以在执行期间随时调整大小,甚至在窗口改变大小时也可以。 - exciteabletom

1

1
这种解决方案的问题是,所有的精灵都不会被缩放,只有画布会被缩放。我正在寻找一些能够根据屏幕大小缩放整个游戏(像 flex box 一样)的东西,而不会改变 Phaser 对游戏宽度和高度的解读。 - exciteabletom
2
你能否将以下代码添加到你的HTML头部并查看它的效果?<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> - SilkeNL
1
页面加载时,屏幕处于正常大小。当我缩小页面时,它仍然保持正常大小。现在扩大图像会导致其占据整个页面宽度。 - exciteabletom
2
抱歉,我不知道任何能帮助你的东西。 - SilkeNL
1
没问题,谢谢你的尝试。 - exciteabletom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接