LibGDX LibGDX Tutorial 13: Physics with Box2D Part 3: Collisions

25. September 2014

 

So far we’ve covered creating a simple simulation then how to create physics bodies and apply forces to them now we look at dealing with collisions.  Truth of the matter is, most of the work is just done for us.  Let’s just right in with an example, heavily copied and pasted from the previous example.

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.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.*;

public class Physics2 extends ApplicationAdapter implements InputProcessor {
    SpriteBatch batch;
    Sprite sprite;
    Texture img;
    World world;
    Body body;
    Body bodyEdgeScreen;
    Box2DDebugRenderer debugRenderer;
    Matrix4 debugMatrix;
    OrthographicCamera camera;
    BitmapFont font;


    float torque = 0.0f;
    boolean drawSprite = true;

    final float PIXELS_TO_METERS = 100f;

    @Override
    public void create() {

        batch = new SpriteBatch();
        img = new Texture("badlogic.jpg");
        sprite = new Sprite(img);

        sprite.setPosition(-sprite.getWidth()/2,-sprite.getHeight()/2);

        world = new World(new Vector2(0, -1f),true);

        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        bodyDef.position.set((sprite.getX() + sprite.getWidth()/2) /
                        PIXELS_TO_METERS,
                (sprite.getY() + sprite.getHeight()/2) / PIXELS_TO_METERS);

        body = world.createBody(bodyDef);

        PolygonShape shape = new PolygonShape();
        shape.setAsBox(sprite.getWidth()/2 / PIXELS_TO_METERS, sprite.getHeight()
                /2 / PIXELS_TO_METERS);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;
        fixtureDef.density = 0.1f;
        fixtureDef.restitution = 0.5f;

        body.createFixture(fixtureDef);
        shape.dispose();

        BodyDef bodyDef2 = new BodyDef();
        bodyDef2.type = BodyDef.BodyType.StaticBody;
        float w = Gdx.graphics.getWidth()/PIXELS_TO_METERS;
        // Set the height to just 50 pixels above the bottom of the screen so we can see the edge in the
        // debug renderer
        float h = Gdx.graphics.getHeight()/PIXELS_TO_METERS- 50/PIXELS_TO_METERS;
        //bodyDef2.position.set(0,
//                h-10/PIXELS_TO_METERS);
        bodyDef2.position.set(0,0);
        FixtureDef fixtureDef2 = new FixtureDef();

        EdgeShape edgeShape = new EdgeShape();
        edgeShape.set(-w/2,-h/2,w/2,-h/2);
        fixtureDef2.shape = edgeShape;

        bodyEdgeScreen = world.createBody(bodyDef2);
        bodyEdgeScreen.createFixture(fixtureDef2);
        edgeShape.dispose();

        Gdx.input.setInputProcessor(this);

        debugRenderer = new Box2DDebugRenderer();
        font = new BitmapFont();
        font.setColor(Color.BLACK);
        camera = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.
                getHeight());
    }

    private float elapsed = 0;
    @Override
    public void render() {
        camera.update();
        // Step the physics simulation forward at a rate of 60hz
        world.step(1f/60f, 6, 2);

        body.applyTorque(torque,true);

        sprite.setPosition((body.getPosition().x * PIXELS_TO_METERS) - sprite.
                        getWidth()/2 ,
                (body.getPosition().y * PIXELS_TO_METERS) -sprite.getHeight()/2 )
        ;
        sprite.setRotation((float)Math.toDegrees(body.getAngle()));

        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.setProjectionMatrix(camera.combined);
        debugMatrix = batch.getProjectionMatrix().cpy().scale(PIXELS_TO_METERS,
                PIXELS_TO_METERS, 0);
        batch.begin();

        if(drawSprite)
            batch.draw(sprite, sprite.getX(), sprite.getY(),sprite.getOriginX(),
                    sprite.getOriginY(),
                    sprite.getWidth(),sprite.getHeight(),sprite.getScaleX(),sprite.
                            getScaleY(),sprite.getRotation());

        font.draw(batch,
                "Restitution: " + body.getFixtureList().first().getRestitution(),
                -Gdx.graphics.getWidth()/2,
               Gdx.graphics.getHeight()/2 );
        batch.end();

        debugRenderer.render(world, debugMatrix);
    }

    @Override
    public void dispose() {
        img.dispose();
        world.dispose();
    }

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

    @Override
    public boolean keyUp(int keycode) {


        if(keycode == Input.Keys.RIGHT)
            body.setLinearVelocity(1f, 0f);
        if(keycode == Input.Keys.LEFT)
            body.setLinearVelocity(-1f,0f);

        if(keycode == Input.Keys.UP)
            body.applyForceToCenter(0f,10f,true);
        if(keycode == Input.Keys.DOWN)
            body.applyForceToCenter(0f, -10f, true);

        // On brackets ( [ ] ) apply torque, either clock or counterclockwise
        if(keycode == Input.Keys.RIGHT_BRACKET)
            torque += 0.1f;
        if(keycode == Input.Keys.LEFT_BRACKET)
            torque -= 0.1f;

        // Remove the torque using backslash /
        if(keycode == Input.Keys.BACKSLASH)
            torque = 0.0f;

        // If user hits spacebar, reset everything back to normal
        if(keycode == Input.Keys.SPACE|| keycode == Input.Keys.NUM_2) {
            body.setLinearVelocity(0f, 0f);
            body.setAngularVelocity(0f);
            torque = 0f;
            sprite.setPosition(0f,0f);
            body.setTransform(0f,0f,0f);
        }

        if(keycode == Input.Keys.COMMA) {
            body.getFixtureList().first().setRestitution(body.getFixtureList().first().getRestitution()-0.1f);
        }
        if(keycode == Input.Keys.PERIOD) {
            body.getFixtureList().first().setRestitution(body.getFixtureList().first().getRestitution()+0.1f);
        }
        if(keycode == Input.Keys.ESCAPE || keycode == Input.Keys.NUM_1)
            drawSprite = !drawSprite;

        return true;
    }

    @Override
    public boolean keyTyped(char character) {
        return false;
    }


    // On touch we apply force from the direction of the users touch.
    // This could result in the object "spinning"
    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        body.applyForce(1f,1f,screenX,screenY,true);
        //body.applyTorque(0.4f,true);
        return true;
    }

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

 

Here is the application running

