Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
20. April 2014

 

So it’s taken a while, 4 years to be precise, but LibGDX, the cross platform Java game development engine, has finally hit the milestone release 1.0. 

 

Everyone thought the day would never come. But here it is. libGDX 1.0 is officially released! Let me quickly run you through the most important changes:

Read the full CHANGES file for more goodies.

To try out our new setup, start here!

If you have a Gradle-based project, make sure to update the gdxVersion to “1.0.0″ and refresh your IDE project files! The new snapshot (==nightly) version is “1.0.1-SNAPSHOT”

Besides the usual bug fixing and enhancements, we also cleaned up our libGDX repo, website and wiki for the 1.0 release. The old setup UI has been deprecated, the audio and image extensions have been removed, and the demos have been gradelized and put into their own repositories. You can now also directly test the demos in your browser (or desktop, or Android device)!

Finally, we’ve setup a Patreon, that allows users to contribute to our infrastructure costs. This has been so successful, that we were able to move our build and website server to Hetzner. After the move and adding some build magic, the build now takes 10 minutes instead of 1 hour and 45 minutes. Thanks to all the patrons, you really made a difference in my life!

Going forward, we’ll try to have a much shorter release cycle (2 weeks – 1 month). The major version of libGDX will stay at 1 for the foreseeable future. The minor version will be increased when API breaking changes are introduced. The patch version will be increased in case of bug fixes and API additions. Releasing often allows you to stay as up-to-date as possible before freezing your libGDX version for a release.

 

They also have a brief blurb about the future:

With all pieces in place, Q1 2014 was used to polish up libGDX’s user experience and documentation for the 1.0 release. We now support all JVM development environments (Eclipse, IDEA, Netbeans, CLI) through our Gradle-based builds. Our build server has been upgraded so we can push out new releases much more easily (and hence regularly!). Our repository has been cleaned up, any clutter has been removed. The Wiki has been updated to reflect the latest state of APIs and setup procedures. We are ready to pull the trigger. After 4 years of development, libGDX has finally reached version 1.0.

 

There is also a detailed history of the LibGDX project.  You can read all about it in the announcement.

 

Congratulations to the LibGDX team!

News


16. April 2014

 

If you’ve never used Tiled read this first!

 

In this tutorial part we are going to look at loading orthogonal maps in LibGDX.  Orthogonal basically means “at a right angle to” which is a fancy way of saying the camera is looking straight at the scene.  Another much less fancy word for this style of game is “top down”.  Common examples include almost every single game from the 16Bit generation of consoles such as Zelda or MegaMan.

 

One of the first problems you are going to encounter is how do you create your maps?  One very common solution is the Tiled Map Editor which fortunately I just completed a tutorial on!  This tutorial assumes you know how to generate a TMX file, so if you haven’t be sure to go through the linked tutorial.  Fortunately LibGDX makes it very easy to work with TMX files.

 

First things first we need to copy the TMX and any/all tilemap image files used to your assets folder, like so:

image

You may notice unlike earlier tutorials I am currently using IntelliJ.  With the recent switch to Gradle it is much easier to get up and running in IntelliJ and I massively prefer it to Eclipse.  That said, everything I say is equally valid in Eclipse or IntelliJ and when there are differences, I will point them out.  If you want to get started with IntelliJ read here.

 

Alright, back on topic…

 

Now that you have the map and tilesets in your project, let’s jump right in with the code:

 

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;

public class TiledTest extends ApplicationAdapter implements InputProcessor {
    Texture img;
    TiledMap tiledMap;
    OrthographicCamera camera;
    TiledMapRenderer tiledMapRenderer;
    
    @Override
    public void create () {
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        camera = new OrthographicCamera();
        camera.setToOrtho(false,w,h);
        camera.update();
        tiledMap = new TmxMapLoader().load("MyCrappyMap.tmx");
        tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);
        Gdx.input.setInputProcessor(this);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        tiledMapRenderer.setView(camera);
        tiledMapRenderer.render();
    }

    @Override
    public boolean keyDown(int keycode) {
        return false;
    }

    @Override
    public boolean keyUp(int keycode) {
        if(keycode == Input.Keys.LEFT)
            camera.translate(-32,0);
        if(keycode == Input.Keys.RIGHT)
            camera.translate(32,0);
        if(keycode == Input.Keys.UP)
            camera.translate(0,-32);
        if(keycode == Input.Keys.DOWN)
            camera.translate(0,32);
        if(keycode == Input.Keys.NUM_1)
            tiledMap.getLayers().get(0).setVisible(!tiledMap.getLayers().get(0).isVisible());
        if(keycode == Input.Keys.NUM_2)
            tiledMap.getLayers().get(1).setVisible(!tiledMap.getLayers().get(1).isVisible());
        return false;
    }

    @Override
    public boolean keyTyped(char character) {

        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        return false;
    }
}

 

