LibGDX Tutorial 13: Physics with Box2D Part 2: Force, Impulses and Torque

10. September 2014

 

In the previous tutorial part we look at creating about the simplest physics simulation possible in LibGDX and Box2D, a single object affected by gravity.  In this tutorial we are going to take things one step further and apply force, impulses and torque ( and no gravity ) to our physics body.  This part is going to consist of a single large code example.

 

Speaking of which, here it is!

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.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;
    Box2DDebugRenderer debugRenderer;
    Matrix4 debugMatrix;
    OrthographicCamera camera;
    
    
    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, 0f),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;

        body.createFixture(fixtureDef);
        shape.dispose();
        
        Gdx.input.setInputProcessor(this);
        
        // Create a Box2DDebugRenderer, this allows us to see the physics 
        simulation controlling the scene
        debugRenderer = new Box2DDebugRenderer();
        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);
        
        // Apply torque to the physics body.  At start this is 0 and will do 
        nothing.  Controlled with [] keys
        // Torque is applied per frame instead of just once
        body.applyTorque(torque,true);
        
        // Set the sprite's position from the updated physics body location
        sprite.setPosition((body.getPosition().x * PIXELS_TO_METERS) - sprite.
                           getWidth()/2 , 
                (body.getPosition().y * PIXELS_TO_METERS) -sprite.getHeight()/2 )
                 ;
        // Ditto for rotation
        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);
        
        // Scale down the sprite batches projection matrix to box2D size
        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());
                        
        batch.end();
        
        // Now render the physics world using our scaled down matrix
        // Note, this is strictly optional and is, as the name suggests, just 
        for debugging purposes
        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) {
        
        // On right or left arrow set the velocity at a fixed rate in that 
        direction
        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) {
            body.setLinearVelocity(0f, 0f);
            body.setAngularVelocity(0f);
            torque = 0f;
            sprite.setPosition(0f,0f);
            body.setTransform(0f,0f,0f);
        }
        
        // The ESC key toggles the visibility of the sprite allow user to see 
        physics debug info
        if(keycode == Input.Keys.ESCAPE)
            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 it is running in your browser.  You may have to click the application to give it focus.

 

 

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

EDIT: OK, several keyboard combo’s do not work correctly in an iframe.  To fully interact with the above application click here to open it in it’s own window:

 

 

You may notice applying force will cause your object to not just move, but also rotate, depending on the angle you click.  You can also offset this force by clicking in the mirrored opposite side.  Also notice that applying impulse moves the object along at a constant rate, and applying the opposite impulse will bring the object to a standstill.  Hitting left or right multiple times however will not increase the speed.  However, applying force, by hitting up or down will cause it to get faster for each time you add force.  This is one of the major differences between impulse and force.  Torque works very similar,  to stop it from spinning you need to apply the appropriate amount of torque from the opposite direction.  Even setting torque to 0 will have little effect due to momentum.

 

Now let’s take a look at a few key concepts here.  First thing you should notice is:

final float PIXELS_TO_METERS = 100f;

 

Well, remember when I said in the last part that the units you use don’t really matter as long as you are consistent?  Well, let’s reclassify that as “kinda true”.  Or, completely true, but not really!  Clear now?

 

Truth of the matter is, Box2d is “tuned” to work in MKS units, which to you non-Canadian/European readers translates to Meters, Kilograms and Seconds.  Don’t get me wrong, you can still work in lbs, miles or parsecs, but you are going to fight with Box2D a bit.  Additionally, this blurb from Box2D documentation is also pretty important:

 

Box2D is tuned for MKS units. Keep the size of moving objects roughly between 0.1 and 10 meters. You'll need to use some scaling system when you render your environment and actors. The Box2D testbed does this by using an OpenGL viewport transform. DO NOT USE PIXELS.

 

So, what did I use in the prior example?  Yeah… pixels.  In reality though, when dealing with gravity only it really doesn’t matter all that much.  Once terminal velocity kicks in, all things fall at the same rate anyways.

 

But… now that we are going to working with forces and such, suddenly it becomes very important not to use pixels, and let me quickly explain why.  Consider when we create our physics object, we define it’s shape and density, like so:

 

shape.setAsBox(sprite.getWidth()/2, sprite.getHeight()/2);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 1f;

 

Our sprite is an image 256x256 in size.  Our density, which by the way is by default kg/ms2 is 1.  As a direct result, in our simulation or sprite has a default mass of…  65,536kg.  Hmmm, that’s kind of heavy and is going to require a hell of a lot of force to move!  If you are trying out box2d and you are finding that force isn’t working as you’d expect, take a look at your units, that’s the most likely culprit.  A rather easy work around is to use one set of coordinates in Box2D and translate to and from pixels to meters and back again.  For that we use:

 

When translating to box coordinates, divide by this value, when translating back, multiply by it.  Basically what we are saying is 1 meter in box2d represents 100 pixels in our game.  So for our 256x256 image, in box it is roughly 2.5m x 2.5m instead of 250x250!  You will notice however that this isn’t the only translation we do:

 

To box2d:

        bodyDef.position.set((sprite.getX() + sprite.getWidth()/2) / 
                             PIXELS_TO_METERS, 
                (sprite.getY() + sprite.getHeight()/2) / PIXELS_TO_METERS);

From box2d:

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

 

There is another calculation in there, each way we are either adding or subtracting half the sprites width and height.  This is due to box2d and LibGDX using two different coordinate systems.  In LibGDX, the sprite’s origin is it’s bottom left corner, while in box2d, it’s the middle.  You may be thinking, hey, I’ll just set the origin.  That wont do you any good actually, as in LibGDX this is only used for scaling and rotation.  So, when moving between the two coordinate systems be mindful of the different origins.

 

Otherwise the code is fairly straight forward.  From playing around with the application the difference between force and impulse is easy to see.  You can think of Force like the action of pushing someone.  It will require a higher value as you have to overcome their inertia, however pushing someone again will cause them to accelerate faster and faster.  Impulse on the other hand can be though of like the acceleration in a car.  A car with an impulse of 50km, moves along steadily at a rate of 50km.  The only way to change speeds would be to change impulse, the values would not be cumulative.  However, if another car rear ended you ( FORCE! ), you can certainly see an increase in velocity! ;)

 

Torque on the other hand is a measure of rotational force.  Unlike force and impulse, in Box2D, torque needs to be applied each frame.  Stop applying torque each frame and things stop, um, torqueing.  Finally, in terms of motion, the touch handler applies force from a given direction.  When the user presses up or down, the force was applied to the center of the object equally.  However, when the user touches or clicks the screen, the force is applied from the direction of contact.  Think just like real life, if you push a glass of beer at it’s center point, it will slide across the table.  However, push it at the top and it will probably tip.  You do have the option of turning a bodies rotation off if so required.

 

You can also set values direction, like I did when the user hits the space bar.  I set the position, torque, rotation and speed of the object back to zero.  This kind of stuff REALLY screws with Box2D though, so if you don’t have to, don’t directly manipulate values, instead work through forces.  In a simple simulation like this, its not really a big deal.

 

