Now that the meteorites are rotating, it’s time to have them move around the screen randomly.
For Meteormania, meteorites should move to a random angle in screen. This way, meteorites can hit the player’s spaceship if they are not paying close attention (or have a bad aim like me!)
meteorite.dart
Start by opening meteorite.dart and adding two new variables to Meteorite. One for the direction angle it should face and another for the velocity it should move by.
double directionAngle;
final Vector2 velocity = Vector2.zero();
Remember to add directionAngle to both named constructors small and big.
{required this.directionAngle}
Now, to move around meteorites, you’ll need to override update. The game loop calls this function continously to keep refreshing components and render them properly.
@override
void update(double dt) {
super.update(dt)
}
First, update the velocity’s x and y coordinates. Use GameConstants.meteoriteSpeed as a multiplier to the normalized direction vector calculated with directionAngle.
velocity.x = GameConstants.meteoriteSpeed * cos(directionAngle);
velocity.y = GameConstants.meteoriteSpeed * sin(directionAngle);
Now, update the position adding the result of multiplying velocity by dt. dt is short for delta, which is the time ellapsed since the last call to update was made. This way, the component’s position moves relative to the time ellapsed at a constant speed.
position += velocity * dt;
Finally, you’ll want to check if the component moves out of the screen’s boundaries. If it meets that criteria, then you’d want to relocate the component to the opposite side, so that it’s visible all the time until it’s destroyed.
if (position.x < -bigSize.toSize().width) {
position.x = GameConstants.cameraWidth + bigSize.toSize().width;
}
if (position.x > GameConstants.cameraWidth + bigSize.toSize().width) {
position.x = -bigSize.toSize().width;
}
Now, let’s check for the Y axis.
if (position.y < -bigSize.toSize().height) {
position.y = GameConstants.cameraHeight + bigSize.toSize().height;
}
if (position.y > GameConstants.cameraHeight + bigSize.toSize().height) {
position.y = -bigSize.toSize().height;
}
MeteormaniaGame
Back in MeteormaniaGame, add a random angle inside the generating function in addEnemies.
final randomAngle = 2 * pi * Random().nextDouble();
Then, update the constructor calls.
directionAngle: randomAngle,
Build and run the game. Meteorites now are moving around in random directions.