Bulah  Pfeffer

Bulah Pfeffer

1632975316

How to Make Your Own 2D Game with Flutter

Learn how to build your very own game of Pong (and sharpen your dev skills) with this step-by-step Flutter tutorial.

The emergence and growth of Flutter has leveraged the development of cross-platform game design; Flutter games can be created with only a few lines of code for the design and logic, while maintaining a great UI/UX.

Flutter has the capability to render at up to 60FPS. You can exploit that capability to build a simple 2D, or even 3D, game. Keep in mind that more complex games won’t be a good idea to develop in Flutter, as most developers will gravitate towards native development for complex applications.

In this tutorial, we will be recreating one of the first computer games ever created: Pong. Pong is a simple game, so it’s a great place to start. This article is split into two main sections: game logic and the user interface, to make the build a bit clearer by focusing on the important sections separately.

Before we get into the build, let’s go over the prerequisites and setup.

Prerequisites

To understand and code along with this lesson, you will need the following:

  • Flutter installed on your machine
  • Working knowledge of Dart and Flutter
  • A text editor

Getting started

In this post, we will be using Alignment(x,y) as a representation of Vector(x,y) for the position of the X and Y axis of the screen, which will help develop the physics of the game. We will also be creating stateless widgets for some of our variables and declare them in the homepage.dart file to make the code less bulky and easy to understand.

First, create a Flutter project. Clear the default code in the main.dart file, and import the material.dart package for including Material widgets in the application.

Next, create a class called MyApp() and return MaterialApp(), then create a statefulWidget HomePage() and pass it into the home parameter of MaterialApp() as shown below:

import 'package:flutter/material.dart'; import 'package:pong/homePage.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) {  return MaterialApp(   debugShowCheckedModeBanner:false,   home: HomePage(),  ); } }

Game logic

Within HomePage(), we need to write some functions and methods to take care of the mathematical and physics-related operations. These include handling collisions, accelerating or decelerating, and navigation in the game.

But first, we need to declare some parameters that will represent the positional alignments of the ball, players, and the initial score of both players. The code for the parameters should be placed under _HomePageState, to which we will refer later in the post:

 

//player variations
double playerX = -0.2;
double brickWidth = 0.4;
int playerScore = 0;
// enemy variable
double enemyX = -0.2;
int enemyScore = 0;
//ball
double ballx = 0;
double bally = 0;
var ballYDirection = direction.DOWN;
var ballXDirection = direction.RIGHT;
bool gameStarted = false;
...

Then, we provide an enumeration for directions for the ball and brick movement:

enum direction { UP, DOWN, LEFT, RIGHT } ...

To make this game work, we need to create artificial gravity so that when the ball hits the top brick (0.9) or bottom brick (-0.9), it goes in the opposite direction. Otherwise, if it does not hit either brick and goes to the top (1) or bottom (-1) of the playing field, it records it as a loss for the player.

When the ball hits the wall on the left (1) or right (-1), it goes in the opposite direction:

void startGame() {
 gameStarted = true;
 Timer.periodic(Duration(milliseconds: 1), (timer) {
  updatedDirection();
  moveBall();
  moveEnemy();
  if (isPlayerDead()) {
   enemyScore++;
   timer.cancel();
   _showDialog(false);
   // resetGame();
  }
   if (isEnemyDead()) {
   playerScore++;
   timer.cancel();
   _showDialog(true);
   // resetGame();
  }
 });
}
...

In the code above, we started with a function startGame() which changes the boolean gameStarted to true, after which we call a Timer() with a duration of one second.

Within the timer, functions like updatedDirection(),moveBall(), and moveEnemy() are passed alongside an if statement to check if either player has failed. If so, the score is accumulated, the timer is cancelled, and a dialog is shown.

The following functions ensure that the ball doesn’t go beyond 0.9 in alignment, and that the ball will only go in the opposite direction when it comes in contact with the brick:

void updatedDirection() {
 setState(() {
  //update vertical dirction
  if (bally >= 0.9 && playerX + brickWidth>= ballx && playerX <= ballx) {
   ballYDirection = direction.UP;
  } else if (bally <= -0.9) {
   ballYDirection = direction.DOWN;
  }
  // update horizontal directions
  if (ballx >= 1) {
   ballXDirection = direction.LEFT;
  } else if (ballx <= -1) {
   ballXDirection = direction.RIGHT;
  }
 });
}
void moveBall() {
 //vertical movement
 setState(() {
  if (ballYDirection == direction.DOWN) {
   bally += 0.01;
  } else if (ballYDirection == direction.UP) {
   bally -= 0.01;
  }
 });
 //horizontal movement
 setState(() {
  if (ballXDirection == direction.LEFT) {
   ballx -= 0.01;
  } else if (ballXDirection == direction.RIGHT) {
   ballx += 0.01;
  }
 });
}
...