Click to open in new Window (It's probably already run by the time you scrolled down)


You can control it using the following controls:

  • Left and Right Arrow:  Apply impulse along X axis
  • Up and Down Arrow: Apply force along Y axis.
  • [ and ]: Apply torque
  • \: Set torque to 0
  • SPACEBAR or '2': Reset all
  • Click, apply force from point of click
  • ESC or '1' toggles display of the sprite graphic on and off

 

This is basically the same application we created in the previous example, except now there is actually something to collide with.  In this case we created a physics body defined by an edge shape just 50 pixels above the bottom of the screen.  The key difference between our two bodies is bodyEdgeScreen has it’s physics type set to StaticBody.  A static body is exactly what it’s name implies, static, meaning that it doesn’t move.  It participates in the physics simulation ( stuff can hit it ), but it is un affected by the simulation itself.  If this body wasn’t static, gravity would have grabbed it and set it free falling in space.  As you can see, it is created the same way as our other physics body.  The only other major difference is instead of being defined in the physics engine by a box, it is instead represented as an edge defined by two points.  This means our EdgeShape has no volume.

 

Now that we have collisions occurring a few values became much more important, density, restitution (and not shown, friction).  These are set on the FixtureDef of your Body.  We touched briefly on density in the previous tutorials, it helps determine the overall mass of your object along with the shape.  Restitution can be thought of as, for the lack of a better term, as bounciness.  Restitution helps determine how one body will respond to contact with another physics object.  Rubber for example would have a high restitution, while rock would have a very low restitution.  Friction on the other hand determines how one body slides across another body.

 

What happens if you want to perform some kind of operation when a collision occurs?  Well fortunately this is quite simple, let’s take a look at another heavily cut and paste example!

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.*;

public class Physics3 extends ApplicationAdapter {
    SpriteBatch batch;
    Sprite sprite,sprite2;
    Texture img;
    World world;
    Body body,body2;
    Body bodyEdgeScreen;

    Matrix4 debugMatrix;
    OrthographicCamera camera;

    final float PIXELS_TO_METERS = 100f;

    @Override
    public void create() {
        batch = new SpriteBatch();
        img = new Texture("badlogic.jpg");

        // Create two identical sprites slightly offset from each other vertically
        sprite = new Sprite(img);
        sprite.setPosition(-sprite.getWidth()/2,-sprite.getHeight()/2 +200);
        sprite2 = new Sprite(img);
        sprite2.setPosition(-sprite.getWidth()/2 + 20,-sprite.getHeight()/2 + 400);

        world = new World(new Vector2(0, -1f),true);

        // Sprite1's Physics body
        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        bodyDef.position.set((sprite.getX() + sprite.getWidth()/2) /
                        PIXELS_TO_METERS,
                (sprite.getY() + sprite.getHeight()/2) / PIXELS_TO_METERS);


        body = world.createBody(bodyDef);

        // Sprite2's physics body
        BodyDef bodyDef2 = new BodyDef();
        bodyDef2.type = BodyDef.BodyType.DynamicBody;
        bodyDef2.position.set((sprite2.getX() + sprite2.getWidth()/2) /
                        PIXELS_TO_METERS,
                (sprite2.getY() + sprite2.getHeight()/2) / PIXELS_TO_METERS);

        body2 = world.createBody(bodyDef2);

        // Both bodies have identical shape
        PolygonShape shape = new PolygonShape();
        shape.setAsBox(sprite.getWidth()/2 / PIXELS_TO_METERS, sprite.getHeight()
                /2 / PIXELS_TO_METERS);

        // Sprite1
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;
        fixtureDef.density = 0.1f;
        fixtureDef.restitution = 0.5f;


        // Sprite2
        FixtureDef fixtureDef2 = new FixtureDef();
        fixtureDef2.shape = shape;
        fixtureDef2.density = 0.1f;
        fixtureDef2.restitution = 0.5f;

        body.createFixture(fixtureDef);
        body2.createFixture(fixtureDef2);

        shape.dispose();

        // Now the physics body of the bottom edge of the screen
        BodyDef bodyDef3 = new BodyDef();
        bodyDef3.type = BodyDef.BodyType.StaticBody;
        float w = Gdx.graphics.getWidth()/PIXELS_TO_METERS;
        float h = Gdx.graphics.getHeight()/PIXELS_TO_METERS;

        bodyDef3.position.set(0,0);
        FixtureDef fixtureDef3 = new FixtureDef();

        EdgeShape edgeShape = new EdgeShape();
        edgeShape.set(-w/2,-h/2,w/2,-h/2);
        fixtureDef3.shape = edgeShape;


        bodyEdgeScreen = world.createBody(bodyDef3);
        bodyEdgeScreen.createFixture(fixtureDef3);
        edgeShape.dispose();

        camera = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.
                getHeight());

        world.setContactListener(new ContactListener() {
            @Override
            public void beginContact(Contact contact) {
                // Check to see if the collision is between the second sprite and the bottom of the screen
                // If so apply a random amount of upward force to both objects... just because
                if((contact.getFixtureA().getBody() == bodyEdgeScreen &&
                        contact.getFixtureB().getBody() == body2)
                        ||
                        (contact.getFixtureA().getBody() == body2 &&
                                contact.getFixtureB().getBody() == bodyEdgeScreen)) {

                    body.applyForceToCenter(0,MathUtils.random(20,50),true);
                    body2.applyForceToCenter(0, MathUtils.random(20,50), true);
                }
            }

            @Override
            public void endContact(Contact contact) {
            }

            @Override
            public void preSolve(Contact contact, Manifold oldManifold) {
            }

            @Override
            public void postSolve(Contact contact, ContactImpulse impulse) {
            }
        });
    }

    @Override
    public void render() {
        camera.update();
        // Step the physics simulation forward at a rate of 60hz
        world.step(1f/60f, 6, 2);

        sprite.setPosition((body.getPosition().x * PIXELS_TO_METERS) - sprite.
                        getWidth()/2 ,
                (body.getPosition().y * PIXELS_TO_METERS) -sprite.getHeight()/2 );


        sprite.setRotation((float)Math.toDegrees(body2.getAngle()));
        sprite2.setPosition((body2.getPosition().x * PIXELS_TO_METERS) - sprite2.
                        getWidth()/2 ,
                (body2.getPosition().y * PIXELS_TO_METERS) -sprite2.getHeight()/2 );
        sprite2.setRotation((float)Math.toDegrees(body.getAngle()));

        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.setProjectionMatrix(camera.combined);
        batch.begin();

        batch.draw(sprite, sprite.getX(), sprite.getY(),sprite.getOriginX(),
                sprite.getOriginY(),
                sprite.getWidth(),sprite.getHeight(),sprite.getScaleX(),sprite.
                        getScaleY(),sprite.getRotation());
        batch.draw(sprite2, sprite2.getX(), sprite2.getY(),sprite2.getOriginX(),
                sprite2.getOriginY(),
                sprite2.getWidth(),sprite2.getHeight(),sprite2.getScaleX(),sprite2.
                        getScaleY(),sprite2.getRotation());
        batch.end();
    }

    @Override
    public void dispose() {
        img.dispose();
        world.dispose();
    }
}

 

And when you run it

 

Click to open in new Window (It's probably already run by the time you scrolled down)


 

In this example we’ve added another dynamic physics body.  Both bodies fall thanks to gravity, however when the second physics body makes contact with the “ground”, an upward force is applied to both bodies.

 

The heart of this example is the ContactListener we added to our physics world.  This handler is called for each collision that occurred in the world and allows you to handle the event before and after contact, then before and after the physics engine does the calculations on what to do.  In this example we used the beginContact callback, although truth is, all 4 would have behaved identically.  In each case a Contact object is passed in, which has details on the collision such as the friction, restitution and speed of the collision.  In this case we actually want to check what types of objects collided, which we do using getFixtureA() and getFixtureB() which returns the FixtureDef of the colliding objects.  Since we don’t actually know which collides with which, we test for both directions of collisions.  If the bodies colliding are Body2 and bodyEdgeScreen, we apply our upward force.  Obviously you could handle whatever kind of calculation you wanted at this point.

 

One very common activity, and something I didn’t cover in this example is tying a physics body back to the object in the real world that this body represents.  In this particular example we’ve simply hard coded things, but in a real life application this isn’t an option.  Fortunately there is an easy elegant solution.  Each physics Body has a property called UserData, which can be basically whatever you want it to be.  Let’s take a quick look at storing the game sprite using UserData of the physics Body.

        //Create the body
        body = world.createBody(bodyDef);
        //Store the sprite the body represents in UserData
        body.setUserData(sprite);
        //Access the sprite
        ((Sprite)body.getUserData()).setPosition(body.getPosition().x,body.getPosition().y);

 

This provides an easy way to link the object represented with the physics entity itself.

 

So far we covered dynamic objects, which can be moved and positioned and participate in the physics simulation, and static bodies, that do not move but can participate in the simulation, what what happens if you want a body to be aware of the physics simulation, but not effect it.  For example, what if you wanted to trigger some code when a physics body went off screen, but you didn’t want this to cause a collision.  There is a very simple solution to this, sensors.

        fixtureDef.isSensor = true;

 

This is all you need to do an now your physics object will no longer cause a reaction when collided with, except whatever you provide in code.  For example, in the earlier example, if you changed fixtureDef3 to be a sensor, the first body will simply fall through it.  However when the second body hits it, it will trigger the code in our ContactListener.

 

If you thought to yourself, wow, that’s an ugly way to handle tests for collisions between different objects… that whole test in both directions thing will get awfully ugly quickly.  You are 100% correct, fortunately there is a clean solution I will cover shortly.

Programming , ,




Adventures in Phaser with TypeScript -- Tweening

23. September 2014

 

 

In the previous particle tutorial I used something called a tween followed by the instructions “don’t worry about it, I will cover them later”.  Well, welcome to later!

 

First off, what exactly is a tween?  It’s actually probably exactly what you expect it is, basically it’s “between” turned into a verb.  Tweens are all about transitioning from one state to another, and they are incredibly handy.  Let’s just straight in with an example:

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    sprite: Phaser.Sprite;
    
    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        this.game.load.image("decepticon", "decepticon.png");
        
    }
    render() {
    }
    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite).to(
            { x: 400 }, 5000, Phaser.Easing.Linear.None, true, 0, Number.MAX_VALUE, true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

This example shows a to() tween, which is it tweens between the initial value and the value you specify.  When creating a tween, you pass in the option you wish to tween, in this case a Phaser.Sprite.  The first value are the properties we wish to tween, in this cases sprite’s x value.  Next we tell it how long to take ( 5 seconds ), then pass in the easing function we want to use, in this case none ( which by the way, would have been the default value ), next is the delay before beginning ( right away ), how many times to perform ( infinite ) the tween, then finally we pass true to bounce.  Bounce says after you are done the tween, go back to the beginning.

 

And here is the result

 

 

As you can see the image moves across the screen until it’s x value is 400.

 

Now let’s take a look at how the easing function affects the tween.  Instead of no easing function, let’s apply an elastic band type affect.  We use InOut, which means it will ease at the beginning and end of the Tween.

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite).to({ x: 400 }, 5000,
            Phaser.Easing.Elastic.InOut, true, 0, Number.MAX_VALUE, true);
    }

 