Finally you may notice I enabled the Box2DDebugRenderer.  In the running example, hit the ESC key ( you may have to click to give keyboard focus ) and you will see a rectangle in place of the sprite.  This is an internal representation of the physics body in box2d.  When debugging physics problems, this renderer can be invaluable.  Not however that we had to modify it’s projection matrix to correspond with our 100pixel per meter scaling factor.

 

Now that we’ve got things moving, in the next part we will look at what happens when they collide.

Programming ,




Guest Tutorial: Making Flappy Bird using Overlap2D and LibGDX

8. September 2014

 

The following is a guest tutorial by Avetis showing how to use LibGDX and Overlap2D to create an Angry Birds like game.  Overlap2D is a level and UI editor handy for separating game coding from content creation.  Keep in mind, Overlap2D is fairly young, currently at 0.0.4 version. Now, on with the tutorial!

 



Making Flappy Bird with Overlap2D – Overlappy Tutorial

 

 

Agenda


In this tutorial we are going to create a FlappyBird clone game (for learning purposes only) using Java, LibGDX framework and accelerate it all by moving our UI, Level, and Asset management into Overlap2D Editor. One thing I figured while coding is that you can’t make a quick tutorial about a flappy bird clone, ever. It’s going to be long if we want details. It is easier though to use the explain approach instead of step by step guide.  So I am going to share all the sources and resources, and then go with you through setting this all up, show how things work, and hopefully this all will make sense.

 

Prerequisites


Java knowledge, basic LibGDX experience, computer, time. Make sure you use latest Overlap2D editor and runtimes (v 0.0.4 or higher)

Get latest LibGDX project setup here: http://bitly.com/1i3C7i3 ( Details here )
Get latest Overlap2D editor here: http://overlap2d.com

 

First - Get Game Assets (Resources)


First let’s download the assets. I made a small pack of images I found on the internet with Flappy Bird images, animations and font. You can get it here: http://overlap2d.com/?p=236

 

 

Setting up Your Overlap2D Project

 

Unzip your Overlap2D zip file, and run the Overlap2D.jar.


First things first, you are currently viewing demo project, so go to File and Create New Project. Call it OverlappyBird and then create the scene size, let it be 480 width, 800 in height. It’s a standard small mobile device resolution, and since Flappy Bird is a portrait game, it should be just right. Click Create Project.
You have now created an empty project and it’s ready for setup, now you need to import the assets. Here we have 3 types of assets, first is just image textures, and second is a sprite animation for bird itself, and lastly the TTF font for score label. I have separated them in folders so you can import easily. Click on File, import to library.


First click on “…” button near the import images text field to select your images; locate them, select all. When done click on import and they all will get imported to your assets area on the right middle panel. Then open same the dialog again, and this time find Import Sprite Animations (note: not spine, but sprite) Click on “…” button there and locate bird.atlas file. Click Import, and it will get added to your assets list as well.


Lastly open import dialog again, and import font, by locating ttf file.


Your project setup is ready.

 

Making The Main Scene

 

First let’s see how main scene looks in Overlap2D when it is finished:

 

image


 
I decided to make several layers to have things organized, bg layer for background image that is not moving, default layer for pipes and bird itself, ground layer for moving the ground that is covering pipes, ui layer for “get ready” popups and score labels, and finally dlg layer for end game dialog. The reason I am not putting dialog inside ui layer is that I can position it in its layer correctly, and later hide that layer so it will not intervene with my work.  So, go ahead and create this layers in the order I described from bottom to top. (bg layer goes below them all, and you can rearrange them by drag-and-dropping)


I also recommend you to open my example project (provided with resources). Open it with Overlap2D and see how things are positioned and grouped. (To open a project, click file, open, and then locate .pit file inside project.)


Compose your own project like I did,. Put background on bg layer, and add bird on default layer. Make sure it looks like the picture above.


The ground is going to be a moving part, so we need to have 2 of this near each other for seamless movement. Put two grounds near each other and then group them into composites, like on this picture, do not forget to give identifier to it for later use.


image

 

For the pipes we are going to do the following trick. First of all we are going to put pipes on top of each other with a gap, and convert them into composite, and then add to library to have kind of a prefab for a pipe column. Later in code we are going to pre-load 3 of this because there is never more than 3 columns of pipes visible on screen, so we can re-use the ones that are left of the screen for next pipe iteration.


image


Now some of the pipes are going to vary in position on Y axis. So there are a minimum and maximum values that it should not be below or above. To avoid having this values in code, I just put 2 of pipe columns on screen: one at the lowest point and the other at the highest, and give them identifiers in order to read those values from code later.

 

image

 

Next click on bird in properties box and add 2 custom variables, by clicking on custom variables button. First is jump_speed=400, and second is gravity=1000 (so you can later tweak game from editor not from code)


image

 

Next up, put a “hint” and “get ready” assets convert them into composite as they always go together and give them id to hide show from game. They should go to ui layer.

 

Making Menu Scene

 

This one is easier: click on File, Scenes, Create New Scene, and choose MenuScene as name.


Make sure to put up all things just like on this picture. And note that you should make a composite for ground agai n (as we do not yet share prefabs between the scenes).


Put a Play button as image and give it an id to add listeners later in your code.


Here is how it should look:

 

image

 

Overlap2D Part DONE!


Looks pretty good! Both scenes are set up and ready for some coding. Most importantly your scene and UI are very flexible and code-independent.

 

 

 

Setting up LibGDX Project and Getting Ready to Code:

 

Download the LibGDX setup application and setup an empty project (make sure to have checked box2d and freetype fonts), import it to your eclipse or other IDE, run the desktop app to make sure it works, then strip it from LibGDX picture  and make it just a black screen.


Make sure your desktop launcher has code to specify screen size of 480x800 (config variables in launcher).


We are going to render everything using a simple LibGDX Stage, so the code structure will be the following: GameStage extending Stage that will load all the Overlap2D data and display it; Main class that will be rendering GameStage in its render method.


For all the rest we are going to use iScript functionality of Overlap2D. Let me go a bit in depth for that. Overlap2D runtime provides an interface that you can implement to create a “brain” of any composite item. Basically it is your way of attaching logic to an object. In this example we are going to create 3 iScripts, one is going to get attached to entire mainScreen and be a GameScreenScript with all game logic, other will be MenuScreenScript for menu, and the last one will be BirdScript that we will attach to the bird. It is important to mention that you cannot attach script to an image, or sprite animation, so I have converted bird animation to composite item in order to do it (right click, convert into composite).

 

You can find the full project on my github:  https://github.com/azakhary/OverlappyBird

Here are the well commented sources:

 

OverlappyBird.java

package com.underwater.demo.overflappy;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

/*
 * This is our ApplicationListener the main thing that things start in libGDX
 */
public class OverflappyBird extends ApplicationAdapter {
   
   /*
    * GameStage will be holding both menu and main game
    */
   private GameStage stage;
   
   @Override
   public void create () {
      stage = new GameStage();
   }

   @Override
   public void render () {
      // Clearing the screen before each render
      Gdx.gl.glClearColor(0, 0, 0, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      
      // calling stage act method and passing delta time passed since last call
      stage.act(Gdx.graphics.getDeltaTime());
      // drawing all actors
      stage.draw();
      
   }
}

GameStage.java

package com.underwater.demo.overflappy;

import java.io.File;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.uwsoft.editor.renderer.DefaultAssetManager;
import com.uwsoft.editor.renderer.SceneLoader;

/*
 * GameStage 
 */
public class GameStage extends Stage {
   
