Colliding with other sprites
Let's fix the issue with George wandering off the edge of the screen that we saw at the end of the last section and flip the direction if he hits the edge of the screen. To do this, follow these steps:
- In the
onLoad
function ofmain.dart
, let's add theScreenCollidable
component to the bottom of the function so we can detect collisions between George and the screen edges:add(ScreenCollidable());
- In the
george.dart
file, change the class definition to add theHasHitBoxes
andCollidable
mixins:class George extends SpriteAnimationComponent with HasHitBoxes, Collidable {
- At the bottom of the
onLoad
function, add theHitboxRectangle
shape for the collision detection:addHitbox(HitboxRectangle());
- Add the following import at the top of the file to resolve the reference to
HitboxRectangle
:import 'package:flame/geometry.dart';
- At the bottom of this class file, after the
update
function definition, add the followingonCollision...