Also, if the ball hits the left or right of the field, it goes in the opposite direction:

void moveLeft() {
 setState(() {
  if (!(playerX - 0.1 <= -1)) {
   playerX -= 0.1;
  }
 });
}
void moveRight() {
 if (!(playerX + brickWidth >= 1)) {
  playerX += 0.1;
 }
}
...

The moveLeft() and moveRight() functions help to control our bricks’ movement from left to right using the keyboard arrow. These work with an if statement to ensure the bricks do not go beyond the width of both axes of the field.

The function resetGame() returns the players and the ball to their default positions:

void resetGame() {
 Navigator.pop(context);
 setState(() {
  gameStarted = false;
  ballx = 0;
  bally = 0;
  playerX = -0.2;
  enemyX =- 0.2;
 });
}
...

Next, we create two functions, isEnemyDead() and isPlayerDead(), that return a boolean value. They check if either of the players has lost (if the ball has hit the vertical section behind the brick):

bool isEnemyDead(){
 if (bally <= -1) {
  return true;
 }
 return false;
}
bool isPlayerDead() {
 if (bally >= 1) {
  return true;
 }
 return false;
}
...

Finally, the function _showDialog displays a dialog when either player wins. It passes a boolean, enemyDied, to differentiate when a player loses. Then, it declares the non-losing player has won the round, and uses the winning player’s color for the displayed text “play again:”

void _showDialog(bool enemyDied) {
 showDialog(
   context: context,
   barrierDismissible: false,
   builder: (BuildContext context) {
    // return object of type Dialog
    return AlertDialog(
     elevation: 0.0,
     shape: RoundedRectangleBorder(
       borderRadius: BorderRadius.circular(10.0)),
     backgroundColor: Colors.purple,
     title: Center(
      child: Text(
       enemyDied?"Pink Wins": "Purple Wins",
       style: TextStyle(color: Colors.white),
      ),
     ),
     actions: [
      GestureDetector(
       onTap: resetGame,
       child: ClipRRect(
        borderRadius: BorderRadius.circular(5),
        child: Container(
          padding: EdgeInsets.all(7),
          color: Colors.purple[100],
          child: Text(
           "Play Again",
           style: TextStyle(color:enemyDied?Colors.pink[300]: Colors.purple[000]),
          )),
       ),
      )
     ],
    );
   });
}

The user interface

Now, we will begin the development of the user interface.

Inside the widget build in the homePage.dart file, add the code below:

return RawKeyboardListener(
 focusNode: FocusNode(),
 autofocus: false,
 onKey: (event) {
  if (event.isKeyPressed(LogicalKeyboardKey.arrowLeft)) {
   moveLeft();
  } else if (event.isKeyPressed(LogicalKeyboardKey.arrowRight)) {  
moveRight();
  }
 },
 child: GestureDetector(
  onTap: startGame,
  child: Scaffold(
    backgroundColor: Colors.grey[900],
    body: Center(
      child: Stack(
     children: [
      Welcome(gameStarted),
      //top brick
      Brick(enemyX, -0.9, brickWidth, true),
      //scoreboard
      Score(gameStarted,enemyScore,playerScore),
      // ball
      Ball(ballx, bally),
      // //bottom brick
      Brick(enemyX, 0.9, brickWidth, false)
     ],
    ))),
 ),
);

In the code, we return RawKeyboardListener(), which will provide movement from left to right as we are building on the web. This can also be replicated for a touchscreen device.

The widget GestureDetector() provides the onTap functionality used to call the function startGame written above in the logic. A child, Scaffold(), is also written to specify the app’s background color and body.

Next, create a class called Welcome and pass in a boolean to check if the game has started or not. If the game has not started, the text “tap to play” will become visible:

class Welcome extends StatelessWidget {

 final bool gameStarted;
 Welcome(this.gameStarted);
 @override
 Widget build(BuildContext context) {
  return Container(
    alignment: Alignment(0, -0.2),
    child: Text(
     gameStarted ? "": "T A P T O P L A Y",
     style: TextStyle(color: Colors.white),
    ));
 }
}

Now we can create another class, Ball, to handle the ball design and its position at every point in the field using Alignment(x,y). We pass these parameters through a constructor for mobility, like so:

class Ball extends StatelessWidget {
 final x;
 final y;
 Ball(this.x, this.y);
 @override
 Widget build(BuildContext context) {
  return Container(
   alignment: Alignment(x, y),
   child: Container(
    decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.white),
    width: 20,
    height: 20,
   ),
  );
 }
}

