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
Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 10. Consuming & Regenerating the Food Next episode: 12. Show Game Over Dialog

This video Detecting Collisions 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.

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;
  }