Skip to content

Commit

Permalink
fix: Allow null passthrough parent (#2821)
Browse files Browse the repository at this point in the history
In `CollisionPassthrough`, while searching for an ancestor with
`CollisionCallbacks` mixin, `firstWhere` was used. This was causing it
to fail when no such ancestor was found. But having a passthrough parent
is not necessary, at least rest of the code wasn't designed on that
assumption. So this PR replaced `firstWhere` with `firstWhereOrNull`
allowing the passthrough to be null.

This was discovered in one of the [discord
discussions](https://discord.com/channels/509714518008528896/516639688581316629/1163600349643411467).
  • Loading branch information
ufrshubham committed Oct 17, 2023
1 parent eca7e41 commit c4d2f86
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
5 changes: 3 additions & 2 deletions packages/flame/lib/src/collisions/collision_passthrough.dart
@@ -1,3 +1,4 @@
import 'package:collection/collection.dart';
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:meta/meta.dart';
Expand All @@ -14,9 +15,9 @@ mixin CollisionPassthrough on CollisionCallbacks {
@mustCallSuper
void onMount() {
super.onMount();
passthroughParent = ancestors().firstWhere(
passthroughParent = ancestors().firstWhereOrNull(
(c) => c is CollisionCallbacks,
) as CollisionCallbacks;
) as CollisionCallbacks?;
}

@override
Expand Down
20 changes: 19 additions & 1 deletion packages/flame/test/collisions/collision_passthrough_test.dart
@@ -1,5 +1,6 @@
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/src/collisions/collision_passthrough.dart';
import 'package:flame_test/flame_test.dart';
import 'package:test/test.dart';

import 'collision_test_helpers.dart';
Expand Down Expand Up @@ -40,5 +41,22 @@ void main() {
expect(hitboxParent.onCollisionCounter, 1);
},
});

testWithFlameGame('Null passthrough', (game) async {
final hitbox = CompositeHitbox(children: [RectangleHitbox()]);
final component = PositionComponent(children: [hitbox]);
final testBlock = TestBlock(Vector2.zero(), Vector2.all(10));

await game.addAll([component, testBlock]);
await game.ready();

expect(hitbox.passthroughParent, isNull);

hitbox.removeFromParent();
testBlock.add(hitbox);
await game.ready();

expect(hitbox.passthroughParent, testBlock);
});
});
}

0 comments on commit c4d2f86

Please sign in to comment.