When you run the code you should see your map.  Pressing the arrow keys will scroll around the map ( and show bright red when you’ve moved beyond the extents of your map ) .  Pressing 0 or 1 will toggle the visibility of each of the two layers in your map.  ( See the tutorial on Tiled if that makes no sense ).

 

image

 

The impressive thing here is how little code was required to accomplish so much.  In a nutshell it was basically just this:

 

camera = new OrthographicCamera();
camera.setToOrtho(false,w,h);
camera.update();
tiledMap = new TmxMapLoader().load("MyCrappyMap.tmx");
tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);

 

We create an OrthographicCamera, set it to the dimensions of the screen and update() it.  Next we load our map using TmxMapLoader.load() and create a OrthogonalTiledMapRenderer passing in our tiled map.

 

In our render method:

camera.update();
tiledMapRenderer.setView(camera);
tiledMapRenderer.render();

Basically update the camera ( in case we moved it using arrow keys ), pass it in to the TiledMapRenderer with setView() and finally render() the map.  That’s it.

As you can see in our key handler:

 

@Override
public boolean keyUp(int keycode) {
    if(keycode == Input.Keys.LEFT)
        camera.translate(-32,0);
    if(keycode == Input.Keys.RIGHT)
        camera.translate(32,0);
    if(keycode == Input.Keys.UP)
        camera.translate(0,-32);
    if(keycode == Input.Keys.DOWN)
        camera.translate(0,32);
    if(keycode == Input.Keys.NUM_1)
        tiledMap.getLayers().get(0).setVisible(!tiledMap.getLayers().get(0).isVisible());
    if(keycode == Input.Keys.NUM_2)
        tiledMap.getLayers().get(1).setVisible(!tiledMap.getLayers().get(1).isVisible());
    return false;
}

 

Navigating around the map is simply a matter of moving around the camera.  We move in 32pixel chunks because those are the size of our tiles.  So basically we move the camera left/right/up/down by one tile each time an arrow key is pressed.  In the event the 0 or 1 key are pressed we toggle the visibility of that particular layer.  As you can see, you can access the TileMap layers using the getLayers().get() function.

 

In the next part we will look at adding some more complex functionality.

 

On to part two.

Programming


15. April 2014

 

One very common requirement for even the most simple game is a level editor.  The level of sophistication required varies massively from game to game but a lot of the functionality is pretty common.  At the very base level, you need a tool to layout the graphics that make up your world.  Slightly more advanced, you need to define layers, properties and collision volumes.  Often people roll their own solution but you certainly don’t have to.  One very popular 2D level editor is Tiled Map Editor which exports in TMX format, perhaps the most supported 2D game format ( Cocos2D, LOVE, LibGDX and many others all support TMX out of the box ).  As I am going to be writing a tutorial about using tiled maps in LibGDX, I figured I would give a quick introduction to Tiled first.  Keep in mind, we are only going to scratch the very surface of what Tiled is capable of.

 

First off, download and install Tiled.  It has binaries available for Windows and Mac and a source (and daily builds) release available for Linux.  You can download Tiled here.  The documentation is available here.

 

The Tiled UI is pretty straight forward, although it looks quite different across platforms.  Today I will be using the MacOS version.

 

T1

 

A tiled map is fundamentally simple.  You are basically making a grid of tiles.  A tile is a fixed size image within a larger image.  The larger image is called a tile sheet.  It’s somewhat like working with legos to make a level.  Here is an example tilesheet ( taken from here ):

 

Tilesheet

 

It’s a 512x512 image composed of a number of tiles that we are going to paint our level with.

 

