嗨,请帮助我了解如何使用Phaser3创建响应迅速的游戏.
限制是至关重要的,因为游戏(Blockly工作区的表示层)应该能够在屏幕上被扩展到更大的部分并在会话期间缩回很多次.
问题是如何在运行时改变游戏的尺寸?
---编辑---
这个
game.resize(window.innerWidth, window.innerHeight, 1.0);
不影响游戏本身,它只改变画布的大小,例如标志setCollideWorldBounds设置为的对象true仍然使用初始世界大小:(
最后这个例子100%ok labs.phaser.io
按照您的操作调整渲染器的大小,但您还需要更新世界边界,以及可能的相机边界。
// the x,y, width and height of the games world
// the true, true, true, true, is setting which side of the world bounding box
// to check for collisions
this.physics.world.setBounds(x, y, width, height, true, true, true, true);
// setting the camera bound will set where the camera can scroll to
// I use the 'main' camera here fro simplicity, use whichever camera you use
this.cameras.main.setBounds(0, 0, width, height);
Run Code Online (Sandbox Code Playgroud)
这就是动态设置世界边界的方法。
小智 5
window.addEventListener('resize', () => {
game.resize(window.innerWidth, window.innerHeight);
});
Run Code Online (Sandbox Code Playgroud)
看看这篇文章。
它解释了如何在保持游戏比例的同时动态调整画布大小。
注:以下所有代码均来自上面的链接。我没有纠正任何内容,它来自上面链接的文章,但我将其发布在这里,以防将来链接中断。
它使用 CSS 使画布居中:
canvas{
display:block;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)
它侦听窗口“调整大小”事件并调用函数来调整游戏大小。
聆听事件:
window.onload = function(){
var gameConfig = {
//config here
};
var game = new Phaser.Game(gameConfig);
resize();
window.addEventListener("resize", resize, false);
}
Run Code Online (Sandbox Code Playgroud)
调整游戏大小:
function resize() {
var canvas = document.querySelector("canvas");
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var windowRatio = windowWidth / windowHeight;
var gameRatio = game.config.width / game.config.height;
if(windowRatio < gameRatio){
canvas.style.width = windowWidth + "px";
canvas.style.height = (windowWidth / gameRatio) + "px";
}
else{
canvas.style.width = (windowHeight * gameRatio) + "px";
canvas.style.height = windowHeight + "px";
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的 Phaser 3 项目中使用并修改了这段代码,效果很好。
如果您想了解动态调整大小的其他方法,请查看此处
| 归档时间: |
|
| 查看次数: |
6384 次 |
| 最近记录: |