And the result:

 

 

Tweens don't have to be limited to positioning items either, you can tween just about any value. For example, let’s instead tween the alpha value of our sprite:

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite).to({alpha:0 }, 5000,
            Phaser.Easing.Quadratic.In, true, 0, Number.MAX_VALUE, true);
    }

 

And the result

 

 

You can also chain together tweens to perform a series of transitions:

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite)
            .to({ x: 400 }, 2000)
            .to({ y: 250 }, 2000)
            .to({ x: 0 }, 2000)
            .to({ y: 0 }, 2000).loop().start();
    }

 

Resulting in:

 

 

Tweens also have event handlers attached. Here for example is a tween that has an onStart and onComplete event handler, that fire before and after the tween completes respectively.

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        var tween = this.game.add.tween(this.sprite);
        tween.to({ x: 400 });

        tween.onStart.addOnce(() => {
            this.sprite.scale.setMagnitude(0.5);
        });
        tween.onComplete.addOnce(() => {
            this.game.add.tween(this.sprite).to({ x: 0 }).start();
            },this);
        tween.start();
    }

 

Tweens provide a pretty powerful but simple way of adding actions, either in sequence or parallel, to your game’s contents.

 

Programming , , , ,




LibGDX Tutorial Part 14: Gamepad support

22. September 2014

 

 

Today we are going to look at adding game pad support into LibGDX, specifically the XBox 360 controller.  Why the Xbox 360 controller?  Well, it’s the controller that I ( and 90% of other PC gamers it seems ) own.  You should be able to modify the following to work with any gamepad, but it’s left as an exercise for the viewer.

 

There are two things we need to be aware of right away.  First, Controller support is via an extension, so when you are creating your project, you need to select Controller like so:

libgdxController

 

Next, LibGDX doesn’t actually support the 360 controller out of the box, it only ships with mappings for the Ouya controller.  Fortunately, thanks to the power of Google, I found someone else to do the work for us!  There is a code sample midway through this thread.  Download the included source and save it to a file named XBox360Pad.java.  Yes, case is important.  So it should look like this:

 

package com.gamefromscratch;

import com.badlogic.gdx.controllers.PovDirection;

// This code was taken from http://www.java-gaming.org/index.php?topic=29223.0
// With thanks that is!

public class XBox360Pad
{
    /*
     * It seems there are different versions of gamepads with different ID 
     Strings.
     * Therefore its IMO a better bet to check for:
     * if (controller.getName().toLowerCase().contains("xbox") &&
                   controller.getName().contains("360"))
     *
     * Controller (Gamepad for Xbox 360)
       Controller (XBOX 360 For Windows)
       Controller (Xbox 360 Wireless Receiver for Windows)
       Controller (Xbox wireless receiver for windows)
       XBOX 360 For Windows (Controller)
       Xbox 360 Wireless Receiver
       Xbox Receiver for Windows (Wireless Controller)
       Xbox wireless receiver for windows (Controller)
     */
    //public static final String ID = "XBOX 360 For Windows (Controller)";
    public static final int BUTTON_X = 2;
    public static final int BUTTON_Y = 3;
    public static final int BUTTON_A = 0;
    public static final int BUTTON_B = 1;
    public static final int BUTTON_BACK = 6;
    public static final int BUTTON_START = 7;
    public static final PovDirection BUTTON_DPAD_UP = PovDirection.north;
    public static final PovDirection BUTTON_DPAD_DOWN = PovDirection.south;
    public static final PovDirection BUTTON_DPAD_RIGHT = PovDirection.east;
    public static final PovDirection BUTTON_DPAD_LEFT = PovDirection.west;
    public static final int BUTTON_LB = 4;
    public static final int BUTTON_L3 = 8;
    public static final int BUTTON_RB = 5;
    public static final int BUTTON_R3 = 9;
    public static final int AXIS_LEFT_X = 1; //-1 is left | +1 is right
    public static final int AXIS_LEFT_Y = 0; //-1 is up | +1 is down
    public static final int AXIS_LEFT_TRIGGER = 4; //value 0 to 1f
    public static final int AXIS_RIGHT_X = 3; //-1 is left | +1 is right
    public static final int AXIS_RIGHT_Y = 2; //-1 is up | +1 is down
    public static final int AXIS_RIGHT_TRIGGER = 4; //value 0 to -1f
}

 

Now let's jump right in with a sample:

 

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.controllers.ControllerListener;
import com.badlogic.gdx.controllers.Controllers;
import com.badlogic.gdx.controllers.PovDirection;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;

public class Gamepad extends ApplicationAdapter implements ControllerListener {
   SpriteBatch batch;
   Sprite sprite;
   BitmapFont font;
   boolean hasControllers = true;
   String message = "Please install a controller";

   @Override
   public void create () {
      batch = new SpriteBatch();
      sprite = new Sprite(new Texture("badlogic.jpg"));
        sprite.setPosition(Gdx.graphics.getWidth()/2 -sprite.getWidth()/2,
                           Gdx.graphics.getHeight()/2-sprite.getHeight()/2);

        // Listen to all controllers, not just one
        Controllers.addListener(this);

        font = new BitmapFont();
        font.setColor(Color.WHITE);


        if(Controllers.getControllers().size == 0)
        {
            hasControllers = false;
        }
    }

   @Override
   public void render () {
      Gdx.gl.glClearColor(0, 0, 0, 0);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      batch.begin();
        if(!hasControllers)
            font.draw(batch,message,
                    Gdx.graphics.getWidth()/2 - font.getBounds(message).width/2,
                    Gdx.graphics.getHeight()/2 - font.getBounds(message).height/2);
        else
          batch.draw(sprite, sprite.getX(), sprite.getY(),sprite.getOriginX(),sprite.getOriginY(),
                    sprite.getWidth(),sprite.getHeight(),
                    sprite.getScaleX(),sprite.getScaleY(),sprite.getRotation());
      batch.end();
   }

    // connected and disconnect dont actually appear to work for XBox 360 controllers.
    @Override
    public void connected(Controller controller) {
        hasControllers = true;
    }

    @Override
    public void disconnected(Controller controller) {
        hasControllers = false;
    }

    @Override
    public boolean buttonDown(Controller controller, int buttonCode) {
        if(buttonCode == XBox360Pad.BUTTON_Y)
            sprite.setY(sprite.getY() + 1);
        if(buttonCode == XBox360Pad.BUTTON_A)
            sprite.setY(sprite.getY()-1);
        if(buttonCode == XBox360Pad.BUTTON_X)
            sprite.setX(sprite.getX() - 1);
        if(buttonCode == XBox360Pad.BUTTON_B)
            sprite.setX(sprite.getX() + 1);

        if(buttonCode == XBox360Pad.BUTTON_LB)
            sprite.scale(-0.1f);
        if(buttonCode == XBox360Pad.BUTTON_RB)
            sprite.scale(0.1f);
        return false;
    }

