Skip to content

Basic Game Example

Almas Baimagambetov edited this page Jul 21, 2016 · 22 revisions

In this tutorial we are going to create a very basic game. I assume that you have completed Setting up FXGL one way or another and have a Java project in your IDE that has access to the latest version of the FXGL library.

Pre-coding Stage

First and foremost, let's define some requirements for our simple game:

  • A 600x600 window.
  • There is a player on the screen, represented by a blue rectangle.
  • The user can move the player by pressing W, S, A or D on the keyboard.
  • UI is represented by a single line of text.
  • When the player moves, the UI text updates to show how many pixels the player has moved during his lifetime.

Although it may not sound like a game, it will help you understand the basic features of FXGL. After you have finished this tutorial, you should be able to build a variety of simple games.

Now that we have a rough idea of what we are expecting from the game, we can go back to the IDE and create a package for our game. (Note: the directory structure is similar to the Maven directory structure, however, if you don't know what this is, don't worry. We will cover the structure at a later stage. At this point having "src" as the main source directory is sufficient). I'm going to use "com.myname.mygame" as the package name, where myname can optionally be replaced with your username and mygame with the game name.

  1. Create package "com.myname.mygame" in your IDE.
  2. Create a Java class name BasicGameApp in that package.

It is quite common to append "App" to the class where your main() is. This allows other developers to easily identify where the main entry point to your game / application is.

Coding Stage

In order to use the FXGL library you need to extend GameApplication and override its abstract methods. The most straightforward way is to make your main class (BasicGameApp that we created) extend it as follows:

public class BasicGameApp extends GameApplication {

    @Override
    protected void initSettings(GameSettings settings) {}

    @Override
    protected void initInput() {}

    @Override
    protected void initAssets() {}

    @Override
    protected void initGame() {}

    @Override
    protected void initPhysics() {}

    @Override
    protected void initUI() {}

    @Override
    protected void onUpdate(double tpf) {}
}

Most IDEs will generate the overridden methods automatically as soon as you extend GameApplication. Now we want to be able to start the application. To do that simply add the following:

public static void main(String[] args) {
    launch(args);
}
Clone this wiki locally