Making a LibGDX Roguelike Survival Game Part 9 – Screen Shake & Inventory #gamedev

In the last tutorial trees could be removed from the map by interacting (pressing ‘E’) on them, as the trees are being cut down lets add in a small screen shake. On a tree being cut down we will add it the the Hero inventory (we will need to create a basic inventory).

[ Full source code for this tutorial ]

shakes

Rumble.java
Rumble allows us to return a Vector allowing us to move the camera relevant to a shake size for a given time in seconds. The variables and methods in this class are all static, so we will be able to use the class without creating an instance of it. Rumble.rumble(1,10) will set the power to 1 and the length of the shake to 10 seconds, the current time is reset to 0.

We have to call the tick method to update the x and y values of the Vector3 to new random values taking into account the size of the shake and update the current time. When current time is greater than time (shake was lasted 10 seconds) we reset the time to 0.

package uk.co.carelesslabs;

import java.util.Random;
import com.badlogic.gdx.math.Vector3;

public class Rumble {
    private static float time = 0;
    private static float currentTime = 0;
    private static float power = 0;
    private static float currentPower = 0;
    private static Random random;
    private static Vector3 pos = new Vector3();

    public static void rumble(float rumblePower, float rumbleLength) {
        random = new Random();
        power = rumblePower;
        time = rumbleLength;
        currentTime = 0;
    }

    public static Vector3 tick(float delta) {
        if (currentTime <= time) {
            currentPower = power * ((time - currentTime) / time);

            pos.x = (random.nextFloat() - 0.5f) * 2 * currentPower;
            pos.y = (random.nextFloat() - 0.5f) * 2 * currentPower;

            currentTime += delta;
        } else {
            time = 0;
        }
        return pos;
    }

    public static float getRumbleTimeLeft() {
        return time;
    }

    public static Vector3 getPos() {
        return pos;
    }
}

Entity.java
The interact method is changed to accept Entity as a parameter:

public void interact(Entity entity){}

Hero.java
When the Hero Entity interacts with another Entity we pass itself, this will give us access to the Hero in the Tree interact method:

// If interact key pressed and interactEntities present interact with first in list.
if(control.interact && interactEntities.size() > 0){
  interactEntities.get(0).interact(this);
}

Tree.java
When a tree is removed we can use Rumble to change the power and time, 1 is a small shake and .2 of a second is a short period:

@Override
public void interact(Entity entity){
    remove = true;
    Rumble.rumble(1, .2f);
}

gameclass.java
We update the render section of gameclass where previously there was only “camera.position.lerp(hero.pos, .2f);”, we now check if there is a shake/rumble to process, if there is then the camera is taken over by the rumble. When the rumble is complete the camera lerps back the the hero.

// Hero Position
if (Rumble.getRumbleTimeLeft() > 0){
    Rumble.tick(Gdx.graphics.getDeltaTime());
    camera.translate(Rumble.getPos());
 } else {
     camera.position.lerp(hero.pos, .2f);
}

Before we look at how we implement a basic inventory lets try out a larger shake just for fun:

Rumble.rumble(3, 5) :big_shake

Control.java
Setup the “I” key to turn on inventory, we can use this to print out the current inventory when ever I is pressed:

public boolean inventory;
... 
// Key up 
case Keys.I:
    inventory = true;
    break;

Inventory.java
This is just a basic class to hold an array of inventory entities and will change in future tutorials. To future proof the idea of the inventory it is better to create a new class rather than testing some inline solution. The class uses a HashMap but any array type would be fine at the moment, we need methods to initialise the array, add to it, return its size and print to console our current inventory:

package uk.co.carelesslabs.entity;

import java.util.HashMap;

public class Inventory {
    HashMap&amp;amp;lt;Integer, Entity&amp;amp;gt; entities;

    public Inventory(){
        reset();
    }

    public int getInventorySize(){
        return entities.size();
    }

    public void addEntity(Entity entity) {
        entities.put(getInventorySize(), entity);
    }

    public HashMap<Integer, Entity> getInventory(){
        return entities;
    }

    public void print() {
        System.out.println("*** Inventory ***");
        for(int i = 0 ; i < entities.size(); i++){
            Entity e = entities.get(i);
            System.out.println("* ["+i+"] " + e.type.toString());
        }    
        System.out.println("*****************");
    }

    public void reset() {
        entities = new HashMap<Integer, Entity>();
    }
}

Entity.java
Add a new Inventory variable to the Entity class:

public Inventory inventory;

Hero.java
Inventory is initialised within Hero and not in the base class, not every Entity will require one:

public Hero(Vector3 pos, Box2DWorld box2d){
   type = EntityType.HERO;
   width = 8;
   height = 8;
   texture = Media.hero;
   speed = 30;
   inventory = new Inventory(); // Init Inventory
   reset(box2d, pos);
}