Now that we have our tiles, let’s create our map.  Tiled has the ability to create Orthogonal ( straight on or “top down” perspective maps ) or IsoMetric ( angled perspective ).  In this example we are creating a Orthogonal map.  Next you need to decide how many tiles your map consists of in each direction.  Yes, tiled maps are always rectangular in shape.  Finally you need to decide your tile dimensions in pixels.  Looking at the tile map above it isn’t clear how large each tile is, but that is because some of the larger constructs are actually composed of a number of tiles.  You will see how that works in a few seconds, for now simply select 32x32 pixels for tile size and 32x32 tiles for map size.  In real pixel terms, this makes our map 1024 pixels by 1024 pixels.

 

T2

 

Now we need to load our tile set into Tiled. Select Map->New Tileset

 

T3

 

Now in the resulting dialog name it and otherwise we keep the defaults.  Our tile set is made up of 32x32 tiles, so those values work.  The background colour is used if you use a particular colour colour to mark transparency.  In this case we are using the alpha channel to determine transparency, so we don’t need to set a colour value.

 

T4

 

Now if you look at the bottom corner of Tiled you will see a grid of tiles available.  You simply select a tile, then paint in the right window with it.  

 

T5

 

Let’s start by quickly paint our entire map with a grass tile.  Click a grass tile in the tile sets window, like so:

 

T6

 

Now in the left hand window, select the Fill Tool ( or hit F ), then click in the window, and it will be filed with the tile selected filling our level with a nice grass base.

 

T7

 

Now lets say we want to quickly fill in some roads.  The road tile is actually composed of four separate tiles.  This is easily handled in Tiled, simply click the top left tile in the tile set window, then holding SHIFT, click the bottom left, like so:

 

T8

 

Now you can draw with all four tiles at once by simply clicking on the map.  First select the Stamp tool, then draw out the tiles as you desire:

 

T9

 

So, what about the tiles with transparent sections like these ones?

 

T10

 

Well these are designed to be layered over top of other tiles.  Which leads us nicely to layers.  If you have ever used Photoshop or GIMP, you probably already have a pretty good understanding of layering.  Basically layers are drawn over top of lower layers.  So for example, what you draw in Layer 2 is drawn over top of what you draw in Layer 1.  

 

Right now, we only have a single layer, let’s add another one.  In the top menu, select Layer->Add Tile Layer.

 

T12

 

Now in the Layers panel you should see a second layer available.  Clicking the checkbox to the side of the layer shows/hides it’s contents.  Clicking the layer itself makes it active.  Click Tile Layer 2.

 

T11

 

You can now paint “over” the grass and road layer, like so:

T13

 

Congratulations, you’ve just created your first map.  Now we simply save it.  

 

T14

 

 

Next we will take a look at using this map in code in LibGDX.

Programming


26. March 2014

 

I am a big fan of LibGDX and a big hater of Eclipse.  This always put me in a bit of an awkward situation, as in order to use LibGDX you basically had to use Eclipse, at least if you wanted cross platform support.  You could get IntelliJ to work, but it required a heck of a lot of jumping through hoops.  The reason Eclipse was basically forced upon you is because Google tied it’s tools pretty heavily to the Eclipse platform.  So if you want to use GWT ( for HTML target ) or Android, Eclipse was by far the easiest path.  Fortunately LibGDX recently announced they moved their build system to Gradle. 

 

Now let’s take a look at how you create and execute a LibGDX project in Eclipse.  First and foremost, grab a new release of LibGDX.

 

Next we want to generate our project.  You need gdx-setup.jar, you can download it here or find it in the lightly release of LibGDX.  Simply double click the jar to run it.  You can also run it from the command line, but we will only use the GUI in this example.

 

image

 

It’s like a stripped down version of the old setup tool, enter the name, package and class name ( following Java naming rules ) and click generate.

 

Configuring Android

 

You need to have the Android SDK installed to continue.  I recommend installing the stand-alone version of the SDK instead of the ADT bundle ( which is Android SDK + Eclipse ).  You can download the Android SDK here.  The download can be a bit tricky to located, Scroll down and locate “DOWNLOAD FOR OTHER PLATFORMS”, then locate SDK Tools only and download the appropriate package:

 

image

 

Extract that archive somewhere. 

At this point ( I am not sure its required, but it’s a good idea ), set the environment variable ANDROID_HOME and point it to this folder.

 