   // Speed of pixels per second of how fast things move left (required both for 
                                                               menu and the game,
                                                               thus put here)
   public float gameSpeed = 200;

   // Overlap2D  provides this easy asset manager that loads things as they are 
   provided by default when exporting from overlap
   private DefaultAssetManager assetManager;
   
   public GameStage() {
      super();
      
      // Set this is input processor so all actors would be able to listen to 
      touch events
      Gdx.input.setInputProcessor(this);
      
      // Initializing asset manager
      assetManager = new DefaultAssetManager();
      
      // providing the list of sprite animations which is one in this case, to 
      avoid directory listing coding
      assetManager.spriteAnimationNames = new String[1]; assetManager.
                                          spriteAnimationNames[0] = "bird";
      
      // loading assets into memory
      assetManager.loadData();
      
      // Menu goes first
      initMenu();
   }
   
   public void initMenu() {
      clear();
      
      // Creating Scene loader which can load an Overlap2D scene
      SceneLoader menuLoader = new SceneLoader(assetManager);
      
      // loading MenuScene.dt from assets folder
      menuLoader.loadScene(Gdx.files.internal("scenes" + File.separator + 
                           "MenuScene.dt"));
      
      // Initializing iScript MenuSceneScript that will be holding all menu 
      logic, and passing this stage for later use
      MenuScreenScript menuScript = new MenuScreenScript(this);
      
      // adding this script to the root scene of menu which is hold in 
      menuLoader.sceneActor
      menuLoader.sceneActor.addScript(menuScript);
      
      // Adding root actor to stage
      addActor(menuLoader.sceneActor);
      
      
   }
   
   public void initGame() {
      clear();
      
      // Creating Scene loader which can load an Overlap2D scene
      SceneLoader mainLoader = new SceneLoader(assetManager);
      
      // loading MainScene.dt from assets folder
      mainLoader.loadScene(Gdx.files.internal("scenes" + File.separator + 
                           "MainScene.dt"));
      
      // Initializing iScript GameSceneScript that will be holding all game, and 
      passing this stage for later use
      GameScreenScript gameScript = new GameScreenScript(this, mainLoader);
      
      // adding this script to the root scene of game which is hold in 
      mainLoader.sceneActor
      mainLoader.sceneActor.addScript(gameScript);
      
      // Adding root actor to stage
      addActor(mainLoader.sceneActor);
   }

}

GameScreenScript.java

package com.underwater.demo.overflappy;

import java.util.ArrayList;

import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.AddAction;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.uwsoft.editor.renderer.SceneLoader;
import com.uwsoft.editor.renderer.actor.CompositeItem;
import com.uwsoft.editor.renderer.actor.LabelItem;
import com.uwsoft.editor.renderer.script.IScript;

/*
 * iScript for entire game logic
 */
public class GameScreenScript implements IScript {
   
   /*
    * reference to GameStage
    */
   private GameStage stage;
   
   /*
    * Main actor that holds root of game screen
    */
   private CompositeItem game;
   
   // Screen loader reference to be later used to retrieve prefabs from library
   private SceneLoader loader;
   
   // Game over Dialog actor
   private CompositeItem gameOverDlg;
   
   /*
    * this will be holding 2-ground system composite item 
    */
   private CompositeItem groundRotator;
   
   /*
    * Instead of holding bird actor we are going to hold birdscript that will 
    provide all bird logic and methods.
    * Also it will have bird actor inside
    */
   private BirdScript bird;
   
   // Hint Box actor the one that shown in begining of game
   private CompositeItem hintBox;
   
   // some helping booleans
   private boolean gameStarted = false;
   private boolean groundStop = false;
   
   // going to hold what is the possible low and high position for a pipe column
   private float minPipe;
   private float maxPipe;
   
   private int gameScore = 0;
   private LabelItem scoreLbl;
   
   // Going to hold 3 pipes here to reuse as pipe pool
   private ArrayList<CompositeItem> pipes = new ArrayList<CompositeItem>();
   
   public GameScreenScript(GameStage stage, SceneLoader loader) {
      this.stage = stage;
      this.loader = loader;
   }
   
   @Override
   public void init(CompositeItem gameItem) {
      game = gameItem;
      
      gameScore = 0;
      
      // Creating and holding BirdScript that will hold entire bird logic.
      bird = new BirdScript(stage);
      game.getCompositeById("bird").addScript(bird);
      
      groundRotator = game.getCompositeById("groundRotator");
      hintBox = game.getCompositeById("hintBox");
      scoreLbl = game.getLabelById("scoreLbl");
      
      // Adding listeners to listen for taps to make bird jump
      game.addListener(new ClickListener() {
         public boolean touchDown (InputEvent event, float x, float y, int 
                                   pointer, int button) {
            return true;
         }
         public void touchUp (InputEvent event, float x, float y, int pointer, 
                              int button) {
            // screen tap was done
            screenTap();
         }
      });
      
      // Loading min/max positions from level editor
      minPipe = game.getCompositeById("minPipe").getY();
      maxPipe = game.getCompositeById("maxPipe").getY();

      // Retrieving 3 pipe columns from library putting them into array,
      // and adding on screen in minus coordinates so the will becom "availible"
      for(int i = 0;  i < 3; i++) {
         CompositeItem pipe = loader.getLibraryAsActor("pipeGroup");             
         pipe.setX(-pipe.getWidth());        
         game.addItem(pipe);
         
         pipes.add(pipe);
      }
      
      
      // Making sure first pipe will be added not sooner then 3 seconds from now
      game.addAction(Actions.sequence(Actions.delay(3.0f), Actions.run(new 
                     Runnable() {
         
         @Override
         public void run() {
            putPipe();
         }
      })));
      
      // hiding game over dialog
      gameOverDlg = game.getCompositeById("gameOverDlg");
      // it should not listen for taps
      gameOverDlg.setTouchable(Touchable.disabled);
      gameOverDlg.setVisible(false);
   }

   @Override
   public void act(float delta) {
      
      // if game is not yet started or started (but most importantly not ended, 
                                                ground is moving) 
      if(!groundStop) {
         groundRotator.setX(groundRotator.getX() - delta * stage.gameSpeed);     
         if(groundRotator.getX() < -groundRotator.getWidth()/2) groundRotator.
            setX(0);
      }
      
      // if game is started, so first tap fone, then we dhould check for 
      collisions and move pipes
      if(gameStarted) {
         for(int i = 0; i < pipes.size(); i++) {
            // get pipe
            CompositeItem pipe = pipes.get(i);
            
            // move it if it has positive coordinate
            if(pipe.getX() > -pipe.getWidth()) {
               // if pipe was right of thebird, and will now become left of the 
               bird, add to score
               if(pipe.getX() >= bird.getBirdCenter().x && pipe.getX() - delta * 
                  stage.gameSpeed < bird.getBirdCenter().x) {
                  gameScore++;
               }
               pipe.setX(pipe.getX() - delta * stage.gameSpeed);
            }
            
            //check for collision with bird
            collisionCheck();
         }
      }
      