Tree.java
When an Entity interacts with a Tree we check if that entity has an inventory, at present only our Hero has an inventory, given this is true we add the Tree to the inventory array of entities, flag the tree for removal from the map and trigger some screen shake, more logic will be applied here later:

@Override
public void interact(Entity entity){
    if(entity.inventory != null){
        entity.inventory.addEntity(this);
        remove = true;
        Rumble.rumble(1, .2f);
    }
}

gameclass.java
Checking if inventory key has been pressed we can call the method/function that prints out the entities in the current inventory array and then set inventory boolean to false:

// Render method
...
if(control.inventory){
    hero.inventory.print();
    control.inventory = false;
}

Running the application and hitting down some trees our inventory will contain some entities, pressing “I” will print out the current inventory to the console:

*** Inventory ***
* [0] TREE
* [1] TREE
* [2] TREE
*****************

 

 

 

 

 

 

 

 

 

 

 

Making a LibGDX Roguelike Survival Game Part 8 – Collision Listeners & Interacting #gamedev

When our Hero collides with certain bodies within our Island we want to be able to interact with them in some way. Most of the bodies exist only to stop us walking through objects, some are set as sensors, we can walk through them but our game is aware of when we come into contact with them and when we lose that contact.  Here is a gif (quite long) explaining how we can handle those collisions. We will go into more detail of the code but hopefully this helps explain the process:

[ Full source code for this tutorial ]

collision_anim

Box2D currently stops the player passing through the boundaries on the Island and walking over trees, to add interactions to objects we can implement listeners to handle collisions.

Before we look at using the Box2D callbacks for collisions we need to add some variables and methods to the Entity class. We have already added a body which acts as a collision hitbox, we add a new body called sensor, this will be a body which can be passed over.

Entity.java