    @Override
    public boolean buttonUp(Controller controller, int buttonCode) {
        return false;
    }

    @Override
    public boolean axisMoved(Controller controller, int axisCode, float value) {
        // This is your analog stick
        // Value will be from -1 to 1 depending how far left/right, up/down the stick is
        // For the Y translation, I use a negative because I like inverted analog stick
        // Like all normal people do! ;)

        // Left Stick
        if(axisCode == XBox360Pad.AXIS_LEFT_X)
            sprite.translateX(10f * value);
        if(axisCode == XBox360Pad.AXIS_LEFT_Y)
            sprite.translateY(-10f * value);

        // Right stick
        if(axisCode == XBox360Pad.AXIS_RIGHT_X)
            sprite.rotate(10f * value);
        return false;
    }

    @Override
    public boolean povMoved(Controller controller, int povCode, PovDirection value) {
        // This is the dpad
        if(value == XBox360Pad.BUTTON_DPAD_LEFT)
            sprite.translateX(-10f);
        if(value == XBox360Pad.BUTTON_DPAD_RIGHT)
            sprite.translateX(10f);
        if(value == XBox360Pad.BUTTON_DPAD_UP)
            sprite.translateY(10f);
        if(value == XBox360Pad.BUTTON_DPAD_DOWN)
            sprite.translateY(-10f);
        return false;
    }

    @Override
    public boolean xSliderMoved(Controller controller, int sliderCode, boolean value) {
        return false;
    }

    @Override
    public boolean ySliderMoved(Controller controller, int sliderCode, boolean value) {
        return false;
    }

    @Override
    public boolean accelerometerMoved(Controller controller, int accelerometerCode, Vector3 value) {
        return false;
    }
}

 

Amazingly enough, LibGDX actually manages to support controllers in their HTML target, so below is the following code running.  Maybe.

 

(Open in new window)

 

Of course, this is gamepad support in HTML5 we are talking about here, so it will only work in a very small subset of browsers and certainly may not work as expected.  However, the fact it runs at all is rather astonishing.  You may need to open the examples in a separate window using the link above to get it to work correctly.  No worries though, on a Desktop target, the above code works perfectly.

 

In this sample we are taking an event driven approach.  That is, as the controller is updated, it pushes a variety of events to our class.  This is done via the ControllerListener interface.  As you can see from the override’s, there is a great deal of functionality ( motion, sliders, etc ) that is OUYA specific.  Of interest to us are buttonDown, axisMoved and povMoved.  buttonDown is called predictably enough when one of the controller buttons is pressed, this includes face buttons, select, start and the bumpers, but not the triggers.  axisMoved is called for either of the analog sticks, and perhaps confusingly at first, the triggers are moved.  The reason triggers are supported this way is do the the fact there is a range of values instead of just a binary option like when dealing with buttons.  The amount the trigger is depressed is the range along the trigger axis.  Finally there is povMoved, this is your DPad, which really is just a set of 4 buttons.  One last thing to note here… the disconnect and connect events simply never fired for me, the logic may be OUYA specific.

 

You may notice however that movement using the analog stick is jerky as hell.  This is because event driven approach isn’t really ideal for analog controls.  You have two options here.  Instead of updating the controls each time an event is fired, you update a flag and apply some smoothing logic, to keep movement between events smooth.  Or, much easier, you use polling instead.  Let’s take a look at how you can poll controls in LibGDX.

 

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.controllers.Controllers;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class Gamepad2 extends ApplicationAdapter {
    SpriteBatch batch;
    Sprite sprite;
    Controller controller;
    BitmapFont font;
    boolean hasControllers = true;
    String message = "Please install a controller";

    @Override
    public void create () {
        batch = new SpriteBatch();
        sprite = new Sprite(new Texture("badlogic.jpg"));
        sprite.setPosition(Gdx.graphics.getWidth()/2 -sprite.getWidth()/2,
                Gdx.graphics.getHeight()/2-sprite.getHeight()/2);

        font = new BitmapFont();
        font.setColor(Color.WHITE);

        if(Controllers.getControllers().size == 0)
        {
            hasControllers = false;
        }
        else
            controller = Controllers.getControllers().first();
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        if(!hasControllers)
            font.draw(batch,message,
                    Gdx.graphics.getWidth()/2 - font.getBounds(message).width/2,
                    Gdx.graphics.getHeight()/2 - font.getBounds(message).height/2);
        else {
            // Update movement based on movement of left stick
            // Give a "deadzone" of 0.2 - -0.2, meaning the first 20% in either direction will be ignored.
            // This keeps controls from being too twitchy
            // Move by up to 10 pixels per frame if full left or right.
            // Once again I flipped the sign on the Y axis because I prefer inverted Y axis controls.
            if(controller.getAxis(XBox360Pad.AXIS_LEFT_X) > 0.2f  || 
                    controller.getAxis(XBox360Pad.AXIS_LEFT_X) < -0.2f)
                sprite.translateX(controller.getAxis(XBox360Pad.AXIS_LEFT_X) * 10f);
            if(controller.getAxis(XBox360Pad.AXIS_LEFT_Y) > 0.2f  || 
                    controller.getAxis(XBox360Pad.AXIS_LEFT_Y) < -0.2f)
                sprite.translateY(controller.getAxis(XBox360Pad.AXIS_LEFT_Y) * -10f);

            // Poll if user hits start button, if they do, reset position of sprite
            if(controller.getButton(XBox360Pad.BUTTON_START))
                sprite.setPosition(Gdx.graphics.getWidth() / 2 - sprite.getWidth() / 2,
                        Gdx.graphics.getHeight() / 2 - sprite.getHeight() / 2);
            batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getOriginX(), sprite.getOriginY(), 
                    sprite.getWidth(),sprite.getHeight(), 
                    sprite.getScaleX(), sprite.getScaleY(), sprite.getRotation());
        }
        batch.end();
    }
}

 

Now here is this code running ( sorta, maybe )

(Open in new window)

 

Here you can see we simply poll the controller for it’s status each frame.  getAxis returns the amount the controller is depressed in either direction along that axis as a value from –1 to 1.  getButton on the other hand returns a boolean representing if the button is currently pressed or not.  One important thing to keep in mind here, this code is incredibly fragile.  LibGDX controller supports multiple controllers, but in this case I simply check to see if any exist and use the first one I can find.  This means if you have multiple controllers plugged into your PC, all but the first one will be ignored.  Second, this code simply assumes the controller is an XBox 360 controller, no idea what will happen if another controller is used instead.  Most likely the worst case scenarios is buttons might be mismapped or non-existent.

 

The only other thing of note ( and mentioned in the comments ) is I applied a dead zone value of –0.2 to 0.2 for each analog stick.  This keeps the controller from being overly twitchy and from moving when the user would think the control should be still.  Generally this dead zone value is what you would configure via a sensitivity setting in your game’s settings.  I also flipped the Y axis value because, well, that’s the way it should be! :)

 

Programming , ,




GameFromScratch Guide to Getting Kids Started in Game Development

16. September 2014

 

It is getting more and more common for kids of younger and younger ages to show interest in game development.  In this day and age there is a wealth of information out there, possibly too much information at times.  This guide is intended to help parents or younger readers get started in the world of game development.  So, what exactly does this mean?  First it means I will focus on technologies that are appropriate to beginners.  Second, it means I am making no assumptions about your technical abilities, in fact, I am assuming you have none.  So if it ever feels like I am insulting your intelligence or speaking down to you, I am not!  On the other hand, if I am unclear or confusing at some point, please let me know and I will try to clarify.

 

 

How young is too young?

 

This is perhaps one of the most common questions asked.  How old do I ( or my child ) have to be to get started in game development?  This is a question with an impossible answer as all kids are different.  On the extremely low end of the range ( and using the right tools ), an incredibly motivated 6 year old would probably be able to have some success.  On the other range of the spectrum, a typical 12 year old should have the educational foundation and mental abilities to succeed.  The actual age is bound to be somewhere in the middle.

 