      // update scorel label
      scoreLbl.setText(gameScore+"");
   }
   
   /*
    * Check for bird versus pipe row collision
    */
   private void collisionCheck() {
      // iterate through all 3 pipes
      for(int i = 0; i < pipes.size(); i++) {
         CompositeItem pipe = pipes.get(i);
         
         // to make it easy going to think about bird as circle with 5 radius 
         Vector2 birdPoint = bird.getBirdCenter();
         
         // Is there collision? if yes stop the game and allow bird to fall
         if(birdPoint.x+5 > pipe.getX() && birdPoint.x - 5 < pipe.getX() + pipe.
            getWidth() && (pipe.getY() + 532 > birdPoint.y - 5 || pipe.getY()+
            701 < birdPoint.y + 5)) {
            stopGame(); 
         }
         
         // Did bird hit the ground? not only stop the game but also 
         // disable gravity to keep from further falling, and consider bird dead 
         ( animations stop )
         if(birdPoint.y-5 < groundRotator.getY()+groundRotator.getHeight()) {
            if(!groundStop) {
               stopGame();
            }
            bird.disableGravity();
            bird.getBird().setY(groundRotator.getY()+groundRotator.getHeight()+5)
                         ;
            // killitwithfire
            bird.die();
         }
      }
   }
   
   /*
    * Stops the game
    */
   private void stopGame() {
      gameStarted = false;
      groundStop = true;
      game.clearActions();
      
      // show end game dialog
      showEndDialog();
   }
   
   /*
    * showing end game dialog
    */
   public void showEndDialog() {
      // enabling touch back, showing
      gameOverDlg.setTouchable(Touchable.enabled);
      gameOverDlg.setVisible(true);
      // setting transparency to full
      gameOverDlg.getColor().a = 0;
      // and fading it in
      gameOverDlg.addAction(Actions.fadeIn(0.4f));
      
      // setting play button listener to replay the game
      gameOverDlg.getImageById("playBtn").addListener(new ClickListener() {
         public boolean touchDown (InputEvent event, float x, float y, int 
                                   pointer, int button) {
            return true;
         }
         public void touchUp (InputEvent event, float x, float y, int pointer, 
                              int button) {
            stage.initGame();
         }
      });
   }
   
   /*
    * Called when screen is tapped
    */
   private void screenTap() {
      // if ground is not moving then bird is dead no actin required on tapp
      if(groundStop) return;
      
      // if game started just jump the bird
      if(gameStarted) {
         bird.jump();
      } else {
         // if game is not yet started, start the game and jump the bird
         gameStarted = true;
         hintBox.addAction(Actions.fadeOut(0.3f));
         // and also enable gravity from now on
         bird.enableGravity();
         bird.jump();
      }
   }
   
   /*
    * get's availible pipe
    * availible pipe is any pipe that is left of screen and not visible
    */
   public CompositeItem getAvailablePipe() {
      for(int i = 0; i < pipes.size(); i++) {
         if(pipes.get(i).getX() <= -pipes.get(i).getWidth()) {
            return pipes.get(i);
         }
      }
      
      return null;
   }
   
   /*
    * this is called every X time to put a new pipe on the right
    */
   public void putPipe() { 
      // getting availible pipe
      CompositeItem pipe = getAvailablePipe();
      
      // when you die at bad moment, it can be null sometimes
      if(pipe == null) return;
      
      // put pipe column on the random hight from min to max range
      pipe.setX(stage.getWidth());
      pipe.setY(MathUtils.random(minPipe, maxPipe));
      
      // schedule next pipe to be put in 1.3 seconds
      game.addAction(Actions.sequence(Actions.delay(1.3f), Actions.run(new 
                     Runnable() {
         
         @Override
         public void run() {
            // call itself
            putPipe();
         }
      })));
   }

}

 

MenuScreenScript.java

 

package com.underwater.demo.overflappy;

import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.uwsoft.editor.renderer.actor.CompositeItem;
import com.uwsoft.editor.renderer.actor.ImageItem;
import com.uwsoft.editor.renderer.actor.SpriteAnimation;
import com.uwsoft.editor.renderer.script.IScript;

/*
 * iScript for menu logic
 */
public class MenuScreenScript implements IScript {
   
   /*
    * reference to GameStage
    */
   private GameStage stage;
   
   /*
    * this is the main root menu actor to work with
    */
   private CompositeItem menu;
   
   /*
    * this will be holding 2-ground system composite item 
    */
   private CompositeItem groundRotator;
   
   /*
    * this will be the bird sprite animation displayed in center of screen
    */
   private SpriteAnimation bird;
   
   // this variables are used to wiggle bird up and down with sin function
   private float iterator = 0;
   private float birdInitialPos;
   
   public MenuScreenScript(GameStage stage) {
      this.stage = stage;
   }

   public void init(CompositeItem menuItem) {
      menu = menuItem;
      
      // Finding playButton by id and storing in variable
      ImageItem playBtn = menuItem.getImageById("playBtn");
      
      // Finding ground composite and storing in variable 
      groundRotator = menuItem.getCompositeById("groundRotator");
      
      // Finding bird and storing in variable
      bird = menuItem.getSpriteAnimationById("bird");
      
      // let's remember where bird was initially
      birdInitialPos = bird.getY();
      
      // Adding a Click listener to playButton so we can start game when clicked
      playBtn.addListener(new ClickListener() {
         // Need to keep touch down in order for touch up to work normal (libGDX 
                                                                          awkward
                                                                          ness)
         public boolean touchDown (InputEvent event, float x, float y, int 
                                   pointer, int button) {
            return true;
         }
         public void touchUp (InputEvent event, float x, float y, int pointer, 
                              int button) {
            // when finger is up, ask stage to load the game
            stage.initGame();
         }
      });
   }
   
   /*
    * This is called every frame
    */
   public void act(float delta) {
      // moving ground left with game speed multiplied by delta as delta shows 
      what part of second was passed since last call
      groundRotator.setX(groundRotator.getX() - delta * stage.gameSpeed);     
      
      // if ground rotator got half way left, we can just put it back to 0, and 
      to eye it will look like it endlessly moves
      if(groundRotator.getX() < -groundRotator.getWidth()/2) groundRotator.setX(
         0);
      
      // Now this part is to wiggle bird up and down, we are going change 
      iterator based on time passed
      iterator += delta*400;
      
      // Then figure out the bird offset from it's original position based on 
      iterator which is based on time passed, and do it with sinus function
      float birdOffset = MathUtils.sinDeg(iterator)*5;
      
      // put bird on it's original pos + offset
      bird.setY(birdInitialPos + birdOffset); 
   }
   
}

 

BirdScript.java

 

package com.underwater.demo.overflappy;

import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.uwsoft.editor.renderer.actor.CompositeItem;
import com.uwsoft.editor.renderer.actor.SpriteAnimation;
import com.uwsoft.editor.renderer.script.IScript;

/**
 * Bird Script
 * @author azakhary
 * This is brain of the bird, it's physics and everything
 */
public class BirdScript implements IScript {

   /*
    * reference to GameStage
    */
   private GameStage stage;
   
