How to Create a 2D Snake Game in Flutter

Jan 17 2023 Dart 2.17, Flutter 3.0, Android Studio or VS Code

Part 1: How to Create a 2D Snake Game in Flutter

5. Move the Pieces to Next Position

Episode complete

Play next episode

Next
Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 4. Create Piece Positions Next episode: 6. Draw the Snake

This video Move the Pieces to Next Position was last updated on Jan 17 2023

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

In this video, you will be changing the positions stored in the positions list. This will be done with the following considerations in mind.

void draw() async {
  ...
  
  // Add this
  for (int i = positions.length - 1; i > 0; i--) {
    positions[i] = positions[i - 1];
  }
}
positions[0] = getNextPosition(positions[0]);
Offset getNextPosition(Offset position) {}
Offset getNextPosition(Offset position) {
    Offset nextPosition;

    if (direction == Direction.right) {
      nextPosition = Offset(position.dx + step, position.dy);
    } else if (direction == Direction.left) {
      nextPosition = Offset(position.dx - step, position.dy);
    } else if (direction == Direction.up) {
      nextPosition = Offset(position.dx, position.dy - step);
    } else if (direction == Direction.down) {
      nextPosition = Offset(position.dx, position.dy + step);
    }

    return nextPosition;
  }