public class Entity implements Comparable<Entity> {
    public int hashcode; // to be explained.
    public Body sensor; // A trigger hitbox
    public boolean remove;

When a collision occurs on the body of an Entity we will call the collision method, the first param of entity is the object that was collided with and begin is true if the hit-boxes started to overlap or false is the collision has ended (They no longer overlap).

The interact method will be overrode to handle the player using an object in some way.

The removeBodies method will be used to remove an entities bodies from the world, cutting down a tree for example would remove it from the Island, we would no longer need the bodies for collisions, leaving them in place would leave behind invisible blocks.

public void collision(Entity entity, boolean begin){}

public void interact(){}
public void removeBodies(Box2DWorld box2D) {
    if(sensor != null) box2D.world.destroyBody(sensor);
    if(body != null) box2D.world.destroyBody(body);
}

Control.java

Add a new class boolean called interact, this is set to true on key up of ‘E’, this is the ‘use’ key.  Once an interaction is processed it will set this value back to false.

// ACTIONS
public boolean interact;
...
public boolean keyUp(int keycode) {
  switch (keycode) {
    case Keys.E:
      interact = true;
      break;

Box2DHelper.java

A new method called createSensor which is almost identical to the createBody method creates hit boxes that are used like triggers. Our Hero will be able to pass over these hitboxes; the key line of code is fixtureDef.isSensor = true;  :

public static Body createSensor(World world, float width, float height, float xOffset, float yOffset, Vector3 pos, BodyDef.BodyType type) {
        Body body;
        BodyDef bodyDef = new BodyDef();
        bodyDef.position.x = pos.x + xOffset;
        bodyDef.position.y = pos.y + yOffset;
        bodyDef.angle = 0;
        bodyDef.fixedRotation = true;
        bodyDef.type = type;
        body = world.createBody(bodyDef);

        FixtureDef fixtureDef = new FixtureDef();
        PolygonShape boxShape = new PolygonShape();
        boxShape.setAsBox(width / 2, height / 2);

        fixtureDef.shape=boxShape;
        fixtureDef.isSensor = true;

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

        return body;
    }

Box2DWorld.java

There are significant changes to the Box2DWorld class, first we add a HashMap to store the Island entities, you may wonder why we store two entity arrays (two arrays with the same entities), one for drawing/logic and this new array for dealing with collisions. A HashMap stores key and value, we set the key to the body hashcode and the value as the Entity. When a collision (contact) occurs we get access to the two fixtures present in the collision, these fixtures are the bodies (body and sensor) that are defined within Entity, by using the hashcode for the key we can select the correct Entity from the array without having to loop.

Given the Hero body has a code of 001 and the Tree sensor has a code of 333, when a contact between the two occur we get fixtureA and fixtureB from the contact, lets say A is the body of the Hero and B is the sensor of the Tree. We can look up the two entities by using the hash codes of the fixtures (bodies).

public class Box2DWorld {
  public World world;
  private Box2DDebugRenderer debugRenderer;
  // New array to hold entities
  private HashMap<Integer, Entity> entityMap;

  public Box2DWorld(){
    world = new World(new Vector2(.0f, .0f), true);
    debugRenderer = new Box2DDebugRenderer();
    // Init the new entity array
    entityMap = new HashMap<Integer, Entity>();

    // Setup the world contacts listeners
    world.setContactListener(new ContactListener() {
      @Override
      public void beginContact(Contact contact) {
        Fixture fixtureA = contact.getFixtureA();
        Fixture fixtureB = contact.getFixtureB();

        process_collisions(fixtureA, fixtureB, true);
      }

      @Override
      public void endContact(Contact contact) {
        Fixture fixtureA = contact.getFixtureA();
        Fixture fixtureB = contact.getFixtureB();

        process_collisions(fixtureA, fixtureB, false);
      }

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

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

  public void tick(OrthographicCamera camera, Control control){
  if (control.debug) debugRenderer.render(world, camera.combined);
    world.step(Gdx.app.getGraphics().getDeltaTime(), 6, 2);
    world.clearForces();
  }

  // Method to clear down all bodies
  public void clearAllBodies() {
    Array<Body> bodies = new Array<Body>;();
    world.getBodies(bodies);
      for(Body b: bodies){
      world.destroyBody(b);
    }

    entityMap.clear();
  }

  // check if the two bodies colliding exist in our array of entities
  // check that only one entity is a sensor
  // When entityA is a sensor then entityB is the player as its the only
  // moving object.
  // We want to call the Entity method collision for the hero:
  // ... Hero.collision(Tree, true)
  private void process_collisions(Fixture aFixture, Fixture bFixture, boolean begin) {
    Entity entityA = entityMap.get(aFixture.hashCode());
    Entity entityB = entityMap.get(bFixture.hashCode());

    if(entityA != null && entityB != null){
      if(aFixture.isSensor() && !bFixture.isSensor()){
        entityB.collision(entityA, begin);
      } else if(bFixture.isSensor() && !aFixture.isSensor()){
        entityA.collision(entityB, begin);
      }
    }
  }

  // Pass in Island entities and copy them into a new
  // array that has a key (the hashcode of the entity).
  public void populateEntityMap(ArrayList<Entity> entities){
    entityMap.clear();
    for(Entity e: entities){
      entityMap.put(e.hashcode, e);
    }
  }

  // When a tree/hero is added to the island we
  // track it in the entity array
  public void addEntityToMap(Entity entity){
    entityMap.put(entity.hashcode, entity);
  }

  // removes an entity from the array
  public void removeEntityToMap(Entity entity){
    entityMap.remove(entity.hashcode, entity);
  }
}

Hero.java

A new ArrayList of entities is added to keep track of the entities currently in contact with the hero hitbox (Body), the player may be overlapping more than one tree for example, but we will only allow interactions with one at a time.

When collisions or contacts occur with other entities they will be added to this array, when those contacts are broken (collision is no longer true) the entities will be removed from this array. When a collision occurs with the hero body then we use the hashcode of the body which we get via the contact > fixture to select the hero from the hashmap and call the collision method.

When the hero update is called we pass in control and check if interact is true, if it is and the interactEntity array has items then we call the interact method on that entity:

// Class variable. Array of entities currently overlapping/coliding with.
ArrayList<Entity> interactEntities;

body = Box2DHelper.createBody(box2d.world, width/2, height/2, width/4, 0, pos, BodyType.DynamicBody);
// Set hashcode to that of the bodies fixture
// Our body has a single fixture
hashcode = body.getFixtureList().get(0).hashCode();
// init the Entity Array
interactEntities = new ArrayList<Entity>();

public void update(Control control) {
        dirX = 0;
        dirY = 0;

        if (control.down)  dirY = -1;
        if (control.up)    dirY = 1;
        if (control.left)  dirX = -1;
        if (control.right) dirX = 1;    

        body.setLinearVelocity(dirX * speed, dirY * speed);
        pos.x = body.getPosition().x - width/2;
        pos.y = body.getPosition().y - height/4;

        // If interact key pressed and interactEntities present interact with first in list.
        if(control.interact && interactEntities.size() > 0){
        	interactEntities.get(0).interact();
        }

        // Reset interact
        control.interact = false;
    }

    @Override
    public void collision(Entity entity, boolean begin)
    	if(begin){
    	    // Hero entered hitbox
    	    interactEntities.add(entity);
    	} else {
    	    // Hero Left hitbox
    	    interactEntities.remove(entity);
    	}
    }

Tree.java
The sensor for the tree is setup to be bigger than the body, the body will only stop the player walking through it making it a solid object. The sensor will trigger collision callbacks, by setting the entity hashcode to that of the sensor (Body) it will be found in the hashmap of entities and we can trigger interactions with it.

On interacting with a tree we set remove to true:

public Tree(Vector3 pos, Box2DWorld box2d){
    ...
    body = Box2DHelper.createBody(box2d.world, width/2, height/2, width/4, 0, pos, BodyDef.BodyType.StaticBody);
    sensor = Box2DHelper.createSensor(box2d.world, width, height*.85f, width/2, height/3, pos, BodyDef.BodyType.DynamicBody);
    hashcode = sensor.getFixtureList().get(0).hashCode();
}

@Override
public void interact(){
    remove = true;
}

gameclass.java
The create method passes the island entities in the the box2D class instance to setup the hashmap of entities, these entities are copied, the point toward the same on entity so changing an entity in the arraylist or the hashmap array has the same outcome.

After reseting the map we have to re-populate the hashmap, the last line in the render loop is clearing out any entities that have remove set to true.

@Override
public void create() {
    ....
    // HashMap of Entities for collisions
    box2D.populateEntityMap(island.entities);
}

@Override
public void render () {
    Gdx.gl.glClearColor(0, 0, 0, 0);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    // GAME LOGIC
    if(control.reset){
        island.reset(box2D);
        hero.reset(box2D,island.getCentrePosition());
        island.entities.add(hero);
        // re-populate hashmap
        box2D.populateEntityMap(island.entities);
        control.reset = false;
    }

    ...
    island.clearRemovedEntities(box2D);
}

Island.java
The new method clearRemoverEntities uses an iterator to loop through the objects, this is a safe way to loop and change an array without causing errors:

public void clearRemovedEntities(Box2DWorld box2D) {
    Iterator<Entity> it = entities.iterator();
    while(it.hasNext()) {
        Entity e = it.next();
        if(e.remove){
            e.removeBodies(box2D);
            box2D.removeEntityToMap(e);

            it.remove();
        }
    }
}

So now we have Box2D listeners calling our collision methods everytime a contact takes place between two bodies. We filter out which contacts we are interesting in and can pass that interaction occurance to an entity to be dealt with.

At the moment we simply remove a tree when the Hero interacts with it, we will later add HP and allow many hits before it is removed also add items to the hero when it is removed as we should get resources for downing a tree.

 

Making a LibGDX Roguelike Survival Game Part 7 – Adding Trees, Entity Sorting #gamedev

** Noticed a typo in my entity package, this has been renamed 
evoscape/core/src/uk/co/carelesslans/entity/Entity.java **

[ Full source code for this tutorial ]

EvoScape is starting to look a little like a game but we yet to have any items to interact with, if we are going to have crafting etc then we need resources, to get started we will add some trees for wood. Before we look at how we handle collisions we need to populate the island with some trees.

Screen Shot 2017-08-06 at 14.24.27

The tree images needs to be saved to assets/entities/tree.png

Media.java
Add new a new class variable for the Tree texture, load it in the load_assets() method and ensure it is disposed in the dispose method:

public static Texture tree;
...
tree = new Texture("entities/tree.png");
...
tree.dispose();

Enums.java
Our EntityType enum needs a new type of “TREE” added for the Tree class, at the moment we do not need to use the type but it will come in useful when we want to save our game etc:

public enum EntityType {
 HERO,
 TREE
}

Tree.java
The Tree class extends Entity, it initialises entity its public construcor then sets the type, size, position, texture and creates a new Box2D body so it has a collision box the hero cannot walk through.

The hitbox is half the width and height, here you can see the createBody method accepts another 2 parameters, these are xOffset and yOffset. These new values allow us to have better positioned hitboxes. We want the Tree hitbox to be just the size of the trunk area:

public class Tree extends Entity{
    public Tree(Vector3 pos, Box2DWorld box2d){
        super();
        type = EntityType.TREE;
        width = 8;
        height = 8;
        this.pos = pos;
        texture = Media.tree;
        body = Box2DHelper.createBody(box2d.world, width/2, height/2, width/4, 0, pos, BodyDef.BodyType.StaticBody);
    }
}
tree_hitbox.png

The Tree hitbox.

Box2DHelper.java
The updated class adds xOffset onto the X value and yOffset onto the Y value of the entities position in the createBody method:

public static Body createBody(World world, float width, float height, float xOffset, float yOffset, Vector3 pos, BodyDef.BodyType type) {
       Body body;
       BodyDef bodyDef = new BodyDef();
       // Updated postion code.
       bodyDef.position.set( (pos.x + width/2) + xOffset, (pos.y + height/2) + yOffset);
       bodyDef.angle = 0;
       bodyDef.fixedRotation = true;
       bodyDef.type = type;
       body = world.createBody(bodyDef);

       FixtureDef fixtureDef = new FixtureDef();
       PolygonShape boxShape = new PolygonShape();
       boxShape.setAsBox(width / 2, height / 2);

       fixtureDef.shape = boxShape;
       fixtureDef.restitution = 0.4f;

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

       return body;
   }

Island.java

Before Trees can be added to the Island we need an ArrayList to store them in, the array will hold a type of Entity, any class that extends Entity can be added to this list:

// Class variable
public ArrayList<Entity> entities = new ArrayList<Entity>();

Next we create a new method that will loop through all of our tiles and randomly add trees, we will look if the tile is grass before adding one also we will roll a random number and allow there to be a 10% chance of a tree being placed:

private void addEntities(Box2DWorld box2D) {
    // Loop all tiles and add random trees
    for(ArrayList<Tile>; row : chunk.tiles){
        for(Tile tile : row){
            if (tile.isGrass()){
                if(MathUtils.random(100) > 90){
                    entities.add(new Tree(tile.pos, box2D));
                }
            }
        }
    }
}
...
// As previously shown the Tree public constuctor which is called to create
// a new tree
public Tree(Vector3 pos, Box2DWorld box2d){

Calling this method and populating Trees will work but running the game they will not be drawn, we add to our render loop after the tiles have been drawn, looping and drawing the entities. The draw method within the Entity class is called unless the Tree class overrides this method:

// Draw all entities
for(Entity e: island.entities){
    e.draw(batch);
}

Running this code will show our randomly sized map and now a number of trees, this looks great until you behind a tree and find you are rendered on top of it. To overcome this we need to add the hero to the array of entities and sort it before rendering.

Screen Shot 2017-08-05 at 23.57.32

No “Z Sorting”

Entity.java
To sort the array of Entity we implement Comparable and compare the class to itself. With that in place we add a compareTo method that will compare the Y values:

// implement comparable
public class Entity implements Comparable<Entity> {
...

// New method
public int compareTo(Entity e) {
    float tempY =  e.pos.y;
    float compareY = pos.y;

    return (tempY < compareY ) ? -1: (tempY > compareY) ? 1:0 ;
}

gameclass.java
After the Hero instance is created add it to the list of Island entities so that it can be sorted and drawn in order with the array.

// Island
island = new Island(box2D); 

// Hero
hero = new Hero(island.centreTile.pos, box2D);
island.entities.add(hero); // Add hero to entity array
...

// Before drawing the entities sort the array
Collections.sort(island.entities);

Running the game we can now move behind trees:

zSort.gif

The hero is now drawn in the correct order (based on its Y value)

Adding a reset option that re-generates the Island

Control.java
Add a new boolean to the class called reset, this will be set to true on pressing ‘R’:

// New class variable
public boolean reset;

// public boolean keyUp(int keycode) {
// new key
case Keys.R:
    reset = true;
    break;

Box2DWorld.java
To reset everything we will need to clear down all of the bodies we have added to the world, a new method clearAllBodies handles this:

// New method to remove Box2D bodies from the World
public void clearAllBodies() {
    Array<Body> bodies = new Array<Body>();
    world.getBodies(bodies);
    for(Body b: bodies){
        world.destroyBody(b);
        }
    }
 }

gameclass.java
Within our game logic (Render loop) we check this reset variable and when its true call reset on hero and island, re-add hero to entities and set reset to false:

// GAME LOGIC
if(control.reset){
    island.reset(box2D);
    hero.reset(box2D,island.getCentrePosition());
    island.entities.add(hero);
    control.reset = false;
}

Island.java
Create a new reset method and call this from the public constructor, this saves re-writing the same calls twice:

public Island(Box2DWorld box2D){
    reset(box2D);
}

public void reset(Box2DWorld box2D) {
   entities.clear();
   box2D.clearAllBodies();
   setupTiles();
   codeTiles();
   generateHitboxes(box2D);
   addEntities(box2D);
}

Hero.java
Add reset method and update the public constructor, when we reset the hero we re-position it to the centre and re-create its hitbox:

public Hero(Vector3 pos, Box2DWorld box2d){
    type = EntityType.HERO;
    width = 8;
    height = 8;
    texture = Media.hero;
    speed = 30;
    reset(box2d, pos);
}

public void reset(Box2DWorld box2d, Vector3 pos) {
    this.pos.set(pos);
    body = Box2DHelper.createBody(box2d.world, width/2, height/2, width/4, 0, pos, BodyType.DynamicBody);
}

Now when we run the game and press ‘R’ the hero is placed back to the centre of the map and we generate a new island with different number of trees.

random_island

Next we will implement collision listeners so we can act on being in contact with a tree, exciting stuff!

Making a LibGDX Roguelike Survival Game Part 6 – Box2D Collisions #gamedev

[ Full source code for this tutorial ]

Currently our hero can move around disregarding the underlying map, running over grass, cliffs and water, the next step is to impose some restrictions and implement collisions. When the project was created we chose to include Box2D:

Box2D is a 2D physics library. It is one of the most popular physics libraries for 2D games and has been ported to many languages and many different engines, including libgdx.

Using LibGDX we have to create a fair amount of the game code ourselves which can be a good thing but writting your own physics engine will slow your progress significantly, Box2D will do all the heavy lifting for us.

To get started we will need a Box2D World, creating and initialising the world will initialise Box2D.  Our world is top down so we do not need any gravity, the World takes a vector for gravity and also a boolean to set if the world objects sleep. To manage Box2D we will create a new class, as we add more features it will be cleaner to keep all of this together away from the other code.

box2DWorld.java (in a new package “uk.co.carelesslabs.box2d” )

public class Box2DWorld {
  // instance of a B2D World
  public World world;
  // Used to render objects which would be invisible
  private Box2DDebugRenderer debugRenderer;

  public Box2DWorld(){
    // Initialise world with no gravity!
    world = new World(new Vector2(.0f, .0f), true);
    // Initialise debug renderer
    debugRenderer = new Box2DDebugRenderer();
  }
  ...
}

This class has a tick method which will step the world and if debug is enabled draw the world shape outlines.

public void tick(OrthographicCamera camera, Control control){
  // Pass in control to check if debug is true
  if (control.debug) debugRenderer.render(world, camera.combined);
  // step the world forward in time
  world.step(Gdx.app.getGraphics().getDeltaTime(), 6, 2);
  world.clearForces();
}

The call to clearForces() should be done automatically so I will likely remove this call in another commit:

/** Manually clear the force buffer on all bodies. By default, forces are cleared automatically after each call to Step. The /** Manually clear the force buffer on all bodies. By default, forces are cleared automatically after each call to Step. The * default behavior is modified by calling SetAutoClearForces. The purpose of this function is to support sub-stepping. * Sub-stepping is often used to maintain a fixed sized time step under a variable frame-rate. When you perform sub-stepping * you will disable auto clearing of forces and instead call ClearForces after all sub-steps are complete in one pass of your * game loop. {@link #setAutoClearForces(boolean)} */

Next we create a helper class that can create objects for our Box2D world, to get us started we need static boxes that can be used to set a boundary around our island.

Box2DHelper.java 
(package “uk.co.carelesslabs.box2d” )
The helper class allows us to create a Box2D Body, there are several types of body, we will be creating static body types only at the moment. The Box2D site fully explains creating a new body, these bodies will match the size, shape and location of our tiles. For the body to fit over the tile we have to add have the half the width or hight to the x/y position, this is due to the co-ordinates being used as the centre point.

Creating the PolygonShape we have to half the width/height due to Box2D using this value as half the size:

/** Build vertices to represent an axis-aligned box./** Build vertices to represent an axis-aligned box. * @param hx the half-width. * @param hy the half-height. */ public void setAsBox (float hx, float hy) { jniSetAsBox(addr, hx, hy); }

Here is the helper class thus far, the method we will use is static:

public class Box2DHelper {
    public static Body createBody(World world, float width, float height, Vector3 pos, BodyDef.BodyType type) {
        Body body;
        BodyDef bodyDef = new BodyDef();
        bodyDef.position.set(pos.x + width/2, pos.y + height/2);
        bodyDef.angle = 0;
        bodyDef.fixedRotation = true;
        bodyDef.type = type;
        body = world.createBody(bodyDef);

        FixtureDef fixtureDef = new FixtureDef();
        PolygonShape boxShape = new PolygonShape();
        boxShape.setAsBox(width / 2, height / 2);

        fixtureDef.shape = boxShape;
        fixtureDef.restitution = 0.4f;

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

        return body;
    }
}

We are ready to add our Box2D class maingame.java

Box2DWorld box2D;

The new variable will need to be initialised within the create() method, a change to Island.java will be made to accept the box2D variable as a parameter:

// Box2D
box2D = new Box2DWorld();

// Island
island = new Island(box2D);

At the bottom of the render method we call the tick method of the Box2DWorld instance:

  ...
  hero.draw(batch);
  batch.end();
  // call tick method to draw debug lines
  // pass in control to check it debug is true
  box2D.tick(camera, control);
}

Island.java
Box2DWorld is needed within the Island class, once the tiles are setup we need to loop through them and check which of them require a collision object making them inpassable.

public Island(Box2DWorld box2D){
  setupTiles();
  codeTiles();
  generateHitboxes(box2D);
}

Before looking at the new generateHitboxes method there is a small fix to Chunk.java and two new methods required in the Tile.java class:

Chunk.java – getTileCode should return 0” and never a null, other wise we could end up with tile codes containing ‘nul’.

Tile.java
isAllWater checks if the tile is water surrounded by water, notIsAllWater returns if the tile is not all water. I prefer to create methods that return the opposite value so they read better, these methods could be better named though!

public boolean isAllWater() {
    return code.equals("000000000");
}

public boolean notIsAllWater() {
    return !isAllWater();
}

With those fixes and additional methods in place we can loop the tiles in the chunk once they are generated and add collision objects where needed.

Looping all of the tiles and checking that they are not passable but not all water we are finding the edge of the island, these are the tiles that should stop the hero moving further, it would be wasteful to create objects for every water tile:

private void generateHitboxes(Box2DWorld box2D) {
  for(ArrayList<Tile> row : chunk.tiles){
    for(Tile tile : row){
      if(tile.isNotPassable() && tile.notIsAllWater()){
        Box2DHelper.createBody(box2D.world, chunk.tileSize, chunk.tileSize, tile.pos, BodyType.StaticBody);
      }
    }
  }
}

Running the game and pressing the backspace key toggles control.debug, when on the debug renderer will draw the world bodies, at the moment the hero is still OP and moves where ever they want:

box2Dworld

Lets add a collision box for the hero so they are trapped on the island, the bodies added to the world for the tiles are not children of the Tile class, once created we cannot access them through the parent (tile), this will be addressed. When it comes to the hero we need to be able to move the body, first add a new variable to Entity class:

public Body body;

The hero will need the box2D variable passed into the public constructor so we can create the body via the world. The body for the hero is dynamic as it will need to move, we dont want the body to be the full height of the hero (wait for the image):

public Hero(Vector3 pos, Box2DWorld box2d){
  type = EntityType.HERO;
  width = 8;
  height = 8;
  this.pos.x = pos.x;
  this.pos.y = pos.y;
  texture = Media.hero;
  // We need to increase the speed!
  speed = 30;
  // Create a new Dynamic body
  body = Box2DHelper.createBody(box2d.world, width, height/2, pos, BodyType.DynamicBody);
}

Next change the update for the Hero class, rather than moving the Entity position we move the Box2D body but setting the linear Velocity, then we set the positon of the Entity to the x and y or the body.

If we were to set the position of the Body using the hero position then we would over ride collisions and force its position:

public void update(Control control) {
  ... 

  body.setLinearVelocity(dirX * speed, dirY * speed);
  pos.x = body.getPosition().x - width/2;
  pos.y = body.getPosition().y - height/4;
}

gameclass.java – update the setup of the Hero class as it requires box2D passed in:

hero = new Hero(island.centreTile.pos, box2D);

Running the game and turning on debug we can see the hero now has a collision box which cannot pass through the other bodies:

bodies

Next we will look at adding in trees to an array of entities and sorting these so our hero can be appear in front or behind them.

 

 

 

Making a LibGDX Roguelike Survival Game Part 5 – Code Style #gamedev #indiedev

Thanks to @cnnranderson for bringing up the Java code style.

Code style is important and coming from a background in many languages other than Java I tend to break a lot of the advice/rules that other Java developers would follow. It was also mentioned that the Vector2 position for the hero is not required, so we can fix that and some variable / method names.

[ Full source code for this tutorial ]

The updated code removes the Vector2 and updates methods and variables so they use camelcase rather than underscores.

If you are interested in the other rules / advice please read the Java code style page.

lerp

Making a LibGDX Roguelike Survival Game Part 4 – I need a hero #gamedev #indiedev

Screen Shot 2017-08-02 at 21.28.51
[ Full source code for this tutorial ]

Most games will have a main character or a hero, for the moment ours will be this little person, they can be replaced later if necessary.

The hero will need a new class that extends Entity, it will need a new texture and ENUM type. We will need to change the keyboard inputs to move the Hero Entity and have the camera follow them.

Enums.java
A new enum is needed for entities, for now we only have one type of HERO:

public enum ENTITYTYPE {
  HERO
}

Entity.java
This new enum type and speed can be added to Entity as class variables:

public ENTITYTYPE type;
public float speed;

Media.java
Add the hero image to a new folder; “assets/entities/hero/hero.png”

Add a new Texture to this class and in the load_assets function initialise it:

// HERO
public static Texture hero;
  ...
  hero = new Texture("entities/hero/hero.png");

Hero.java
The public constructor for our hero class sets the type to the newly defined HERO, we set the dimensions, texture, speed and position. The position is a Vector2, this has a x and y value and denotes the hero position on the map, the initial position is passed as a variable (pos) to the class.

public Hero(Vector2 pos){
  type = ENTITYTYPE.HERO;
  width = 8;
  height = 8;
  this.pos.x = pos.x;
  this.pos.y = pos.y;
  texture = Media.hero;
  speed = 1;
}

Previously we stored the on screen location in some temporary variables, these will now be tracked within our hero class and updated every frame:

public void update(Control control) {
  dir_x=0;
  dir_y=0;

  if (control.down) dir_y = -1 ;
  if (control.up) dir_y = 1 ;
  if (control.left) dir_x = -1;
  if (control.right) dir_x = 1;

  pos.x += dir_x * speed;
  pos.y += dir_y * speed;
}

We pass the control instance into the public update function and use the same logic as before to set the x and y values for the Hero Entity.

gameclass.java
Variables to remove from class:

// Temp x and y co-ords
int x, y;

// For Movement
int direction_x, direction_y;
int speed = 1;

Add an instance of Hero to the class:

Hero hero;

Initialise the hero instance passing in the Island.java centre tile, we will need to make this variable public in order to access it.

// Hero
hero = new Hero(island.centre_tile.pos);

Now we have the Hero class we can also remove code from the render function of the gameclass:

// This now exists in the Hero class
direction_x=0;
direction_y=0;
if (control.down) direction_y = -1 ;
if (control.up) direction_y = 1 ;
if (control.left) direction_x = -1;
if (control.right) direction_x = 1;

// Camera position will need to use the hero Vector2
camera.position.x += direction_x * speed;
camera.position.y += direction_y * speed;

The new render code to update the hero, camera position and draw our hero:

hero.update(control);
camera.position.x = hero.pos.x;
camera.position.y = hero.pos.y;
camera.update();
.....

hero.draw(batch);

We call the Hero update function every frame and pass in the control instance so we can check the WASD or arrow keys are pressed and change the positions accordingly. The draw function for the Hero is the default function held in the Entity class. If everything is correct we should now be able to move our hero around the screen, the camera position is set to that of the hero:

hero
This appears ok but the camera position is incorrect, the image below shows that snapping to the x and y positions of the hero the camera is placed at the bottom left of the image.

hero_align
To overcome this we can add new functions to the Hero class that return the correct values and call these from the render function of the gameclass:

// Hero.java
public float get_camera_x() {
  return pos.x + width/2;
}

public float get_camera_y() {
  return pos.y + height/2;
}

// Render Loop for gameclass.java
camera.position.x = hero.get_camera_x();
camera.position.y = hero.get_camera_y();

To take this one step further lets look at a function available on the camera position called Lerp. Further reading on Interpolation. This basically moves the camera toward the Hero’s position slower than the hero has moved, so we get a nice smooth/delayed camera movement.

Rather than setting the x and y values of the camera.position we can call camera.position.lerp, this requires a Vector3 rather than Vector2 so we will need to make some small changes.

Entity.java
Add a new Vector3 variable, a Vector3 holds x,y and z values, we wont need the z value so can just set this to 0 and ignore it.

public class Entity {
  public Vector2 pos;
  public Vector3 pos3;

  ...
  // initialise the new variable in the public constructor
  pos3 = new Vector3();

When we call the Hero update function we can set the Vector3 variable using the Vector2 that has already been updated after checking the for keyboard inputs:

pos3.x = pos.x;
pos3.y = pos.y;

Moving back to gameclass.java after the hero.update function is called we can set the camera position using the new Vector3 variable:

// GAME LOGIC
hero.update(control);
camera.position.lerp(hero.pos3, .1f);
camera.update();

The .1f defines the speed at which the camera catches up with the hero position, 0.1 (f stands for float) should give a steady speed, as long as the speed is less than the hero’s speed we will see some delay.

Final resultlerp.gif

We now have a randomly sized island in the sea, a hero that can move and a camera that follows, next we will look at using Box2D to handle our collisions and make sure our hero cannot walk on water.

 

 

 

 

 

 

Making a LibGDX Roguelike Survival Game Part 3 – Loading Media refactored #gamedev

LibGDX offers an asset manager that can help take care of loading and getting textures etc, feel free to take a look at this, the wiki page shows exactly how it is used. The main benefit is the asynchronous loading of assets and the ability to display a loading bar:

“Loading of most resources is done asynchronously, so you can display a reactive loading screen while things load”

Screen Shot 2017-08-02 at 15.43.37.png

[ Full source code for this tutorial ]

Our game has very few assets which are all very small in size, for now we can move the loading of Textures to a new class. In the main package uk.co.carelesslabs we will add a new file Media.java, we will move all of the Textures defined in Island.java into this new class.

Media.java

// TILE
// class variables

public static Texture grass_01, grass_02, grass_03, grass_04;
public static Texture grass_left, grass_right;
public static Texture grass_left_upper_edge, grass_right_upper_edge;
public static Texture grass_top, grass_top_right, grass_top_left;
public static Texture water_01, water_02, water_03, water_04;
public static Texture cliff, water;

There is a static function in the Media class (load_assets) which will initialise all of our textures both are defined as static:

public static void load_assets(){
  grass_01 = new Texture("8x8/grass/grass_01.png");
  grass_02 = new Texture("8x8/grass/grass_02.png");
  ...

These images will not change and we only want to load them once, as they are so small there is no need to dispose of them mid game, we can call this method from are main gameclass.java in the Create() method and our images will be ready to use:

Media.load_assets();

Island.java

We can remove the old reference to loading images (also remove the function form this calss) so the public function now looks like this:

public Island(){
  setup_tiles();
  code_tiles();
}

To fix all of the references to the textures that are no longer declared in this class we reference them via the Media class (not an instance of it):

tile.secondary_texture = Media.grass_top_right;

Once all of the references are updated the game should run as it did previously, going forward this will make the assets a little easier to manage as they will all be in one place.

This class will make it easy to add new textures and even switch between different tile sets without having to change the island, chunk or tile classes at all.