Now let’s design the Brick class to handle the brick design, color, position, and player type.

Here, we use a mathematical equation (Alignment((2* x +brickWidth)/(2-brickWidth), y)) to pass the position for the x and y axis:

class Brick extends StatelessWidget {
 final x;
 final y;
 final brickWidth;
 final isEnemy;
 Brick( this.x, this.y, this.brickWidth, this.isEnemy);
 @override
 Widget build(BuildContext context) {
  return Container(
    alignment: Alignment((2* x +brickWidth)/(2-brickWidth), y),
    child: ClipRRect(
     borderRadius: BorderRadius.circular(10),
     child: Container(
       alignment: Alignment(0, 0),
       color: isEnemy?Colors.purple[500]: Colors.pink[300],
       height: 20,
       width:MediaQuery.of(context).size.width * brickWidth/ 2,
       ),
    ));
 }
}

Finally, the Score class should be placed directly underneath the build widget in the homepage.dart file; it displays the score of each player.

Create a constructor for the variables enemyScore and playerScore to handle the score of each player, and gameStarted to check if the game has started. This will display the content of the Stack(), or an empty Container():

class Score extends StatelessWidget {
 final gameStarted;
 final enemyScore;
 final playerScore;
 Score(this.gameStarted, this.enemyScore,this.playerScore, );
 @override
 Widget build(BuildContext context) {
  return gameStarted? Stack(children: [
   Container(
     alignment: Alignment(0, 0),
     child: Container(
      height: 1,
      width: MediaQuery.of(context).size.width / 3,
      color: Colors.grey[800],
     )),
   Container(
     alignment: Alignment(0, -0.3),
     child: Text(
      enemyScore.toString(),
      style: TextStyle(color: Colors.grey[800], fontSize: 100),
     )),
   Container(
     alignment: Alignment(0, 0.3),
     child: Text(
      playerScore.toString(),
      style: TextStyle(color: Colors.grey[800], fontSize: 100),
     )),
  ]): Container();
 }
}

The gif below shows a test of the game:

Conclusion

In this post, we covered alignment, RawKeyboardListener, widgets, booleans, ClipRect for containers, and mathematical functions in our code, all used to recreate the game Pong. The game could also be improved by increasing the number of balls or reducing the brick length, making it more complex.

I hope this post was as helpful and fun as it was building and documenting it. Feel free to use the principles in the article to recreate other classic games, or invent a new one. You can find a link to the code from this article on GitHub.

Original article at https://blog.logrocket.com

#flutter #gamedev 

What is GEEK

Buddha Community

How to Make Your Own 2D Game with Flutter

Google's Flutter 1.20 stable announced with new features - Navoki

Flutter Google cross-platform UI framework has released a new version 1.20 stable.

Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.

Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store.  If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.

Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.

Here are the few key points of this release:

Performance improvements for Flutter and Dart

In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.

sksl_warm-up

If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.

Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.

Autofill for mobile text fields

Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.

flutter_autofill

A new widget for interaction

InteractiveViewer is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.

Updated Material Slider, RangeSlider, TimePicker, and DatePicker

In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with Slider and RangeSliderDatePicker with support for date range and time picker with the new style.

flutter_DatePicker

New pubspec.yaml format

Other than these widget updates there is some update within the project also like in pubspec.yaml file format. If you are a flutter plugin publisher then your old pubspec.yaml  is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.

Preview of embedded Dart DevTools in Visual Studio Code

Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by _dart.previewEmbeddedDevTools_setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.

Network tracking

The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.

Generate type-safe platform channels for platform interop

Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the Dartmethod.

There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.

You can get more free Flutter tutorials you can follow these courses:

#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows

Terry  Tremblay

Terry Tremblay

1598396940

What is Flutter and why you should learn it?

Flutter is an open-source UI toolkit for mobile developers, so they can use it to build native-looking** Android and iOS** applications from the same code base for both platforms. Flutter is also working to make Flutter apps for Web, PWA (progressive Web-App) and Desktop platform (Windows,macOS,Linux).

flutter-mobile-desktop-web-embedded_min

Flutter was officially released in December 2018. Since then, it has gone a much stronger flutter community.

There has been much increase in flutter developers, flutter packages, youtube tutorials, blogs, flutter examples apps, official and private events, and more. Flutter is now on top software repos based and trending on GitHub.

Flutter meaning?

What is Flutter? this question comes to many new developer’s mind.

humming_bird_dart_flutter

Flutter means flying wings quickly, and lightly but obviously, this doesn’t apply in our SDK.