Now open up this folder and located SDK Manager:

image

 

Run it.  Let it install/un-install whatever it wants to do to make sure you are current.

 

The next step is very important.  You need to install the build tools version that LibGDX expects.  Right now I believe that version is 19.0.3.  The Gradle build process will fail if these tools are not installed.

image

 

 

Configuring IntelliJ

 

Make sure you have version 13 or higher.  You can download it here.  Community edition is fine, in fact, not much of the paid version is of use to a game developer.  Download and install IntelliJ 13.x if you haven’t already.

 

Anyways, now that we have fired up IntelliJ, we have a bit of configuration to do before we continue.  We need to setup our JDK and Android SDK in IntelliJ.  If you haven’t already, install and configure the Java 7 JDK.

 

This part is going to be a bit awkward, but it should only happen the first time.

 

Run IntelliJ.

In the welcome dialog, select Import Project

image

 

Navigate to the directory you created your project in earlier and select build.gradle from the root directory:

image

 

Click OK.

In the next dialog, accept the defaults and click OK.

image

 

Gradle is now going to build your project… or at least try.

Gradle downloads all the required components, so this could take a while.   Or it should, but truth is, its going to explode in a horrible state of explosionness.  Look for an error like this;

image

 

Don’t worry over much, it’s just that IntelliJ doesn’t have a clue where your JDK and ADK are.  Let’s fix that now.

 

In the Project View (ALT + 1 if missing), right click the root project and select Open Module Settings:

image

 

In the resulting dialog select SDKs then click +.

image

 

Select JDK

image

 

Navigate to the location you installed your JDK.

 

Next click + again, and this time select Android SDK.  Select the Android SDK location and click OK.

This time you also have to pick the version:

image

 

Now there is a possibility you have a wrongly configured JDK at this point too:

image

If you have an entry other than the ones you created, select it and then hit the – button.

 

OK, SDK’s are now configured.

 

Now lets re-import the project.  Select File->Import Project and pick the .build file in the root of your project again.  When prompted:

image

Select “This Window”.

 

Now your project should load without errors.  You should never have to perform the above steps again, unless you change JDK or Android SDK versions.

 

Running the Desktop Project

 

You have a one time configuration to run each project type.  Let’s start with the Desktop project:

Select Run->Edit Configurations…

image

 

If an entry for Desktop doesn’t already exist, select the + icon.

image

 

Select Application:

image

 

Now configure the project like so.  Name it then select DesktopLauncher as the Main Class, the Android\assets folder for the working directory and desktop for the classpath value.

 

image

 

Once again, its very important when selecting the working directory, make sure to select the assets folder in the android project!

image

 

Now select Run->Run Desktop and voila:

image

 

Running the Android Project

 

Once again select Run->Edit Configurations.

If an Android project doesn’t exist, select the + icon and select Android Application.

image

 

In the configuration, name it, select Android for module and optionally pick USB Device under target device.  Unless of course you are crazy enough to actually use the horrific Android emulator that is!

image

 

Now select Run->Run Android to run on an Android device.  The application will be deployed to your device and you should see Logcat information in IntelliJ

 

image

 

Running the iOS Project

 

Ok… you need a Mac to do this part and I don’t currently have my Mac with me.  So… coming later.

 

 

Running the GWT ( HTML ) Project

 

If there is an area you are going to have trouble with, this is the one.  It’s somewhat normal though, I’ve had a lot of fights with GWT tooling thus far.

 

The project is the same Run->Edit Configurations:

This time select Gradle as the project type.

image

 

Now configure the following, set the Name, select the gradle project ( details below ), click Single Instance Only and task to superDev:

 

image

 

When setting the gradle project, be sure to select the project in the gwt folder.

image

 

Now click Run->Run HTML.

 

It will churn away for a few moments, then you should see:

image

 

Look for the URL in the results.  Open this in a browser to run your app.

 

In all honesty, this currently simply doesn’t work for me right now.  Currently I get:

image

 

Frankly I have had nothing but trouble with GWT and superDEV, so I really cant be bothered fixing this at the moment.  If I do come up with a solution, I will post it here.

 

EDIT

Ok, I have a solution to the GWT problems, and it was mostly me, but partially a lack of intuitiveness.