There are a few critical things to be aware of up front. 

 

The first is motivation.  Motivation is more likely to be the biggest hurdle to success, not mental ability.  If your child absolutely loves creating stuff ( loving to play video games is massively different than loving to create video games ) and is willing to trial and error, they are perfect for game development!

 

The second is managing expectations.  This is where we lose the most potential game developers out there, regardless to age.  Game development doesn’t have to be exceptionally hard, but it is certainly complex.  Your child is not going to be creating massive modern games like Call Of Duty or NHL any time soon.  Nor are they going to create an MMO ( online game like World of Warcraft ).  They need to start small, very small and work their way up from there.

 

A key way to put it is, if your child’s mindset is “I am going to create the next Minecraft”, they are going to fail and fail hard.  On the other hand, if their mindset is “I am going to create the next Minecraft, eventually”, they have perhaps the perfect mentality to succeed.  Knowing the difference there is critical.  Like almost any other skill, you need to start small and build on your successes.  Starting too big will just result in failure and frustration.  For the record, I believe I was about 8 when I started programming using Atari BASIC.

 

 

What is Game Development anyways?

 

This section is going to get slightly more technical, but not overly so.  Game Development is an umbrella term, it includes many different skills all coming together to create a greater whole.  Think about Game Development like you would an car maker.  There is no single skill involved in making a car, instead you have engineers, graphic designers, manufacturers, quality assurance and more all coming together to make a car.  In the case of a game however, it’s still possible for all of these different tasks to be performed by a single person.  There are a number of highly successful games out there that were written, drawn and scored by the same person.  It is important to realize though, this generally isn’t the case.  Basically what I am saying is game development isn't a single task, it’s multiple.  While your child may really enjoy one part, they may dislike another part.  It’s also important when looking at what tools to use to see if they come with art or sound examples to get your child started, so they don’t have to do everything all at once.

 

If you look at a modern game’s credits, you will literally see hundreds of different names and job titles contributed to the project.  When just getting started however, there are really only two tasks to focus on. Creating the game and creating the stuff that goes in the game.

 

Let’s look at the board game Monopoly as an example.  Two major sets of skills went in to making that game.  First you had to create the game…  design the board layout, make the dice rules, write up all the game cards, etc.  Then you had to create the contents of the games, the pictures that went on the board, the drawings on each card, the little plastic houses, etc.

 

In video games, it’s really no different.  You have the task of creating the game, generally called programming and the task of creating stuff to populate your game, be it art, animation or music/sound.  These skills are completely different but are generally required for a game.  This actual tutorial is going to focus mostly on programming, when a child is interested in game development, this is generally what they mean.  A child interested in being a game artist for example, has probably already got their face buried in a notebook, sketching away!  This by the way is the perfect approach for them too, as the difference between “an artist” and a “game artist” is miniscule.  If you do however want to explore computer art for games a bit closer, read this guide.

 

 

What is Programming?

 

So, chances when you are talking about game development you are actually talking about game programming.  What is programming?  The simplest definition I can give is programming is the art of telling the computer what to do.  In the case of game programming, this means doing stuff like “when the user pushes the UP arrow do this” or “when player health equals 0, draw that”.

 

Now how you program games, that’s a much trickier conversation and one of the biggest things that you will struggle with.  Perhaps more importantly, it’s the thing that is going to be most dependent on your child.  We don’t all think the same way and we don’t all express ideas the same.  In some cases a child might take to one particular style while a completely different child would possibly despise it. 

 

For the most part for game programming there are three different ways to tell the computer what to do ( and often a combination of all 3 ):

 

Visually – this is a very common approach for beginners and for game development in general ( Unreal Engine 4, one of the most commonly used commercial game technologies has a Visual scripting interface called Blueprint for example ).  In Visual programming languages you generally drag and drop to draw your game screen, then wire it all together in a flow chart like experience  Basically it’s the programming equivalent of creating a flow chart.  If your child is a visual thinker, this may be the best route for them.

 

Here is an example of a Visual game development tool, Construct:

 

Scripting Languages – With scripting languages you tell a computer what to do using small text files.  You often still draw your game using a visual editor like the picture above, but when actually telling the computer what to do, instead of filling in text boxes or creating flow charts, you use code.

 

Here is an example of the LUA scripting language, using a 2D game library named LÖVE:

image

This little bit of text tells to computer to load an image with the filename “whale.png” and then to draw it on screen.

 

Traditional Programming Languages – Finally a lot of game development is done in traditional programming languages.  Common names include C++, Java, C# and more.  I should start straight away by saying, I do not recommend young programmers start by using a traditional or more accurately, a compiled programming language for several reasons.

 

The big question you may have is, what’s the difference between a scripting and compiled programming language?  A lot of it is technical and beyond the scope of this article but most of it comes down to complexity.  Dealing with a compiled language leaves you dealing with a number of things you simply don’t have to worry about with scripting languages.  Things like compiling ( the act of turning the text you write into something the computer can understand ), linking ( can’t easily explain this one ) and more. 

 

Perhaps more importantly, it’s purpose.  Scripting languages are generally much more focused in what they do and are designed to make things easier for the developer.  Put in the simplest terms, scripting languages are generally a lot easier to learn and use.  If you do want to learn more about traditional programming languages, you can read this guide.  It is a much more technical guide than this one.  If your child is in their teens, this may be an appropriate place to start.  That of course isn’t to say that teenagers ( and older ) are too old for the stuff recommended below.

 

In the end you will often find game development tools offer both a visual system and a scripting language, where much of the game is created using drag and drop but portions can be controlled using a scripting language.

 

 

IDE, Library, what???

 

OK, one last topic to cover before we get into it.  There are a bunch of terms and expressions that get thrown around that might be confusing.  I am going to quickly cover some of them.

 

Language – This is the programming language used.  Just like we used English, Spanish, German etc to talk to each other, we use different languages to talk to computers.  In the example above the programming language was Lua.

IDE – Integrated Development Environment.  This is a bundling of a number of tasks all into a single application.  Not all suggestions will have an IDE, meaning you need to use different programs to do different things.  Generally an IDE includes a text editor, a programming language and various tools all in a single spot.

Library – Think of a library like someone doing a bunch of work for you.  Generally even the “simple stuff” isn’t actually part of the language, things like drawing on the screen.  Instead people write that stuff and make it available to you as libraries.  In some cases, like GameMaker or Construct, it’s all bundled together for you.  In other cases, like Lua, you pick a library to go with the programming language.  Each approach has advantages and disadvantages.  For example, Gamemaker bundling everything together makes life easier to get started, but with Lua, if they don’t like a particular library, they can simply use a different one.

Sprite – A sprite is a graphic used in a game, for example the player.  A sprite can be a single image or could contain multiple for animations.  The exact meaning of a Sprite changes from engine to engine, but is always a visible thing in the game that moves.  If you’ve played Super Mario Brothers, Mario, the turtles, fireballs, etc… would be considered sprites.  The world however, such as pipes and the sky, would not generally be considered sprites.

HTML 5 – This one can get a bit confusing.  HTML5 is the most current version of HTML ( Hyper Text Markup Language ) which is the language of the web.  When you load a webpage in your browser or phone, generally it’s an HTML document that you are looking at.  The confusing part is, HTML5 is actually an umbrella term for a number of technologies that work together to make the web work.  Those include HTML itself, which is a language that describes the contents of a webpage, CSS which is another language that describes how a webpage should look, and finally JavaScript, which is a scripting language that controls the logic.  People often use the terms HTML, HTML5 and JavaScript interchangeably, although this isn’t technically true.  HTML5 can be used to create games and doesn’t have to be run in a web browser.

Debugger – When your game doesn’t run correctly, it can be tricky to figure out why.  Some packages ship with something called a debugger, which is a tool to help you identify problems or “bugs” in your game.  It is a somewhat advanced feature for beginners, but at the point you need one, a debugger can be invaluable.  For additional information on debugging click here, although advanced warning, that is a highly technical article.

 

 

 

Kid Friendly Game Development Options

 