So Flutter was one of the companies that were acquired by **Google **for around $40 million. That company was based on providing gesture detection and recognition from a standard webcam. But later when the Flutter was going to release in alpha version for developer it’s name was Sky, but since Google already owned Flutter name, so they rename it to Flutter.

Where Flutter is used?

Flutter is used in many startup companies nowadays, and even some MNCs are also adopting Flutter as a mobile development framework. Many top famous companies are using their apps in Flutter. Some of them here are

Dream11

Dream11

NuBank

NuBank

Reflectly app

Reflectly app

Abbey Road Studios

Abbey Road Studios

and many more other apps. Mobile development companies also adopted Flutter as a service for their clients. Even I was one of them who developed flutter apps as a freelancer and later as an IT company for mobile apps.

Flutter as a service

#dart #flutter #uncategorized #flutter framework #flutter jobs #flutter language #flutter meaning #flutter meaning in hindi #google flutter #how does flutter work #what is flutter

Adobe XD plugin for Flutter with CodePen Tutorial

Recently Adobe XD releases a new version of the plugin that you can use to export designs directly into flutter widgets or screens. Yes, you read it right, now you can make and export your favorite design in Adobe XD and export all the design in the widget form or as a full-screen design, this can save you a lot of time required in designing.

What we will do?
I will make a simple design of a dialogue box with a card design with text over it as shown below. After you complete this exercise you can experiment with the UI. You can make your own components or import UI kits available with the Adobe XD.

#developers #flutter #adobe xd design export to flutter #adobe xd flutter code #adobe xd flutter code generator - plugin #adobe xd flutter plugin #adobe xd flutter plugin tutorial #adobe xd plugins #adobe xd to flutter #adobe xd tutorial #codepen for flutter.

Autumn  Blick

Autumn Blick

1602565700

Game Development with .NET

We’ve launched a new Game Development with .NET section on our site. It’s designed for current .NET developers to explore all the choices available to them when developing games. It’s also designed for new developers trying to learn how to use .NET by making games. We’ve also launched a new game development Learn portal for .NET filled with tutorials, videos, and documentation provided by Microsoft and others in the .NET game development community. Finally, we launched a step-by-step Unity get-started tutorial that will get you started with Unity and writing C## scripts for it in no time. We are excited to show you what .NET has to offer to you when making games. .NET is also part of Microsoft Game Stack, a comprehensive suite of tools and services just for game development.

A picture of a game controller

.NET for game developers

.NET is cross-platform. With .NET you can target over 25+ different platforms with a single code base. You can make games for, but not limited to, Windows, macOS, Linux, Android, iOS, Xbox, PlayStation, Nintendo, and mixed reality devices.

C## is the most popular programming language in game development. The wider .NET community is also big. There is no lack of expertise and support you can find from individuals and user groups, locally or online.

.NET does not just cover building your game. You can also use it to build your game’s website with ASP.NET, your mobile app using Xamarin, and even do remote rendering with Microsoft Azure. Your skills will transfer across the entire game development pipeline.

logos of some gaming platforms supported by .NET

Available game engines

The first step to developing games in .NET is to choose a game engine. You can think of engines as the frameworks and tools you use for developing your game. There are many game engines that use .NET and they differ widely. Some of the engines are commercial and some are completely royalty free and open source. I am excited to see some of them planning to adopt .NET 5 soon. Just choose the engine that better works for you and your game. Would you like to read a blog post to help you learn about .NET game engines, and which one would be best for you?

#.net #.net core #azure #c# #game development #azure #cryengine #game developers #game development #game development with .net #game engines #games #monogame #playfab #stride #unity #visual studio #waveengine

Brain  Crist

Brain Crist

1602147600

Flutter App Development Trends 2020

As the new decade dawns upon us, a slew of technologies has been making a lot of noise to grab the developers’ attention. While native app development is going strong, the trade winds are now blowing towards going cross-platform.

Adobe PhoneGap, React Native, Xamarin and Ionic are all leaving no stone unturned to be the undefeated champion of cross-platform development. Still, Google’s Flutter is all set to take them all on at once.

There are a tonne of resources available online to learn about Flutter, and you can start with this step by step flutter guide.

With reduced code development time, increased time-to-market speed, near-native performance, and a bevy of advantages under its hood, Flutter is set to dominate the market this decade.

Before we take a look at trends making the Flutter race ahead in 2020, let us do a quick recap of what Flutter is, for those who have been living under a rock.

#flutter #flutter-for-mobile-app #flutter-app-development #mobile-app-development #flutter-trends #software-development #advantages-of-flutter-mobile #pros-and-cons-of-flutter