Prohibit changing the game resolution in Unity WebGL.

huangapple go评论53阅读模式
英文:

Prohibit changing the game resolution in Unity WebGL

问题

我有一个Unity WebGL游戏。浏览器窗口可以随意更改,因此游戏可能会严重变形。如何使游戏始终保持其比例,而不受浏览器分辨率的影响?

我认为只能在HTML中进行配置,所以在style.css中我写了

min-width: 100vw;
min-height: 100vh;

出于绝望,我已经尝试将其适应到所有元素中:html,body; canvas; body; #unity-container; #unity-canvas。但浏览器不关心这段代码。没有结果。

英文:

I have a Unity WebGL game. The browser window can be changed as you like, so the game can be severely deformed. How to make the game always maintain its proportions regardless of the browser resolution?

I think it can be configured only in HTML, so in style.css I wrote

min-width: 100vw;
min-height: 100vh;

out of desperation, I have already tried to fit it into all the elements: html, body; canvas; body; #unity-container; #unity-canvas. But browsers don't care about this code. There is no result.

答案1

得分: 1

我能够解决这个问题。我们需要在index.html中编写以下代码:

<script>
function resizeGame() {
    var gameContainer = document.getElementById("unity-container");
    var widthToHeight = 16 / 9;
    var newWidth = window.innerWidth;
    var newHeight = window.innerHeight;
    var newWidthToHeight = newWidth / newHeight;

    if (newWidthToHeight > widthToHeight) {
        newWidth = newHeight * widthToHeight;
    } else {
        newHeight = newWidth / widthToHeight;
    }

    gameContainer.style.width = newWidth + 'px';
    gameContainer.style.height = newHeight + 'px';
}

window.addEventListener('resize', resizeGame, false);
resizeGame();
</script>

这是您要写入index.html的代码部分。

英文:

I was able to figure out this problem. We need to write this code in index.html

&lt;script&gt;
function resizeGame() {
      var gameContainer = document.getElementById(&quot;unity-container&quot;);
      var widthToHeight = 16 / 9;
      var newWidth = window.innerWidth;
      var newHeight = window.innerHeight;
      var newWidthToHeight = newWidth / newHeight;

      if (newWidthToHeight &gt; widthToHeight) {
          newWidth = newHeight * widthToHeight;
        } else {
          newHeight = newWidth / widthToHeight;
      }

      gameContainer.style.width = newWidth + &#39;px&#39;;
      gameContainer.style.height = newHeight + &#39;px&#39;;
    }

    window.addEventListener(&#39;resize&#39;, resizeGame, false);
    resizeGame();
&lt;/script&gt;

huangapple
  • 本文由 发表于 2023年5月7日 14:46:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76192549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定