Now after all of that we get to the meat of the article… the actual suggestions for development tools to introduce your child to the world of game development.  This is by no means an all inclusive list!  For each example I will list what’s included, an example of how it works, positives and negatives, the costs if any and links to books available, if applicable.  One last very important thing to note…  any of these options is a valid one, there really isn’t a single ‘best” choice.  Tailor your decision to best match your kids interests.  If you first choice doesn’t work out, try a different one.

 

The following list is in no particular order.

 

Scratch

 

http://scratch.mit.edu/

Overview:

Scratch is an MIT backed project aimed at teaching kids aged 8 to 16 to learn how to program.  There is a massive community built around Scratch, which has been around since 2006.  There is a special focus on being family friendly.  Scratch is run entirely in the web browser, you simply go to the web page and start programming.  If you want to save your work, you need to register, but it’s a simply form and doesn’t even email you for verification.

 

Scratch is firmly in the visual programming languages category.  Your child works by dragging actors onto a scene, then controls them using Lego-like programming blocks.  The blocks are a good parallel to actual programming language structure, so if they switch to scripting or traditional programming, it will make immediate sense.  There is a good amount of documentation available and you can find literally thousands of sample scratch programs to learn from.

 

Perhaps the most valuable part of scratch is it comes preloaded with all kinds of content for your child to get started with.  However it also has the ability to import graphics and audio you create yourself or get from the community, allow an easy transition between programming and making game assets.

 

Screenshots:

Scratch running in Chrome:

image

 

Loading a new Sprite

image

 

Programming in Scratch:

image

The above is a script attached to the blue dog.  It’s in two parts, first is when the Green flag ( Go ) is clicked.  It makes the dog visible, moves to a certain position on screen, then moves by one step over and over.  The other waits until it gets the collide message from the other dog, when it does it goes back to the starting position, changes the scene then hides itself.  Each Sprite has it’s own script.  The programming blocks are drag and dropped from the programming palate:

 

The Programming Palate:

image

These are the blocks you use to program in Scratch.  Above are the “Looks” options.  As you can see, there are a number of different categories to choose from.

Includes or Alternatives:

Scratch is an all in one solution, so you need no other tools to work in Scratch.  It also ships with a large variety of sample scenes, backgrounds and sounds to start with.

Costs:

Scratch is completely free and run by sponsorship donations.

Books:

 

Comments:

Scratch also makes an iPad application called ScratchJr which is aimed at children 5 to 8.  It is also completely free.  Since there is nothing to buy, or download and you don’t even have to register to try Scratch, it is probably the easiest option to try out in this list.

 



 

 

Construct 2

 

https://www.scirra.com/

 

Overview:

Construct2 is another visual programming based game engine.  You create games in Construct2 using a drag and drop interface and control logic using a flow chart like event system.  If the functionality you need isn’t available in Construct2, you can create your own plugins using JavaScript, although this is certainly an advanced feature and is strictly optional, Construct2 is meant to be controlled using the event system.  The ultimate output of Construct2 is HTML5, which can be exported to run on a number of platforms such as mobile ( Android, iOS, Windows Mobile ), browsers and desktop.

 

Construct2 is a great deal more complex than Scratch, which has a two fold impact.  First, Construct certainly has a higher learning curve than Scratch, so it isn’t suitable for younger children and does not take a teaching approach.  On the other hand, it is meant to provide an easy to learn tool capable of creating professional games, instead of for learning.  This means there is a lot more runway before your child runs into any limitations.  There are many professionally shipped games that were created in Construct 2. 

 

There is a good deal of documentation available, including a complete references and a PDF manual available for download.  There is a very active community and strong forum for support.

 

Construct is an application installed on your computer.  Construct requires a computer running Windows.  There is no Mac option currently available.

 

Screenshot:

Construct 2 Main Window:

image

 

Event Sheets

image

This is the primary way of programming a Construct 2 game.  The example above is part of the code controlling how the player responds to input, taken from one of the included samples that shows creating a simple shooting game.

Behaviors

image

Behaviors allow you add quickly add predefined behavior to a game object.

Integrated Image Editor:

image

 

Includes or Alternatives:

Construct 2 is an all in one solution that contains everything you need to get started.  Out of the box however it does not contain a ton of content to get started with.  They do however have a free asset pack available for download. ( Warning, that is a direct download link.  Click it and the 38mb archive of assets will start downloading ).  If you move beyond the free version, you get more assets included.

If you do get into creating plugins, you will need to download the JavaScript SDK, which is available for free.  In this case you will need to provide your own text editing environment, Construct does not include one.

Costs:

Construct2 has tiered pricing.

  • There is a free version available to download.  The free version is only able to create games that run in your browser.  It also includes less bundled assets and has a number of limitations on the complexity of game that can be created.  This limits shouldn’t be too much of a problem at least initially.
  • The Personal Edition is currently 129USD, is able to create Desktop, iPhone and Android games and includes much more bundled assets like sounds, songs and sprites.
  • Finally, there is a Business Edition, which is exactly the same as Personal Edition, except it costs more and is required if you make more than 5,000USD from your Construct2 games.  Basically if you have this problem, it’s a good problem to have!

 

Books:

 

Comments:

None

 



 

Game Maker

 

https://www.yoyogames.com/studio

 

Overview:

GameMaker is an all in one game creation system that is a hybrid providing both a visual programming interface, as well as a scripting language, their own proprietary language GML.  GameMaker initially exports to Windows only, but for a fee can also create games for iOS, Android, Web, Windows Phone and more.

 

Programming in GameMaker can be done in a flow chart like manner, similar to Construct2.  It also adds the option of programming in their own scripting language GML.  This is both a plus and a minus.  The ability to program using a Scripting language in addition to the visual system gives the user a great deal of flexibility.  It is however a more complex process.  Since the language is proprietary to GameMaker, if they move to a different environment, a lot of their knowledge will be less useful.  That said, general programming concepts stay pretty much the same from language to language, so this isn’t as big of a problem as it might sound.

 

Other than assets to get started with, GameMaker quite literally ships with everything you might need out of the box, although the quality of the tools varies.  You are able to create graphics, sounds and levels in addition to programming, all in one single application.  GameMaker has been used to make some very successful commercial games such as Spelunky and Retro City Rampage ( not for children ).

 

GameMaker is one of the more complex options on this list and is probably not appropriate for pre-teen level children.  For older children though, it offers a lot of flexibility and a ton of options should they wish to share or sell their games eventually.  Obviously this changes from child to child, so there is no hard set rule.  Just be aware, compared to say Scratch, the difficulty level here is much higher. 

 

Screenshot:

Main Interface:

image

Visual Programming:

image

Scripting:

(Script for firing a bullet)

image

Level Editor:

image

Sprite Editor:

image

Includes or Alternatives:

GameMaker is an all in one solution and contains everything you will need to make a game including code editing, image creation and editing, map designer and more.  It also includes a built in debugger, useful for hunting down problems.  The standard version however comes with very little in the way of included samples to get started with.  In fact, there are none.  However there is a very active community and tons of examples and tutorials available online.  The quality of the materials varies massively and curation by Yoyo Games is lacking, so finding the best starting material can be a bit of a challenge.  For all of the screenshots and code samples in this entry, I used material from this tutorial.

 

Costs:

GameMaker licensing can be a bit confusing, as their pricing structure has changed and not all material is updated.

The version you initially download is heavily restricted by the number of resources and scripts it can support.

You can however update to the Standard edition by simply registering an email address, which will be verified and you will then be sent a product key.

Then there is a “Professional” version for $100 USD that adds functionality for working with other developers ( you will not need at this point ).  The biggest difference is the Professional version can buy additional modules that support exporting to platforms other than Windows.  Each platform is generally $200 USD.  So for example, if you want to export your game to play on Android and iOS it will cost $500.  $100 for Professional, then $200 for each platform. 

Finally there is a “Master” version, which is basically Pro with all of the different export platforms enabled.  It’s $800USD currently.

For a new developer, the registered Standard edition is most likely good enough.  If you do need Professional, keep an eye on the Steam Store, it is made available for sale quite often.  To add to the confusion, the Standard edition you can download for free is $50USD on Steam.  DO NOT BUY IT!

 

