Flame 1.8中如何配置CameraComponent适配设备屏幕?
Flame 1.8 RPG游戏屏幕适配问题解决
环境与初始实现
使用Flame 1.8开发RPG风格游戏,游戏类继承自FlameGame,初始onLoad方法代码如下:
@override Future<void> onLoad() async { // debugMode = true; myWorld = MyWorld(); await add(myWorld); Flame.device.setLandscape(); cameraComponent = CameraComponent(world: myWorld); //cameraComponent.viewfinder.anchor = Anchor.topLeft; await add(cameraComponent); return super.onLoad(); }
遇到的适配问题
原本计划通过以下代码实现屏幕适配:
camera.viewport = FixedResolutionViewport(size);
但Flame 1.8中不存在camera属性,且CameraComponent的viewport为final属性,无法直接赋值设置。
游戏在Chrome浏览器中通过game.size计算组件位置显示正常,但在Android设备上部分组件(如下方的砖块)无法显示,砖块初始化代码如下:
for (int i = 0; i * 1024 < 20000; i++) { var top = game.size.toSize().height - 64; add(Brick(position: Vector2(i * 1024, top))); }
(注:64为砖块高度)
代码编辑器提示:viewport无法作为setter使用,因为它是final属性。
最终解决方案
通过CameraComponent.withFixedResolution构造函数创建相机组件,解决了适配问题,代码如下:
final cameraComponent = CameraComponent.withFixedResolution( world: myWorldComponent, width: size.x, height: size.y, );
内容的提问来源于stack exchange,提问作者Vaheed01
相关产品推荐
相关产品推荐