   // Bird composite item actor
   private CompositeItem bird;
   
   // Inside bird composite actor there is the bird sprite animation actor
   private SpriteAnimation birdAnimation;
   
   // used to wiggle the bird in the air using Sine function
   private float iterator = 0;
   
   // current vertical velocity of the bird
   private float currVerticalVelocity = 0;
   
   // boolean to know if gravity is enabled or not
   private boolean isGravityEnabled = false;
   
   // to avoid jumping to rotation bird will try to always rotate a bit towards 
   desired rotation
   private float desiredRotation;
   
   // is it alive?
   private boolean isAlive = true;
   
   
   public BirdScript(GameStage stage) {
      this.stage = stage;
   }
   
   @Override
   public void init(CompositeItem item) {
      bird = item;
      
      // find animation from the composite
      birdAnimation = bird.getSpriteAnimationById("birdAnimation");
      
      // set origin of the bird in it's center, so it will rotate normally
      bird.setOrigin(bird.getWidth()/2, bird.getHeight()/2);
      
      // set desired rotation to current rotation which is 0
      desiredRotation = bird.getRotation();
   }

   @Override
   public void act(float delta) {
      
      if(!isGravityEnabled && isAlive) {
         // Wiggling when no gravity only
         iterator += delta*400;
         float birdOffset = MathUtils.sinDeg(iterator)*5;
         birdAnimation.setY(birdOffset);
      }
      
      // aplying gravity every frame
      gravity(delta);
      
      // moving to new position based on current vertical velocity
      bird.setY(bird.getY() + delta*currVerticalVelocity);
      
      // manage bird rotation based on it's vertical speed
      manageRotation(delta);
      
   }
   
   /*
    * manage bird rotation based on it's vertical speed
    * this is a part of code that is not interesting boring and whatever..
    */
   private void manageRotation(float delta) {
      if(isGravityEnabled) {
         if(currVerticalVelocity > -200) {
            float rotation = currVerticalVelocity+200;
            desiredRotation = rotation/15f;
         }
         if(currVerticalVelocity <= -200) {
            float rotation = currVerticalVelocity+200;
            if(rotation < -400) rotation = -400;
            desiredRotation = rotation/4.4f;
         }
         
         if(desiredRotation != bird.getRotation()) {
            if(desiredRotation > bird.getRotation()) {
               bird.setRotation(bird.getRotation() + 900*delta);
               if(desiredRotation < bird.getRotation()) bird.setRotation(
                  desiredRotation);
            }
            if(desiredRotation < bird.getRotation()) {
               bird.setRotation(bird.getRotation() - 900*delta);
               if(desiredRotation > bird.getRotation()) bird.setRotation(
                  desiredRotation);
            }
         }
      }
   }
   
   public void enableGravity() {
      isGravityEnabled = true;
   }
   
   public void disableGravity() {
      isGravityEnabled = false;
   }
   
   public void jump() {
      // if bird is dead do not jump (I think I checked it somewhere already)
      if(!isAlive) return;
      
      // if bird is higher then screen then do not jump
      if(bird.getY() > stage.getHeight()) return;
      
      // if jumped get the custom variable jump_speed from bird actor and set it 
      as current vertical velocity
      currVerticalVelocity = bird.getCustomVariables().getFloatVariable(
                             "jump_speed");
   }
   
   /*
    * Apply gravity each frame (get's delta time since last frame)
    */
   private void gravity(float delta) {
      if(isGravityEnabled) {
         // change curernt velocity based on gravity (gravity changes velocity 
                                                      every second by gravity 
                                                      amount)
         currVerticalVelocity -= delta*bird.getCustomVariables().
                                 getFloatVariable("gravity");
      }
   }
   
   public CompositeItem getBird() {
      return bird;
   }
   
   // get's the bird center coordinates as vector 2 needed for collision 
   detection in GameScreenScript
   public Vector2 getBirdCenter() {
      Vector2 vec = new Vector2(bird.getX() + bird.getWidth()/2, bird.getY() + 
                    bird.getHeight()/2);
      return vec;
   }
   
   // Kills the bird, for reals
   public void die() {
      currVerticalVelocity = 0;  
      isAlive = false;
      desiredRotation = 0; 
      bird.setRotation(0);
      birdAnimation.pause();
   }

}

Programming, Design , , ,




Adventures in Phaser with TypeScript–Particles

5. September 2014

 

 

Other than being a word my brain seems to think is spelled incorrectly, Particles are a common part of many games.  Fortunately Phaser has pretty good support for particles.  In this tutorial we are going to take a look at how they are used.

 

First, a quick introduction to particles.  A particle system is simply a mass of things, namely particles.  A particle is often ( as in this case ) a simple sprite.  The entire idea behind a particle system is to control a large number of particles using a single controller.  Particles are commonly used to create effects like fire and smoke, where each dozens, hundreds or thousands of smoke and flame particles are emitted ( pushed ) from the particle emitter.  As the emitter moves, so do the particles emitted from it.  This allows you to define over all behavior in the emitter, not each particle.  If that makes no sense, don’t worry, the examples below should clear it up.

 

Let’s take a look at a very basic emitter.  First we need a particle graphic.  In this case I am using the following graphic:

 

particle

 

It’s a simple transparent png image named particle.png.  Now the code:

 

/// <reference path="phaser.d.ts"/>

class SimpleGame {
    game: Phaser.Game;
    sound: Phaser.Sound;
    emitter: Phaser.Particles.Arcade.Emitter;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', { create: 
                    this.create, preload: this.preload});
    }
    preload() {
        // Load the image we are going to use for our particle
        this.game.load.image("particle", "particle.png");
    }
    create() {
        // Now we are creating the particle emitter, centered to the world
        this.emitter = this.game.add.emitter(this.game.world.centerX, this.game.
                       world.centerY);
        // Make the particles for the emitter to emmit.  We use the key for the 
        particle graphic we loaded earlier
        // We want 500 particles total
        this.emitter.makeParticles('particle', 1, 500, false, false);
        // And BOOM, emit all 500 particles at once with a life span of 10 
        seconds.
        this.emitter.explode(10000, 500);
    }
}

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

 

Now when you run this code:

 

p1

 

500 particles using our png texture “explode” out of the emitter all at once.  The code is fairly heavily commented to explain what exactly is going on so I am going to move on to the next example.

 

Some ( most? ) of the time, you arent going to want all of your particles exploding all at once, except perhaps if you are modeling an explosion that is, instead you often want them to stream over time, perhaps from a moving source.  Also, you often want to use more than a single particle graphic for variety.  Finally, you often want those particles to physically interact with the world.  This example is going to do all of this.

 

This time we are going to use multiple (poorly edited by me) image files for our particles:

particleparticle2particle3

 

And now the code:

 

/// <reference path="phaser.d.ts"/>

