【问题标题】:Automatically scale Phaser 3 game dynamically mid-execution在执行过程中动态自动缩放 Phaser 3 游戏
【发布时间】:2020-02-10 23:24:46
【问题描述】:

我想知道是否有办法以设定的分辨率开发我的游戏,例如:

width: 1000,
height: 600,

然后让 HTML 或 Phaser 在窗口大小发生变化时自动缩放画布元素。

我试过用这个:

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

但这不能保留纵横比,不能正确缩放精灵/图像,需要重新加载页面进行调整,这意味着我不能使用特定的 x/y 坐标。

我查看了 Phaser 3 的 Scale manager 和 Flex Boxes,但它们似乎并没有改变画布大小。

【问题讨论】:

  • 你能为它生成一个虚拟的工作小提琴吗?
  • 您是如何尝试使用 ScaleManager 的?它应该调整画布的大小。

标签: javascript html css phaser-framework


【解决方案1】:

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

  • 首先,添加这些 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%';
    }
  }
};

我找到了代码示例here

编辑

如果您希望游戏在执行过程中更改窗口时调整大小,您可以在更新循环中创建类似的函数,如下所示:

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
}

【讨论】:

  • 感谢 Manuel,这与我想要的非常接近。我通过将您的函数添加到我的更新循环中进行了轻微修改。这样,它会在窗口更改时调整大小,即使在执行期间也是如此。
【解决方案2】:

试试这个: https://www.w3schools.com/cssref/css3_pr_mediaquery.asp

它允许您将 css 调整为视口。

【讨论】:

  • 这个解决方案的问题是我所有的精灵都不会被缩放,只有画布。我正在寻找能够根据屏幕尺寸(如弹性框)缩放整个游戏的东西,这不会改变 Phaser 对游戏宽度和高度的解释。
  • 你能把它添加到你的 html 头中,看看它有什么作用吗?
  • 页面加载时屏幕处于正常大小。当我缩小页面时,它继续保持正常大小。展开图像现在会导致它吞下整个页面宽度。
  • 对不起,我不知道有什么可以帮助你的
  • 没问题,感谢您的尝试
猜你喜欢
  • 1970-01-01
  • 2015-12-23
  • 2022-01-04
  • 2021-08-31
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多