Books:


Comments:

Note, it is not necessary to use the included tools.  For example, if you want to use another graphics program to create sprites, or to import graphics from another source, this is perfectly possible!



 

Lua with LOVE

 

http://www.lua.org/

http://love2d.org/

 

Overview:

Lua is a scripting language, while LOVE is a library for making games ( see the descriptions earlier for definition of a library ).  Lua was a programming language created for non-programmers and has become increasingly popular as a scripting language for commercial games, such as these.  That is one large advantage to choosing this option over say, Gamemaker’s custom scripting language, GML.  Lua is used elsewhere and fairly commonly, so it is a skill that will carry forward very well.    As a language it is fairly simple to learn.

 

LÖVE is the library you use to create games using the Lua programming language.  LÖVE provides pretty much all of the functionality you need to create 2D games including drawing graphics, playing sound, controlling input, loading files, etc. 

 

LÖVE and Lua isn’t a turn key solution like some of the others however, you still need a text editor to create and edit your scripts, a drawing program for creating art, and audio programming for recording sounds, a map maker for creating maps, etc.  Fortunately all of these things are freely available and I have recommendations below.  You do however have to download each one separately.  LÖVE however comes with no assets like graphics or sounds to get started, but sites like Open Game Art and FreeSound can help you get started.  It is however, yet another thing you have to locate and download.

 

The biggest negative about LOVE is the lack of platform support.  Currently LOVE can only create games for computers, although mobile targets are in the works.

 

Screenshot

Sample Lua/LOVE Code:

image

Zerobrane Studio:

image

Includes or Alternatives:

The LOVE library contains Lua, so all you need to get started is here with the getting started documentation here.  However that just gives you Lua and LOVE and nothing else.  You still need a text editor to create your code, plus art and sound programs.

 

For straight text editing, two very popular choices are Notepad++ and Sublime Text.

However, for Lua development I would recommend ZeroBrane Studio which is a more integrated development environment (IDE) that allows things like code suggestions and debugging.  Oh, plus it’s free, which is nice.

For art creation, Paint.NET, GIMP and Inkscape are three very popular free options, the last two however have a pretty hefty learning curve.

For creating levels and maps, Tiled is a very popular and free choice.

 

On the alternatives front, LUA is the scripting language for a number of popular game development tools including Corona, Gideros and Marmalade Quick.  None are as easy to learn as LOVE however, which is why I recommend LOVE over all.  They do however illustrate how learning Lua is a skill that transfers well to other projects.

 

Costs:

Both Lua and LOVE are free.  ZeroBrane is a pay way you like product.

 

Books:

Only one of these books is specifically about LOVE programming.

Lua also have a free reference manual available online.


Comments:

The name of the library is actually LÖVE with an umlaut over the O.  While cute, coupled with the commonness of the word love makes searching for help incredibly annoying.  When using Google, always add “lua” to search expressions.



 

Python with PyGame

 

https://www.python.org/

http://www.pygame.org/news.html

 

Overview:

Like the Lua and LÖVE option, this is a programming language and game library combination.  Very similar to the LÖVE library, PyGame is a very beginner friendly library.  Python is the programming language used in this pairing.  Python is a popular scripting language, although less so in game development.  It is an extremely popular language in the world of 3D graphics, such as at Pixar.   It is also quite commonly used by IT professionals to automate tasks, so even outside game development, Python can be a very valuable skill.  Python has been used to make several games.

 

PyGame also provides most of the common functionality you would expect in a game such as audio, input and graphics.  You also need to provide your own text editor, graphics, sounds, etc.  However unlike LÖVE, PyGame does ship with several examples and some sample assets to get started with.

 

Screenshot:

Python Code in PyCharm

image

Includes or Alternatives:

See the recommendations for LÖVE above, most of the same tools can be used.

ZeroBrane studio however is not an option for Python.  I would personally recommend checking out PyCharm, which has a free version available.  It is however a somewhat complicated editor.  Of course, you can still use whatever text editor you would like, such as the earlier recommendations of Notepad++ or Sublime Text.

 

Costs:

Python and PyGame are both free.  PyCharm is available in a free version.

Books:


Comments:

Python is a more complicated language than Lua, so its is recommended only for older children.  On the other hand, programming in Python is also much closer to programming in traditional languages, so the experience of learning Python will be closest to what professional programming generally feels like.

Sadly, there are two versions of Python, something that has plagued the language for a very long time.  Most of the time you want to use the 2.x version of the language.



 

HTML5 with various

 

http://www.gamefromscratch.com/page/Links-of-interest-for-HTML5-game-developers.aspx

Overview:

HTML5 is a somewhat confusing term these days.  Basically HTML is the language of web browsers while Javascript is the language that enables HTML to do stuff.  With each generation of web browser, the ability to create games has gotten more and more impressive.

 

Javascript is an interesting proposition for learning with as your kids probably already have experience in using a web browser.  Then can simply open a text file, type some code, save and load in the webpage and play.  It’s a very nice feedback loop.  Unfortunately there are some downsides here too.  While a pretty straight forward programming language, Javascript has some horrible flaws that make it hard to recommend to a complete beginner.  On top, each browser has tons of flaws, that also add a layer of complication on top.  Finally there are just so many options when it comes to HTML game development, unlike Lua or Python, that making a recommendation could actually take another article even longer than this one!

 

If you child is interested in working on HTML5 games, it is a good option to persue with the right library.  Two very good options, that provide game functionality and deal with some of the browser lunacy are Phaser and CreateJS, but there are literally hundreds of options.  Both of those libraries are straight forward, well documented and commonly used.

 

Like Python and Lua, HTML5 is not an integrated solution, so you need to provide your own text editor, graphics, etc.  However, pretty much every modern browser has build in tools to make development easier.



 

Stencyl

 

http://www.stencyl.com/

 

Overview:

Stencyl is a visually programmed game creation kit that bills itself as “the quickest and easiest way to make games”, which may actually be true!  In functionality it is very similar to Construct2, you program by drawing out your scene, then adding behaviors visually.  It is an all in one solution with an integrated image editor, although you can always import assets created in external tools.  There is no way to script in Stencyl, although you can create extensions using a programming language called Haxe, if there is functionality you need that is not available in Stencyl.  This however is advanced functionality and is probably beyond your child’s current ability level.  You can however download pre-made extensions from the marketplace.

 

Stencyl runs on Windows, Linux and Mac and by default can only create web (Flash) applications.  The ability to target other platforms like desktop computers (outside their browser), as well as iOS and Android is available for a cost (see below).  While it doesn’t ship with a ton of assets, it does make them very easily available.  In addition the help available online is very good.

 

Screenshot:

Stencyl:

image

Defining Behaviors:

image

Level Editing:

image

Program Flow:

image

Includes or Alternatives:

This is a pretty all in one solution.  Unless you delve into Haxe extension programming, basically everything is here with the initial download, or is linked directly from inside the application.

Costs:

Stencyl is available for free, but limited to applications that run in Flash, either in the integrated player or your browser.  Published games will have a Stencyl splashscreen when they load.

For $99, there is Studio that enables you to target desktop computers outside of the Flash player.  The splashscreen is removed in this version.

For $199, you gain the ability to target iOS and Android.

Books:

     

Comments:

None



 

Lego Mindstorm

 

http://www.lego.com/en-us/mindstorms

 

Overview:

Right off the top let me just say, this stuff is expensive Name Your Link'>Name Your Link'>really expensive.  However if your child shows an interest in robotics or is an avid Lego fan, this can be a very good introduction to programming.  Mindstorm Lego is basically a simple robot creation kit using lego.  The key part is it ships with a programmable piece that enables you to program your robot’s behavior.  Mindstorm enables a nice progression, your child can start by building in Lego, then start controlling the robot using the desktop or iPad application, then graduate to actually programming logic.

 

Lego Mindstorm enables you to simply control your creations, or program them using the EV3 software, a flow chart like process.  They do however make tools available allowing you to get as low leveled as you want to. 

 