class SimpleGame {
    game: Phaser.Game;
    sound: Phaser.Sound;
    emitter: Phaser.Particles.Arcade.Emitter;
    sprite: Phaser.Sprite;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload: this.preload,
            update: this.update
        });
    }
    preload() {
        // This time we have 3 different particle graphics to use
        this.game.load.image("particle", "particle.png");
        this.game.load.image("particle2", "particle2.png");
        this.game.load.image("particle3", "particle3.png");

        this.game.load.image("logo", "gfslogo.png");
    }
    update() {
        // This checks for and handles collisions between our sprite and 
        particles from the emitter
        this.game.physics.arcade.collide(this.sprite, this.emitter);
    }
    create() {
        var start = new Date().getTime();
        for (var i = 0; i < 1e7; i++) {
            if ((new Date().getTime() - start) > 10000) {
                break;
            }
        }
        this.emitter = this.game.add.emitter(0, 0);
        // As you can see, you can pass in an array of keys to particle graphics
        this.emitter.makeParticles(['particle', 'particle2', 'particle3'], 1, 
                                   500, false, false);
        // Instead of exploding, you can also release particles as a stream
        // This one lasts 10 seconds, releases 20 particles of a total of 500
        // Which of the 3 graphics will be randomly chosen by the emitter
        this.emitter.start(false, 10000, 20, 500, true);

        // This line of code illustrates that you can move a particle emitter.  
        In this case, left to right across
        // The top of the screen.  Ignore details tweening for now if it's new, 
        we will discuss later
        this.game.add.tween(this.emitter).to({ x: this.game.width }, 10000,null,
                            true,0,1,true).start();

        // Let's create a sprite in the center of the screen
        this.sprite = this.game.add.sprite((this.game.width / 2) - 100, (this.
                      game.height / 2) - 100, "logo");
        // We want it to be part of the physics of the world to give something 
        for particles to respond to
        // Note, we will cover physics in more detail later ( after tweening 
                                                              perhaps... ;) )
        this.game.physics.enable(this.sprite);
        this.sprite.body.immovable = true;
    }
}

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

 

And run it:

 

p2

 

As you can see, you can provide multiple particles, move the emitter and have it physically interact with the scene.  Don’t worry over much about tweening or physics, these are two subjects we will cover later in more detail.

 

In these two examples, we’ve looked at particles like you would use for special effects work, a very common situation.  That said, Particles can actually be used to control a large number of game entities that have common over all behavior, but randomized location, rotation, size or scale.  Take for example, a flight of animated birds.  You might want to add birds flying in the background of your game.  Let’s take a look at how to do this!

 

First I am using (a full sized version) of this sprite sheet taken from here.

robin-782x1024

 

It’s an animated sequence of a robin in flight.  It contains 22 frames, each 240x314 pixels in size.

 

Now let’s take a look at the code:

 

/// <reference path="phaser.d.ts"/>


// Create our own Particle class
class MyParticle extends Phaser.Particle {
    elapsedTime: number;
    currentFrame: number;
    static MAX_FRAME: number = 22;
    game: Phaser.Game;

    // In the constructor, randomly pick a starting frame of animation so all 
    the 
    // birds arent animated at the same rate
    constructor(game: Phaser.Game, x: number, y: number, key?: any, frame?: any) 
                {
        this.currentFrame = Math.floor(Math.random() * MyParticle.MAX_FRAME);
        this.elapsedTime = 0;
        this.game = game;

        // Now call Particle's constructor, passing in the spritesheet and frame 
        to use initially
        super(game, x, y, "ss", this.currentFrame);
    }

    update() {
        super.update();

        // Ever 100ms move to the next frame of animation
        this.elapsedTime += this.game.time.elapsed;
        if (this.elapsedTime >= 100) {
            this.currentFrame++;
            if (this.currentFrame > MyParticle.MAX_FRAME) this.currentFrame = 0;
            this.frame = this.currentFrame;
            this.elapsedTime = 0;
        }
    }
}

class SimpleGame {
    game: Phaser.Game;
    sound: Phaser.Sound;
    emitter: Phaser.Particles.Arcade.Emitter;

    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() {
        // Now we are creating the particle emitter, centered to the world
        this.emitter = this.game.add.emitter(this.game.world.centerX, this.game.
                       world.centerY);

        this.emitter.particleClass = MyParticle;
        this.emitter.makeParticles();
        
        // In this case, we dont want gravity affecting the birds and we dont 
        want them to rotate
        this.emitter.gravity = 0;
        this.emitter.minRotation = 0;
        this.emitter.maxRotation = 0;

        // Now start emitting particles.  Total life of 1000 seconds, create one 
        per 500ms ( 2/sec )
        // and create a total of 100 birds.
        this.emitter.start(false, 100000, 500, 100, true);
    }
}

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

 

And when run:

 

p3

 

The terrible graphics are a side effect of being converted to an animated GIF that would take forever to download!

 

It just dawned on me that I haven’t actually covered Spritesheets yet… oops.  Hey, this is how you use a spritesheet! :)  Don’t worry if you struggle with the spritesheet portions, we will cover that later as well.  The important part here is the Particle itself.  In this example we extend the class Particle to create our own Particle class.  This class then handles updating itself resulting in the animation of the bird.  Obviously you could put a great deal more logic in there, although be sure to keep things pretty light computationally, especially if you intend to create a number of them.

 

This example actually illustrates a couple of really nice features of TypeScript, but maps nicely to Phaser’s JavaScript.  The first in the concept of a constructor.  This is code that is called as the object is created.  The next more important concept is class and extend.  In this case we are extending an existing JavaScript class, Particle.  A quick look behind the curtains now.

 

In TypeScript we write:

 

class MyParticle extends Phaser.Particle

 

