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

11. Detecting Collisions

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 10. Consuming & Regenerating the Food Next episode: 12. Show Game Over Dialog

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

You are now able to control a moving Snake. It also grows as it eats the food but one thing that you should also do is prevent the Snake from moving off the screen.

@override
  Widget build(BuildContext context) {
    ...
    return Scaffold(
      body: Container(
        color: Color(0XFFF5BB00),
        child: Stack(
          children: [
            getPlayAreaBorder(),
            ...
          ],
        ),
      ),
    );
  }
bool detectCollision(Offset position) {
    
}
bool detectCollision(Offset position) {
    if (position.dx >= upperBoundX && direction == Direction.right) {
        return true;
    } else if (position.dx <= lowerBoundX && direction == Direction.left) {
        return true;
    } else if (position.dy >= upperBoundY && direction == Direction.down) {
        return true;
    } else if (position.dy <= lowerBoundY && direction == Direction.up) {
        return true;
    }
    return false;
  }
Future<Offset> getNextPosition(Offset position) async {
    Offset nextPosition;

    // Add this
    if (detectCollision(position) == true) {
        if (timer != null && timer.isActive) timer.cancel();
        return position;
    }

    ...

    return nextPosition;
  }