Even though it’s somewhat off topic, I mention Mindstorm because it can be an ideal introduction to more (literally) hands on children to the concepts of programming.  Literally being able to see cause and effect in the real world can be very valuable.

 

Screenshot:

Programming Mindstorm:

mindstormProg

A Mindstorm robot assembled:

LEGO Mindstorm robot

Includes or Alternatives:

N/A

Costs:

Name Your Link'>Name Your Link'>Lots!

Books:

EBooks of the manual ( pdf link ) and teaching guide ( pdf link ) are available online.


Comments:

This is pushing the definition of “game programming”, but certainly is a very tactile introduction to many of the same skills that go into game development.  Also I have to say, had my parents purchased this for me as I child I would have considered nominating them for parent of the year awards.  When my daughter gets a bit older I am certainly buying this, but then, is it for her, or me? :)

 



 

Honourable Mentions

 

All lists must end at some point, and this one is no exception.  The following are other recommendations I have for parents looking to get their kids into game programming, but for whatever reason didn’t make the main list.  If nothing above appeals to you, be sure to check some of these options out.

 

Minecraft Modding

If your kids play games, there is probably a pretty good chance you have already been exposed to Minecraft.  Modding is the act of modifying an existing game and Minecraft happens to be a very popular game to mod.  Modifying an existing game can often be a great way, or at least motivation, for learning programming.  There is a HUGE community of people that mod Minecraft.  The downside is, it’s done in the Java programming language and it certainly isn’t suitable for young children.  If your child is very interested in Minecraft though, this could be a good approach to take.  You can learn more here.

 

GameSalad

http://www.gamesalad.com/

GameSalad is another visual game creation kit in the veins of Stencyl and Construct2 mentioned above.  It has been used to create professional games, there is a free version available as well as paid versions for other targeting other platforms.  I personally have no experience with GameSalad.

 

Codea

twolivesleft.com/Codea/

Codea is an iPad application for creating games on the iPad.  It currently costs $10USD.  It uses the Lua programming language and provides it’s own library for creating games that is very easy to learn.  It comes with code editing tools, debugger and tools to hook up with your computer.  You can later hook it up to a Mac and actually create a game for publishing.  However, typing code on an iPad keyboard is extremely unfun, so a bluetooth keyboard is pretty much essential.  It does however come with tons of examples and is actually a great option for a young developer who has an iPad, especially if that’s all they have.

 

Kodu or Project Spark

http://worlds.kodugamelab.com/browse

or

http://www.projectspark.com/#home

This is a game that is about creating games.  Basically it’s a game you can modify to do just about anything.  Kodu is a visual programming language created by Microsoft.  Project Spark is a modified version of Kodu being released shortly for the XBox One console.  It’s pretty far from normal game programming, but many of the concepts ( and the end result! ) are very similar.

 

Code Combat

http://codecombat.com/

Code combat is an interesting concept.  It’s a web based game where you control your character through programming.  As you progress in the game, it teaches harder concepts.  Basically you learn to program while playing a game.  It was originally created to teach Javascript, but has since added a number of other languages.  I believe it is completely free, so you’ve got nothing to lose by trying.

 

Alice

http://www.alice.org/index.php

Alice is a integrated programming solution designed to teach programming.  In their own words:

Alice is an innovative 3D programming environment that makes it easy to create an animation for telling a story, playing an interactive game, or a video to share on the web. Alice is a freely available teaching tool designed to be a student's first exposure to object-oriented programming. It allows students to learn fundamental programming concepts in the context of creating animated movies and simple video games. In Alice, 3-D objects (e.g., people, animals, and vehicles) populate a virtual world and students create a program to animate the objects.

Alice is maintained by Carnegie Mellon university and is completely free.

 

RPGMAKER

http://www.rpgmakerweb.com/

RPGMaker Ace is a product similar to GameMaker specifically for creating one type of games, Role Playing Games, generally along the Japanese style.  Their tagline is literally “Simple enough for a child; powerful enough for a developer.”  There are some commerically created games available that were written using RPGMaker.  If your child is really in to this style of game, RPGMaker could be a great introduction to game programming.  RPGMaker is $70, although quite often on sale on Steam.  Ironically enough, as I write this, it is on sale for 75% off.

 

 

Conclusion

 

Of course I only scratched the surface of the options available, but I think I got the majority of options in that list.  If you think there is something else I should have put in this document, let me know!  I tried to make this clear to people of all technical levels, but no doubt I’ve made mistakes.  If I lost you somewhere, please let me know and I will try to clarify.  The most important thing to remember, all children are different, so one approach that works for one child may fail with another.  Pick the option above that you think most fits with your child's personality, but if it doesn’t seem to be a good fit, remember there’s a dozen other options!

 

I hope that was useful.  Good luck.

Programming, General, Design, Art , , ,




Adventures in Phaser with TypeScript–Using Sprite sheets ( and Texture Atlases )

12. September 2014

 

 

In my previous Phaser tutorial on particles I used a sprite sheet to provide particles in one of the examples, then realized I hadn’t covered how to actually use a sprite sheet yet, oops!  So this tutorial is going to correct that oversight.  A spritesheet ( also known as a texture atlas ), is simply a collection of images together in a single image file.  Loading a single file into memory is often more efficient than loading dozens on small images.  It’s also generally easier from a resource management perspective.

 

Let’s take a look using the texture I used for the particle example.  It’s a seamless animation of a robin in flight that I downloaded from here.  Here is a small version of the image:

robin-782x1024

 

Now imagine the above image as a 5x5 grid of images.  This gives 22 240x314 bird images and 3 empty spaces.  Now let’s look at using that image to create an animation.

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    bird: Phaser.Sprite;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        // Load the spritesheet containing the frames of animation of our bird
        // The cells of animation are 240x314 and there are 22 of them
        this.game.load.spritesheet("ss", "robin.png", 240, 314, 22);
    }
    render() {
    }
    create() {
        this.bird = this.game.add.sprite(0, 0, "ss", 0);
        // Create an animation using all available frames
        this.bird.animations.add("fly");
        // Play the animation we just created at 10fps, looping forever
        this.bird.play("fly", 10, true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

And running:

 

 

 

So I mentioned earlier about a texture atlas.  What is that if not a spritesheet?  Well basically it’s the same thing, but with a  table of contents if you will.  The spritesheet relies entirely on images being the same size in a grid like the above.  A texture atlas on the other hand is more flexible.

 

First is the matter of how to create them.  There are actually several applications capable of creating Phaser compatible texture atlases, but TexturePacker is probably the easiest.  I am not going to go into detail on how to use TexturePacker in this post as I have already done so in the past.  For more information click here.

 

There are a couple things to be aware of that are Phaser specific.  For this example I am going to use the animation I created in my Blender tutorial series.  It’s simply the jet in a barrel roll animation, rendered as individual frames, like so:

 

0005000100020003

 

When choosing your project type, Phaser is not listed.  Instead choose Sparrow/Starling:

image

 

Simply drag and drop your frames on animation then set the following settings:

image

 

Size Constraints does not need to be set to Power of 2, but it’s generally a good idea for performance.

Allow Rotation CANNOT be checked, it will break Phaser.

Trim mode is important for this case, as I want to keep the white spaces so the image size remains the same across all animations.  For animations you will generally want to set this to keep your frames the same size.  For non-animations, it can save a great deal of space not selecting this option.

 

When ready click Publish Sprite Sheet at the top button bar.  This will then save an xml file and a png for you to use.  I called mine jet.xml and jet.png, but I am a creative type.

 

Now let’s look at the code for using a texture atlas instead of a sprite sheet… a bit of a warning, it’s awfully same-y.

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    jet: Phaser.Sprite;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        this.game.load.atlasXML("jet", "jet.png", "jet.xml");
    }
    render() {
    }
    create() {
        this.jet = this.game.add.sprite(0, 0, "jet", 0);
        // Make it bigger so we can see
        this.jet.scale.setMagnitude(3);
        this.jet.animations.add("fly");
        this.jet.animations.play("fly", 15,true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

And when we run it:

 

 

And that is how you use a spritesheet or texture atlas.

Programming , , , ,