This results in the JavaScript

 

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
// Create our own Particle class
var MyParticle = (function (_super) {
    __extends(MyParticle, _super);

 

Pretty cool stuff, and certainly easier to read and maintain.

 

A Small Bug

 

While writing this I ran into a small bug I figured I should make you aware of ( and one of the downsides of working with TypeScript ).  In the code sample we had the following line:

 

this.emitter.particleClass = MyParticle;

 

This line is specifying the type of class to use for a Particle, no an instance of the class.  Unfortunately the Phaser.d.ts file is incorrect in it’s definition.  It instead expects particleClass to receive a Phaser.Particle instance.  This is wrong ( and took some time to route out ).  In the definition, if not fixed by the time you read this, make the following edit to Emitter:

 

particleSendToBack: boolean;
// MJF Fix particleClass: Phaser.Sprite;
particleClass: any;

 

Hopefully that will be fixed by the time you read this.

 

Programming , , , ,




LibGDX Tutorial 13: Physics with Box2D Part 1: A Basic Physics Simulations.

27. August 2014

 

Today we are going to look at implementing physics in LibGDX.  This technically isn’t part of LibGDX itself, but instead is implemented as an extension.  The physics engine used in LibGDX is the popular Box2D physics system a library that has been ported to basically every single platform and language ever invented, or so it seems. We are going to cover how to implement Box2D physics in your 2D LibGDX game.  This is a complex subject so will require multiple parts.

 

If you’ve never used a Physics Engine before, we should start with a basic overview of what they do and how they work.  Essentially a physics engine takes scene information that you provide, then calculates “realistic” movement using physics calculations.  It goes something like this:

  • you describe all of the physics entities in your world to the physics engine, including bounding volumes, mass, velocity, etc
  • you tell the engine to update, either per frame or on some other interval
  • the physics engine calculates how the world has changed, what’s collided with what, how much gravity effects each item, current speed and position, etc
  • you take the results of the physics simulation and update your world accordingly.

 

Don’t worry, we will look at exactly how in a moment.

 

First we need to talk for a moment about creating your project.  Since Box2D is now implemented as an extension ( an optional LibGDX component ), you need to add it either manually or when you create your initial project.  Adding a library to an existing project is IDE dependent, so I am instead going to look at adding it during project creation… and totally not just because it’s really easy that way.

 

When you create your LibGDX project using the Project Generator, you simply specify which extensions you wish to include and Gradle does the rest.  In this case you simply check the box next to Box2d when generating your project like normal:

 

image

 

… and you are done.  You may be asking, hey what about Box2dlights?  Nope, you don’t currently need that one.  Box2dlights is a project for simulating lighting and shadows based off the Box2d physics engine.  You may notice in that list another entity named Bullet.  Bullet is another physic engine, although more commonly geared towards 3D games, possibly more on that at a later date.  Just be aware if you are working in 3D, Box2d isn’t of much use to you, but there are alternatives.

 

Ok, now that we have a properly configured project, let’s take a look at a very basic physics simulation.  We are simply going to take the default LibGDX graphic and apply gravity to it, about the simplest simulation you can make that actually does something.  Code time!

 

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
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.Vector2;
import com.badlogic.gdx.physics.box2d.*;

public class Physics1 extends ApplicationAdapter {
    SpriteBatch batch;
    Sprite sprite;
    Texture img;
    World world;
    Body body;

    @Override
    public void create() {

        batch = new SpriteBatch();
        // We will use the default LibGdx logo for this example, but we need a 
        sprite since it's going to move
        img = new Texture("badlogic.jpg");
        sprite = new Sprite(img);

        // Center the sprite in the top/middle of the screen
        sprite.setPosition(Gdx.graphics.getWidth() / 2 - sprite.getWidth() / 2,
                Gdx.graphics.getHeight() / 2);

        // Create a physics world, the heart of the simulation.  The Vector 
        passed in is gravity
        world = new World(new Vector2(0, -98f), true);

        // Now create a BodyDefinition.  This defines the physics objects type 
        and position in the simulation
        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        // We are going to use 1 to 1 dimensions.  Meaning 1 in physics engine 
        is 1 pixel
        // Set our body to the same position as our sprite
        bodyDef.position.set(sprite.getX(), sprite.getY());

        // Create a body in the world using our definition
        body = world.createBody(bodyDef);

        // Now define the dimensions of the physics shape
        PolygonShape shape = new PolygonShape();
        // We are a box, so this makes sense, no?
        // Basically set the physics polygon to a box with the same dimensions 
        as our sprite
        shape.setAsBox(sprite.getWidth()/2, sprite.getHeight()/2);

        // FixtureDef is a confusing expression for physical properties
        // Basically this is where you, in addition to defining the shape of the 
        body
        // you also define it's properties like density, restitution and others 
        we will see shortly
        // If you are wondering, density and area are used to calculate over all 
        mass
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;
        fixtureDef.density = 1f;

        Fixture fixture = body.createFixture(fixtureDef);

        // Shape is the only disposable of the lot, so get rid of it
        shape.dispose();
    }

    @Override
    public void render() {

        // Advance the world, by the amount of time that has elapsed since the 
        last frame
        // Generally in a real game, dont do this in the render loop, as you are 
        tying the physics
        // update rate to the frame rate, and vice versa
        world.step(Gdx.graphics.getDeltaTime(), 6, 2);

        // Now update the spritee position accordingly to it's now updated 
        Physics body
        sprite.setPosition(body.getPosition().x, body.getPosition().y);

        // You know the rest...
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        batch.draw(sprite, sprite.getX(), sprite.getY());
        batch.end();
    }

    @Override
    public void dispose() {
        // Hey, I actually did some clean up in a code sample!
        img.dispose();
        world.dispose();
    }
}

 

The program running:

 

test

 

What's  going on here is mostly defined in the comments, but I will give a simpler overview in English.  Basically when using a Physics Engine, you create a physical representation for each corresponding object in your game.  In this case we created a physics object ( Body ) that went along with our sprite.  It’s important to realize, there is no actual relationship between these two objects.  There are a couple of components that go into a physics body, BodyDef which defines what type of body it is ( more on this later, for now realize DynamicBody means a body that is updated and capable of movement ) and FixtureDef, which defines the shape and physical properties of the Body.  Of course, there is also the World, which is the actual physics simulation.

 

So, basically we created a Body which is the physical representation of our Sprite in the physics simulation.  Then in render() we call the incredibly important step() method.  Step is what advances the physics simulation… basically think of it as the play button.  The physics engine then calculations all the various mathematics that have changes since the last call to step.  The first value we pass in is the amount of time that has elapsed since the last update.  The next two values control the amount of accuracy in contact/joint calculations for velocity and position. Basically the higher the values the more accurate your physics simulation will be, but the more CPU intensive as well.  Why 6 and 2?  ‘cause that’s what the LibGDX site recommend and that works for me.  At the end of the day these are values you can tweak to your individual game.  The one other critical take away here is we update the sprites position to match the newly updated body’s position.  Once again, in this example, there is no actual link between a physics body and a sprite, so you have to do it yourself.

 

There you go, the worlds simplest physics simulation.  There are a few quick topics to discuss before we move on.  First, units.

 

This is an important and sometimes tricky concept to get your head around with physics systems.  What does 1 mean?  One what?  The answer is, whatever the hell you want it to be, just be consistent about it!  In this particular case I used pixels.  Therefore 1 unit in the physics engine represents 1 pixel on the screen.  So when I said gravity is (0,-98) that means gravity is applied at a rate of –98 pixels along the y axis per second.  Just as commonly, 1 in the physics engine could be meters, feet, kilometer, etc… then you use a custom ratio for translating to and from screen coordinates.  Most physics systems, Box2d included, really don’t like you mixing your scales however.  For example, if you have a universe simulation where 1 == 100 miles, then you want to calculate the movement of an Ant at 0.0000001 x 100miles per hour, you will break the simulation, hard.  Find a scale that works well with the majority of your game and stick with it.  Extremely large and extremely small values within that simulation will cause problems.

 

Finally, a bit of a warning about how I implemented this demo and hopefully something I will cover properly at a later date.  In this case I updated the physics system in the render loop.  This is a possibility but generally wasteful.  It’s fairly common to run your physics simulation at a fixed rate ( 30hz and 60hz being two of the most common, but lower is also a possibility if processing restrained ) and your render loop as fast as possible.

 

In the next part we will give our object something to collide with, stay tuned.

Programming , , ,




Adventures in Phaser with TypeScript–Audio

19. August 2014

 

 

Now that we’ve covered input and graphics, it’s time we move on to audio.  Here is a bit of a warning upfront…

 

HTML5 audio sucks.

 

Yeah, that’s about it in nutshell.  This is one of those areas where games in HTML5 really suffer and sadly it doesn’t seem to be going away any time soon.  There are two major things to be aware of right up front.

 

First, audio file formats.  Different browsers support different file formats, but not all the same formats sadly.  You can read a pretty good chart on the topic right here.  In a nutshell, some support ogg, some support mp3, some support wav and some support m4a.  To make things even more fun, mp3 is a license encumbered format that could result in heavy licensing fees if your game is successful.  In reality, it’s never really enforced, but just the possibility should be enough to make you wary.  Fortunately, Phaser provides a way to deal with all of this that you will see shortly.

 

Second, well, Safari on iOS really kinda stinks at audio for a couple glaring reasons.  First and foremost, you can only play one sound or video at a time…  Yeah, really.  If you play a second sound, the first immediately stops.  Kinda. Big. Deal.  You can however work around this using an audio sprite, which is basically a bunch of audio files smashed together into a single file.  A second major failing is you can’t play audio on page load in Safari.  This means if you want to load your game up to a title screen with some music playing… you cant.  Audio can only be started in response to a users touch.  Yeah, this sucks too.  This one unfortunately you cannot work around, short of using a wrapper like CocoonJS for “natively” deploying your HTML5 game.

 

Through this all, you are probably going to need a tool to either merge your audio, or convert to a variety of formats.  Fortunately there is a free and excellent audio editor named Audacity available, that makes the process fairly painless.  In order to follow this tutorial, you are going to have to get an audio file and save it in mp3 and ogg format and add it to your project.

 

OK, enough about the HTML5 audio warts, let’s get to some code! 

 

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

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', { create: this.create, preload: this.preload });
    }
    preload() {
        this.game.load.audio("GameMusic", ["song.mp3","song.ogg"]);
    }
    create() {
        this.sound = this.game.add.audio('GameMusic');
        this.sound.play();
    }
}

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

 