To see your application, once you run the project open a browser window and go to localhost:8080/gwt

Then you should see:

image

 

There you now have a working project running in IntelliJ now.  Much of that was one time, so at the end of the day, after the first time, setting up a new project in IntelliJ is just as fast as an Eclipse one.  YAY, no more Eclipse!

Programming


11. March 2014

 

We are going to look at networking for your LibGDX application.  Networking in LibGDX is relatively primitive, supporting only socket communications.  In many cases though, that’s more than enough.  We are going to implement a very simple socket based chat application.  The code is heavily commented, so the discussion will actually be pretty sparse.  If I missed something please leave a comment and I will do my best to address it.

 

Alright, let’s jump right in with the code:

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net.Protocol;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.net.ServerSocket;
import com.badlogic.gdx.net.ServerSocketHints;
import com.badlogic.gdx.net.Socket;
import com.badlogic.gdx.net.SocketHints;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextArea;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.VerticalGroup;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class Networking implements ApplicationListener {
    private OrthographicCamera camera;
    private SpriteBatch batch;
    private Skin skin;
    private Stage stage;
    private Label labelDetails;
    private Label labelMessage;
    private TextButton button;
    private TextArea textIPAddress;
    private TextArea textMessage;
    
    // Pick a resolution that is 16:9 but not unreadibly small
    public final static float VIRTUAL_SCREEN_HEIGHT = 960;
    public final static float VIRTUAL_SCREEN_WIDTH = 540;
    
    
    @Override
    public void create() {        
        camera = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
        batch = new SpriteBatch();
        
        // Load our UI skin from file.  Once again, I used the files included in the tests.
        // Make sure default.fnt, default.png, uiskin.[atlas/json/png] are all added to your assets
        skin = new Skin(Gdx.files.internal("data/uiskin.json"));
        stage = new Stage();
        // Wire the stage to receive input, as we are using Scene2d in this example
        Gdx.input.setInputProcessor(stage);

        
        // The following code loops through the available network interfaces
        // Keep in mind, there can be multiple interfaces per device, for example
        // one per NIC, one per active wireless and the loopback
        // In this case we only care about IPv4 address ( x.x.x.x format )
        List<String> addresses = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            for(NetworkInterface ni : Collections.list(interfaces)){
                for(InetAddress address : Collections.list(ni.getInetAddresses()))
                {
                    if(address instanceof Inet4Address){
                        addresses.add(address.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        
        // Print the contents of our array to a string.  Yeah, should have used StringBuilder
        String ipAddress = new String("");
        for(String str:addresses)
        {
            ipAddress = ipAddress + str + "\n";
        }
        
        // Now setupt our scene UI
        
        // Vertical group groups contents vertically.  I suppose that was probably pretty obvious
        VerticalGroup vg = new VerticalGroup().space(3).pad(5).fill();//.space(2).pad(5).fill();//.space(3).reverse().fill();
        // Set the bounds of the group to the entire virtual display
        vg.setBounds(0, 0, VIRTUAL_SCREEN_WIDTH, VIRTUAL_SCREEN_HEIGHT);
        
        // Create our controls
        labelDetails = new Label(ipAddress,skin);
        labelMessage = new Label("Hello world",skin);
        button = new TextButton("Send message",skin);
        textIPAddress = new TextArea("",skin);
        textMessage = new TextArea("",skin);

        // Add them to scene
        vg.addActor(labelDetails);
        vg.addActor(labelMessage);
        vg.addActor(textIPAddress);
        vg.addActor(textMessage);
        vg.addActor(button);
        
        // Add scene to stage
        stage.addActor(vg);
        
        // Setup a viewport to map screen to a 480x640 virtual resolution
        // As otherwise this is way too tiny on my 1080p android phone.
        stage.setViewport(VIRTUAL_SCREEN_WIDTH, VIRTUAL_SCREEN_HEIGHT,false);
        stage.getCamera().position.set(VIRTUAL_SCREEN_WIDTH/2,VIRTUAL_SCREEN_HEIGHT/2,0);
        
        // Now we create a thread that will listen for incoming socket connections
        new Thread(new Runnable(){

            @Override
            public void run() {
                ServerSocketHints serverSocketHint = new ServerSocketHints();
                // 0 means no timeout.  Probably not the greatest idea in production!
                serverSocketHint.acceptTimeout = 0;
                
                // Create the socket server using TCP protocol and listening on 9021
                // Only one app can listen to a port at a time, keep in mind many ports are reserved
                // especially in the lower numbers ( like 21, 80, etc )
                ServerSocket serverSocket = Gdx.net.newServerSocket(Protocol.TCP, 9021, serverSocketHint);
                
                // Loop forever
                while(true){
                    // Create a socket
                    Socket socket = serverSocket.accept(null);
                    
                    // Read data from the socket into a BufferedReader
                    BufferedReader buffer = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
                    
                    try {
                        // Read to the next newline (\n) and display that text on labelMessage
                        labelMessage.setText(buffer.readLine());    
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start(); // And, start the thread running
        
        // Wire up a click listener to our button
        button.addListener(new ClickListener(){
            @Override 
            public void clicked(InputEvent event, float x, float y){
                
                // When the button is clicked, get the message text or create a default string value
                String textToSend = new String();
                if(textMessage.getText().length() == 0)
                    textToSend = "Doesn't say much but likes clicking buttons\n";
                else
                    textToSend = textMessage.getText() + ("\n"); // Brute for a newline so readline gets a line
                
                SocketHints socketHints = new SocketHints();
                // Socket will time our in 4 seconds
                socketHints.connectTimeout = 4000;
                //create the socket and connect to the server entered in the text box ( x.x.x.x format ) on port 9021
                Socket socket = Gdx.net.newClientSocket(Protocol.TCP, textIPAddress.getText(), 9021, socketHints);
                try {
                    // write our entered message to the stream
                    socket.getOutputStream().write(textToSend.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void dispose() {
        batch.dispose();
    }

    @Override
    public void render() {        
        Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        stage.draw();
        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

 

And when you run the code you should see:

image

 

The top two values are the IP v4 addresses of the machine you are running on.  You need to enter these in the other copy of the application you want to chat with.  This address uniquely identifies your machine on the internet, while we specified the port (9021) using code.  Think of a port like a mailbox at an apartment building.  The street address of the building is comparable to the IP address, while PORT is akin to the apartment number.  Port values go from 1 to 65,536, although several are reserved.  Most of the reserved ports are > 100, so when picking a port for your application look up to see if that address is a dedicated port ( such as 80 for HTTP communication, or 21 for FTP ), or simply pick a random high value.  Your machine can have multiple addresses, one per network adapter and possibly more, especially if you run virtualization software like VMWare.  Then there is the value 127.0.0.1, this is a special address known as a loop back adapter, and address that points back at itself.

 

Where it currently says “Hello World”, this is where any incoming messages will be displayed.

 

In the first textbox, you enter the IP address of machine you want to send a message to.  In this example, you can actually send a message to yourself, simply enter your own IP address.  Finally the second textbox is the text of the message to send.  Of course you send the message by pressing the Send Message button.

 

One thing you may notice from the above example is I set it to run in the oddball resolution of 540x960.  Why did I do this?  For a couple reasons.  First, the native resolution of the phone I tested on ( HTC One ) is 1920x1080 and the default Scene2D Skin/Font are wayyyyyyyy too small at that resolution.  Of course I could have created a a new skin that was more appropriate but, well, I'm lazy.  The second reason is that resolution is a decent size and is the same aspect ratio as 1080p ( 16:9 ), so it scales well, both up and down, when displayed on a 16:9 screen.  On an iPad it’s going to look like absolute garbage.  Perhaps in the future I will do a post specifically about handling multiple device resolutions.

 

There is one more thing to be aware of, this example currently will not work on iOS.  The Scene2D TextField widget currently doesn’t bring up the iOS on screen controller.  There is a fix on the LibGDX contributions forum.  It’s an iOS specific hack/workaround, so I wouldn’t expect it to be merged into the main trunk.  Finally, LibGDX built in networking is fairly simple, limited to just socket programming.  For more robust networking support check out kryonet, it supported in LibGDX and is reported to work across all LibGDX platforms except HTML5.  Which isn’t really surprising, as the author Nathan Sweet is also a LibGDX contributor.

Programming


AppGameKit Studio

See More Tutorials on DevGa.me!

Month List