英文:
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
<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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论