It’s important to note, this example wont actually work in Safari on iOS due to the limitation of only being able to play audio in response to a user touch.  You would have to change it so the play() call is done in a touch handler.

 

Here what you are doing is preloading audio using game.load.audio().  The parameters are the key to refer to the audio file, and a list of files to load.  This is where the magic happens, you should provide all supported file formats, then Phaser will serve the one that performs best on the browser the user is using.  M4A files perform the best on iOS, and don’t have the legal encumbrance that MP3, so OGG and M4A would probably be all you needed, but I may be wrong here.  If in doubt, provide all 3.

 

Now let’s look at an example that allows you to control playback of the sound file:

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    sound: Phaser.Sound;
    playButton: Phaser.Button;
    pauseButton: Phaser.Button;
    stopButton: Phaser.Button;
    volUpButton: Phaser.Button;
    volDownButton: Phaser.Button;
    muteButton: Phaser.Button;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', { create: this.create, preload: this.preload, 
render
: this.render }); } preload() { this.game.load.audio("GameMusic", ["song.mp3", "song.ogg"]); this.game.load.image("button", "button.png", false); } render() { this.game.debug.soundInfo(this.sound, 0, 100); } create() { this.sound = this.game.add.audio('GameMusic'); // Set up sound event handlers on the sound object this.sound.onPlay.add(() => { alert("Played"); }); this.sound.onPause.add(() => { alert("Paused"); }); // Play Button this.playButton = this.game.add.button(0, 0, "button", () => { if (this.sound.currentTime > 0) this.sound.resume(); else this.sound.play(); } , this); this.playButton.addChild(new Phaser.Text(this.game, 17, 18, "Play", { fill: '#ff0000' })); // Pause Button this.pauseButton = this.game.add.button(95, 0, "button", () => { this.sound.pause(); } , this); this.pauseButton.addChild(new Phaser.Text(this.game, 12, 18, "Pause", { fill: '#ff0000' })); // Stop Button this.stopButton = this.game.add.button(190, 0, "button", () => { if (this.sound.isPlaying) { this.sound.stop(); this.sound.currentTime = 0; } } , this); this.stopButton.addChild(new Phaser.Text(this.game, 17, 18, "Stop", { fill: '#ff0000' })); // Volume Up Button this.volUpButton = this.game.add.button(300, 0, "button", () => { this.sound.volume += 0.1; } , this); this.volUpButton.addChild(new Phaser.Text(this.game, 17, 18, "Vol +", { fill: '#ff0000' })); // Volume Down Button this.volDownButton = this.game.add.button(400, 0, "button", () => { this.sound.volume -= 0.1; } , this); this.volDownButton.addChild(new Phaser.Text(this.game, 17, 18, "Vol -", { fill: '#ff0000' })); // Mute Button this.volDownButton = this.game.add.button(500, 0, "button", () => { // Global mute! Use this.sound.mute to mute a single sound this.game.sound.mute = !this.game.sound.mute; } , this); this.volDownButton.addChild(new Phaser.Text(this.game, 17, 18, "Mute", { fill: '#ff0000' })); } } window.onload = () => { var game = new SimpleGame(); };

 

Here is the resulting app:

 

 

It’s a bit of a monster, but most of the code is actually just wiring up the buttons.  There are a few important take away points here.  First, you can work with the local sound object, or all sounds globally using game.sound.  Second, each action on the sound file ( play, resume, stop, etc ) have an appropriate event handler you can implement.  I only did a couple in this example.  Finally, volume is a value from 0 to 1.  You can go above or below this range, but it wont actually do anything.  All said, once you get over the file format issues, playing audio is relatively straight forward.

 

Finally, let’s touch on audiosprites again for a second.  As mentioned earlier, an audiosprite is actually a bunch of audio files smashed together into a single file.

 

Consider the following sound effects.  A gun cocking ( http://www.freesound.org/people/woodmoose/sounds/177054/ ) and a gun shot ( http://www.freesound.org/people/18hiltc/sounds/228611/ ).  Load your first sound effect into audacity, like so:

image

 

Take note of the end of the file, in this case 0.785 seconds.

 

Now, select File->Import-> Audio

image

 

Import your additional sound effects, in this case I’m opening the gunshot file.  You should now have two tracks in Audacity, like so:

image

 

Now select the bottom track by double clicking.  It should highlight in gray, like so:

image

Now click at the end of the first track and paste ( CTRL + V, or EDIT->Paste ).  You should now have a single track that looks like this:

image

 

Now save this file ( might as well create OGG, MP3 and M4A versions while you are at it ).

 

Now lets take a look how we use it in code.

 

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

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', { create: this.create, preload: this.preload, 
render
: this.render }); } preload() { this.game.load.audio("sfx", ["GunSounds.ogg", "GunSounds.wav"]); } render() { this.game.debug.soundInfo(this.sound, 0, 100); } create() { this.sound = this.game.add.audio('sfx'); this.sound.addMarker("gunCock", 0, 0.785); this.sound.addMarker("gunShoot", 0.786, 1.49); this.sound.play("gunCock"); this.sound.onMarkerComplete.add(() => { this.sound.play("gunShoot"); }); } } window.onload = () => { var game = new SimpleGame(); };

 

This plays the first sound, then immediately once it is complete, it plays the other.  As you can see, you do so by setting markers within the entire sound file.  0.785 is the length of the first sound effect, then 1.49 is the length of the entire file.  You simply name each marker, then give it’s start and end locations within the file.  You can get these values using an audio editor, such as audacity.  This allows you to load all of your similar sound effects into a single quicker to load file and should help you work around the single sound stream limitations of iOS.

 

Programming , , , ,