I'm trying to fill the whole screen with 6 rows and 4 columns of SpriteComponent, but there are always gaps in between, I've checked my code and I don't know what's wrong
Here is code for FlameGame:
List<List<SquareComponent>> grids;
@override
Future<void> onLoad() async {
await super.onLoad();
gridWidth = size.x / 4;
gridHeight = size.y / 6;
grids = List.generate(
6,
(i) => List.generate(
4,
(j) => SquareComponent(
position: Vector2(j * gridWidth, i * gridHeight),
size: Vector2(gridWidth, gridHeight),
color: getRandomColor())),
);
for (var square in grids) {
addAll(square);
}
}
here is SquareComponent:
class SquareComponent extends PositionComponent with HasGameRef<MyGame>{
Color color;
final Random random = Random();
late Sprite cardSprite;
SquareComponent({
required Vector2 size,
required Vector2 position,
required this.color,
}) : super(size: size, position: position);
@override
Future<void> onLoad() async {
await super.onLoad();
cardSprite = await gameRef.loadSprite('img.png');
add(SpriteComponent(
sprite: cardSprite,
position: position,
size: size,
anchor: Anchor.topLeft
));
}
}
Thanks for the hint!
I simplified the code for just one row, Here is the printed results and screenshot:
flutter: position[0.0,155.33333333333334] size[107.5,155.33333333333334]
flutter: position[53.75,155.33333333333334] size[107.5,155.33333333333334]
flutter: position[107.5,155.33333333333334] size[107.5,155.33333333333334]
flutter: position[161.25,155.33333333333334] size[107.5,155.33333333333334]
since the screen size is [430.0,932.0], I dont understand why the size is not aligned with the position.
The problem that you are having is that you are setting the position both on the SquareComponent
and on the SpriteComponent
which makes you render half of the sprites outside of the screen, since the SpriteComponent
's position is relative to the SquareComponent
and thus you add double as much to the position as what you intend.
Just remove the position
(or set it to Vector.zero()
) on the SpriteComponent
and it will work:
add(
SpriteComponent(
sprite: cardSprite,
size: size,
anchor: Anchor.topLeft
),
);