31. March 2015

 

Today I suppose, the new tutorial series covering creating a 2D game in both Unreal and Unity officially kicked off.  I just finished publishing this videoUntitled 7 ( embedded below ) to YouTube.

 

In many ways the video covers the same topics as the earlier announcement post.  Additionally it also goes into a bit of the differences between Unity 5 and Unreal Engine 4, especially from a licensing perspective, and area where Unity and Unreal differ a great deal.

 

We also cover some of the similarities and differences between Unity and Unreal Engine, which are probably more alike than you realize.  We go into the languages and platforms supported by each engine.  Of course we also describe the goals of this entire series.  If you are already familiar with Unity and Unreal and read the last posts, there isn’t really anything new here.

 

Once again, your comments and feedback will shape how I continue, so the earlier you can get suggestions in to me, the more likely I am to be able to cover them! Next up I will be doing a learning resources post for each engine, then we will jump in to the technical details, so stay tuned!

 

Unity vs Unreal Engine Tutorial Series –The Series Introduction

 

This space left intentionally vague.

Programming

29. March 2015

 

I’ve been trying to decide what major project to embark on here at Gamefromscratch.com.  All of the current tutorial series are at a stage that I feel they are “good enough” to get anyone started and I will keep adding to them over time.  Once I reach that point I need to decide on what project to work on next.  It’s both a fun and frustrating problem to have!

 

I’ve been thinking about it long and hard, then recently there were some major announcements I simply couldn’t afford to ingore.  First the folks over at Unreal announced that Unreal Engine would no longer have a monthly subscription.  This is actually something I called for ( with a fair bit of hyperbole… ) when Unreal Engine 4 was released.  Immediately after, and with much thunder stolen, Unity made a very similar announcement.  These lowered barriers of entry vastly increased the appeal of both engines.

 

I’ve long intended to cover both engines in more detail.  I immediately subscribed to Unreal 4 on it’s release and did a bit of an overview post.  I never got the opportunity to get much deeper, as frankly, there is a pretty steep learning curve attached and I simply didn’t have the time.  Way back when I launched this game I was intending to “create a game from scratch” using Unity.  Somewhere along the way I got distracted and we ended up with a series of LibGDX, Phaser, Blender, HTML, C++, JavaScript and more game development tutorials.  Oops.

 

So, basically I’ve always intended to cover both for the longest time, but which one should I cover first?

 

I struggled with this for a long time, going back and forth between the two so many times I got nowhere.  Then I had a thought…

 

Lot’s of you have got to be asking “What should I use, Unity or Unreal?”.  It’s a fair and difficult question, as I obviously can’t decide myself!  So I am going to learn both and document the process, both in text and video.  So essentially I am going to do a Unity and Unreal tutorial series at the same time, learning both and documenting the process in both video and text form as I go.

 

Untitled 7

 

That all said…  this thread title and the above image are both a bit on the sensational side.  I am not actually comparing the two engines, there will never be a “Unity is greater than Unreal” or vice versa conclusion.  Both engines are obviously quite viable, popular and each has it’s own strengths and weakness.  Determining which engine is better than the other engine all comes down to your own preferences and requirements.  At this point arguing which engine is better is about as useful as the endless programming language wars.

 

Instead I will be going the process of creating a typical 2D game ( at least initially, 2D only ) in each game engine, documenting the process as thoroughly as possible.  So by the time I am done I should have a fairly comprehensive tutorial series covering creating a 2D game in each engine, and you should have a nice side by side comparison of how each engine works, which should aid in your selection process.

 

I intend to cover subjects such as the following, for each engine, in both video and text tutorial form:

  • Engine overview
  • Learning resources
  • Simple graphics
  • Game loop/Event processing
  • Input
  • Audio
  • Animation
  • Level composition
  • Collisions
  • Physics
  • AI
  • Networking ( maybe )
  • etc…

 

So basically all the pieces that go in to making a simple game.  I will learn it in one engine, document the process, learn it in the other engine, document the process then continue on to the next item in the list.  Obviously if there is something you think I should cover, let me know and I’ll do my best.

 

There are a few caveats of course…  first, this might take a very long time.  I’ve a lot of learning to do here, so there might be a bit of lag between posts.  The biggest catch though is I’ll be documenting things I’ve only just learned!  Expect some mistakes, inefficiencies and other hiccups as I go.  Obviously as I go I will try to be as “right” as possible, but I am no subject matter expert here!  I have a small bit of experience with both engines and tons of experience with game programming in general, but I don’t for a second claim to be an expert with either technology!

 

One other aspect of a game project like this is obviously game assets.  For a programmer, often getting art assets is as much of a time sink as programming!  Therefore I am going to be implementing this project in parallel with another very interesting art tutorial over at 2dgameartforprogrammers to create and release all of the assets to create a game called BotBox.

 

So, essentially I am going to attempt to create that game using both the Unity and Unreal game engines.  Wish me luck and I hope you enjoy it!

 

Of course, any and all feedback highly appreciated.  Please have patience with me… this might take a while!

Programming, News, General , ,

29. March 2015

 

The popular HTML5 library Phaser have just released 2.3.  It’s not a huge new functionality release, but it’s got some major architecture changes that will affect you greatly if you are a Phaser user.  First off, they went down a more modular approach leading to fewer god classes.  This is aPhaser 2.3.0 good thing™.  Then thanks to this redesign, they also made the Phaser build process different, allow you to disuse unneeded portions.

 

From the release notes:

 

Significant Updates

 

GAME OBJECTS AND COMPONENTS

All of the core Game Objects have received an important internal restructuring. We have moved all of the common functions to a new set of Component classes. They cover functionality such as 'Crop', 'Physics Body', 'InCamera' and more. You can find the source code to each component in the src/gameobjects/components folder of the repo.

All of the Game Object classes have been restructured to use the new component approach. This puts an end to the "God classes" structure we had before and removes literally hundreds of lines of duplicate code. It also allowed us to add features to Game Objects; for example Bitmap Text objects are now full-class citizens with regard to physics capabilities.

Although this was a big internal shift from an API point of view not much changed - you still access the same methods and properties in the same way as before. Phaser is just a lot leaner under the hood now.

It's worth mentioning that from a JavaScript perspective components are mixins applied to the core game objects when Phaser is instantiated. They are not added at run-time or are dynamic (they never get removed from an object once added for example). Please understand that this is by design.

You can create your own custom Phaser classes, with your own set of active components by copying any of the pre-existing Game Objects and modifying them.

 

CUSTOM BUILDS

As a result of the shift to components we went through the entire source base and optimised everything we could. Redundant paths were removed, debug flags removed and new stub classes and hooks were created. What this means is that it's now easier than ever to "disable" parts of Phaser and build your own custom version.

We have always included a couple of extra custom builds with Phaser. For example a build without P2 Physics included. But now you can strip out lots of additional features you may not require, saving hundreds of KB from your build file in the process. Don't use any Sound in your game? Then you can now exclude the entire sound system. Don't need Keyboard support? That can be stripped out too.

As a result of this work the minimum build size of Phaser is now just 83KB (minified and gzipped).

Please see this tutorial on how to create custom builds.

 

ARCADE PHYSICS

We've updated the core of Arcade Physics in a number of significant ways.

First we've dropped lots of internal private vars and moved to using non-cached local vars. Array lengths are no longer cached and we've implemented physicsType properties on Game Objects to speed-up the core World collideHandler. All of these small changes have lead to a nice improvement in speed as a result, and also allows us to now offer things like physics enabled BitmapText objects.

More importantly we're now using a spacial pre-sort for all Sprite vs. Group and Group vs. Group collisions. You can define the direction the sort will prioritize via the new sortDirection property. By default it is set to Phaser.Physics.Arcade.LEFT_RIGHT. For example if you are making a horizontally scrolling game, where the player starts on the left of the world and moves to the right, then this sort order will allow the physics system to quickly eliminate any objects to the right of the player bounds. This cuts down on the sheer volume of actual collision checks needing to be made. In a densely populated level it can improve the fps rate dramatically.

There are 3 other directions available (RIGHT_LEFT, TOP_BOTTOM and BOTTOM_TOP) and which one you need will depend on your game type. If you were making a vertically scrolling shoot-em-up then you'd pick BOTTOM_TOP so it sorts all objects above and can bail out quickly. There is also SORT_NONE if you would like to pre-sort the Groups yourself or disable this feature.

Another handy feature is that you can switch the sortDirection at run-time with no loss of performance. Just make sure you do it before running any collision checks. So if you had a large 8-way scrolling world you could set the sortDirection to match the direction the player was moving in and adjust it in real-time, getting the benefits as you go. My thanks to Aaron Lahman for inspiring this update.

 

PHASER.LOADER

The Phaser.Loader has been updated to support parallel downloads which is now enabled by default (you can toggle it via the Loader.enableParallel flag) as well as adding future extensibility points with a pack/file unified filelist and an inflight queue.

There are no known incompatibilities with the previous Loader. Be aware that with parallel downloading enabled the order of the Loader events may vary (as can be seen in the "Load Events" example).

The parallel file concurrency limit is available in Loader.maxParallelDownloads and is set to 4 by default. Under simulated slower network connections parallel loading was a good bit faster than sequential loading. Even under a direct localhost connection parallel loading was never slower, but benefited most when loading many small assets (large assets are more limited by bandwidth); both results are fairly expected.

The Loader now supports synchronization points. An asset marked as a synchronization point must be loaded (or fail to load) before any subsequent assets can be loaded. This is enabled by using the withSyncPoint and addSyncPoint methods. Packs ('packfile' files) and Scripts ('script' files) are treated as synchronization points by default. This allows parallel downloads in general while allowing synchronization of select resources if required (packs, and potentially other assets in the future, can load-around synchronization points if they are written to delay final 'loading').

Additional error handling / guards have been added, and the reported error message has been made more consistent. Invalid XML (when loading) no longer throws an exception but fails the particular file/asset that was being loaded.

Some public methods/properties have been marked as protected, but no (except in case of a should-have-been-private-method) public-facing interfaces have been removed. Some private methods have been renamed and/or removed.

A new XHR object is created for each relevant asset (as there must be a different XHR for each asset loaded in parallel). Online searches indicated that there was no relevant benefit of XHR (as a particular use-case) re-use; and time will be dominated with the resource fetch. With the new flight queue an XHR cache could be re-added, at the cost of some complexity.

The URL is always transformed through transformUrl, which can make adding some one-off special cases like #1355 easier to deal with.

This also incorporates the fast-cache path for Images tags that can greatly speed up the responsiveness of image loading.

Loader.resetLocked is a boolean that allows you to control what happens when the loader is reset, which happens automatically on a State change. If you set resetLocked to true it allows you to populate the loader queue in one State, then swap to another State without having the queue erased, and start the load going from there. After the load has completed you could then disable the lock again as needed.

Thanks to @pnstickne for vast majority of this update.

 

PIXI V2

We are now using our own custom build of Pixi v2. The Pixi project has moved all development resources over to Pixi v3, but it wasn't ready in time for the release of Phaser 2.3 so we've started applying our own fixes to the version of Pixi that Phaser uses.

As a result we have removed all files from the src/pixi folder that Phaser doesn't use, in order to make this distinction clearer. This includes EventTarget, so if you were relying on that in your game you'll need to add it back in to your local build.

We've also removed functions and properties from Pixi classes that Phaser doesn't require: such as the Interaction Manager, Stage.dirty, etc. This has helped us cut down the source code size and make the docs less confusing, as they no longer show properties for things that weren't even enabled.

We've rolled our own fixes into our version of Pixi, ensuring we keep it as bug-free as possible.


You can read the entire release notes here.

Programming, News ,

24. March 2015

 

In this tutorial we start looking at 3D game development using LibGDX.  We explore creating a Camera, Model, ModelInstance and look at the basics of working in 3D using LibGDX.

 

You can watch the tutorial in HD here or embedded below.  The following is the source used in this example.

 

The Source


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.*;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.*;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.Vector3;

public class Demo3D extends ApplicationAdapter implements InputProcessor {
    private PerspectiveCamera camera;
    private ModelBatch modelBatch;
    private ModelBuilder modelBuilder;
    private Model box;
    private ModelInstance modelInstance;
    private Environment environment;
   
   @Override
   public void create () {
        camera = new PerspectiveCamera(75,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
        camera.position.set(0f, 0f, 3f);
        camera.lookAt(0f,0f,0f);
        camera.near =0.1f;
        camera.far = 300f;

        modelBatch = new ModelBatch();
        modelBuilder = new ModelBuilder();
        box = modelBuilder.createBox(2f,2f,2f,
                new Material(ColorAttribute.createDiffuse(Color.BLUE)),
                VertexAttributes.Usage.Position|VertexAttributes.Usage.Normal);
        modelInstance = new ModelInstance(box,0,0,0);
        environment = new Environment();
        environment.set(new ColorAttribute(ColorAttribute.AmbientLight,0.8f,0.8f,0.8f,1f));

        Gdx.input.setInputProcessor(this);
   }

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

        camera.update();
        modelBatch.begin(camera);
        modelBatch.render(modelInstance,environment);
        modelBatch.end();
   }

    @Override
    public boolean keyDown(int keycode) {
        // In the real world, do not create NEW variables over and over, create
        // a temporary static member instead
        if(keycode == Input.Keys.LEFT)
            camera.rotateAround(new Vector3(0f, 0f, 0f), new Vector3(0f, 1f, 0f), 1f);
        if(keycode == Input.Keys.RIGHT)
            camera.rotateAround(new Vector3(0f,0f,0f),new Vector3(0f,1f,0f), -1f);
        return true;
    }

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

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

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

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

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

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

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

 

The Video


Programming , , ,

19. March 2015

 

In this tutorial we are going to take a look at two key topics in Godot game development, Collision Detection and Physics Simulations.  Collision Detection is simply detecting if two objects overlap.  Physics on the other hand simulates the movement and interaction of game objects based on physical properties.  This of course also includes handling collisions.  There is also a video of this tutorial and this might be one of those times, due to all of the motion in the results, that you may in fact want to refer to the video even if you prefer text based tutorials.  So if you struggle to understand what I am talking about here, be sure to quickly check the video, it may have the answer.

 

You can watch the video here, or embedded below.

 

Checking for Collisions

 

Let’s start with checking collisions between two objects, in this case, two different Sprite objects.  I have created the following scene:

image

It’s simply two sprite objects side by side.  I then attached a script to the one on the left.  This script updates the position of the left sprite until a collision occurs, at which point it resets to the beginning and does it all over again.  Like so:

anim

 

Let’s take a look at the script now:

extends Sprite

var start_pos = Vector2()
var box1 = null
var box2 = null

func _ready():
   set_process(true)
   start_pos = get_pos()
   box1 = RectangleShape2D.new()
   box2 = RectangleShape2D.new()



func _process(delta):
   # Get a reference to the other sprite
   var sprite2 = get_node("/root/SceneRoot/Sprite 2")
   
   # Update our location
   self.move_local_x(0.1)
   
   # set the boundaries of each RectangleShape2D to those of the texture making up our sprite
   # values are relative to center, thus half width and height
   box1.set_extents(Vector2(self.get_texture().get_size().width/2,self.get_texture().get_size().height/2))
   box2.set_extents(Vector2(
sprite2.get_texture().get_size().width/2,sprite2.get_texture().get_size().height/2)) #Now check to see if box1 at sprite1's pos collided with box2 and sprite2's position if(box1.collide(get_transform(),box2,sprite2.get_transform())): set_pos(start_pos) # it did, so reset position to beginning, what's old is new again!

Essentially what you are doing here is creating a RectangleShape2D using the boundaries of each Sprite’s texture image.  AKA, creating a rectangle the size of the texture.  You then check if box1 at the transformed position of Sprite1 collides with box2 at the transformed position of Sprite2.  Of course, since they both use the same texture map, you don’t actually need to create two different RectangleShape2D objects!  Also, since the size never changes, you don’t actually need to set_extents() in process().  There are a number of simple shape classes that can be used to check for collisions such as concave and convex polygons, circles and even rays ( for mouse picking ).

 

This is one way to check for simple collisions.  However you will quickly find it gets unwieldy as you add more and more objects and have to check them against each other.  Fortunately the physics engine makes this process a whole lot easier.

 

Physics Simulations

 

Now that we looked at a way to test for collisions, lets move on and discuss the physics system.  Basically a physics engine simulates movement using complex math, calculating how items interact with each other and external forces like gravity.  The physics simulation then updates, either on a fixed or per frame basis, a set of objects with the new locations calculated by the simulation.  You then update your visible game objects positions accordingly.  In Godot however, you don’t generally need to perform that last step, it’s done automatically.

 

Let’s start with an extremely simple example, gravity.

 

First we start by creating a RigidBody2D node:

image

 

Next, parented to the RigidBody2D node, create a sprite node.  I am using the default icon.png that comes with Godot.  Your heirarchy should look like this:

image

 

… and that’s it.  You have now created a physics object that gravity will be applied to.  Run your game and you should see:

anim2

 

Now let’s pause a second to see exactly what is happening here.

 

First, let’s start with the RigidBody2D part…  There are three kinds of physics objects you can use in your 2D game world:

image

The biggest difference is how they are dealt with by the simulation.

 

A RigidBody can be thought of as a typical physics object.  It’s the most processing intensive, but it’s also got the most functionality.  Unless you have a reason otherwise, if something needs physics, it’s probably a rigid body.  This is a physics object that can move, can collide with other objects and itself by collided with.

 

Next up is the StaticBody2D.  This is an unmoving object in your world.  Basically things can hit it, it can be hit, but it doesn’t move.  It also takes a lot less processing power to handle.  Generally things like the world, or invisible but unmoving triggers will be static bodies.

 

Finally is KinematicBody2D.  This is a physics object that doesn’t have the range of functionality of a rigid body ( for example, you cant apply force to it ), but can move and can collide with other physics objects.  The biggest thing about a Kinematic body is that its motion is generally controlled directly by you no the physics simulation.  Generally this is the character sprite.  You want the physics simulation to react to its actions, but you generally control those movements directly in code.

 

So, those are the three major types of physics objects, now let’s look at global settings.  You notice how gravity is being applied to our simulation automatically?  Where is this coming from?

 

The answer is trust ole project settings:

image

 

So… what do those values means?  Well this is one of the nice things about working entirely in Godot.  In many physics engines like Box2D, you work in meters, then have to translate from meters to pixels when transforming your sprites.  In godot, these values are in pixels.  So a gravity value of 98 means gravity moves at 98 pixels per second.

 

Now what about Rigid Body settings?  Well let’s take a look:

image

 

Mass Friction and Bounce are the most commonly used values.  Hey, aren’t mass and weight the same thing?  Nope, not exactly.  Mass is the amount of “stuff” that composes and object, while weight is the amount that stuff weighs.

 

Consider the classic question “What weighs more, a ton of bricks or a ton of feathers?”  Both objects would have identical weights ( one ton ), but vastly different masses.  In some ways it can be easier to think of mass instead as density. 

 

Friction on the other hand is how it slides in contact with another surface.  Picture sliding a mouse down a surface on a 45 degree angle.  If one surface was rubber and the other was glass, the mouse is going to move at vastly different rates.  Friction controls this.   Bounce is often refered to as restitution.  This is the amount of, well, bounce in an object.  Or how much it reacts to a collision.  A rubber ball has a higher “Bounce” value, while a brick is almost 0.  Another key concept is sleep, this is the ability to turn the Rigid Body off during calculations, determines if it is or isn’t used as part of the over all simulation.  Linear and Angular velocity finally are the default movement values of the object.

 

Collisions Physics Style

 

Now let’s take a look at how collisions are handle using a Physics engine.  Let’s change the above scene to add another physics item, this time a static body, like so:

image

 

The top sprite has a RigidBody2D as it’s parent.  The bottom has a StaticBody2D for a parent.  Now we need to define a collision volume for each one, just like we did back at the beginning.  Simple add a new node to each Body ( not the sprite, it’s parent! ) of type CollisionShape2D, so your hierarchy looks like this:

image

 

Then for each CollisionShape2D, you need to pick a bounding shape.  With the CollisionShape2D selected in Inspector simply select the Shape dropdown and pick the one that is best suited:

image

Finally, size it so it covers the collide-able portions of your sprite:

image

 

Now when you run the game:

anim3

 

Tada!  Collisions calculated by the physics engine.  Now you can play around a bit with the physical properties of your Rigid Body and see how it reacts differently.

 

In this case we used a simple box for our collision detection, and that works well for box shaped objects.  But if your object isn’t box or circle shaped, what do you do?  Enter CollisionPolygon2D:

image

 

It works exactly the same as CollisionShape2D, but you can define the shape yourself.  Remove one of the CollisionShape2D nodes and replace it with a CollisionPolygon2D node.  With the Collision node selected, you will notice a new option in the 2D window:

image

 

Click the pen, and you can now draw a polygon around your object:

image

 

And once closed:

image

A MUCH more accurate representation of your object for collisions!

 

Kinematic Nodes

 

Finally let’s look at KinematicBody2D objects.  These are special in that the physics engine doesn’t control their motion, you do.  They can however collide with entities in the physics world.  Generally speaking, this is how you would create your character.  Unlike RigidBodies you cannot apply forces or impulses.  Instead you move them directly.  Let’s create a simple example:

 

First add a KinimaticBody2D to your scene, add a sprite and collision shape for it, like so:

image

 

Now apply a script to the KinematicBody2D with the following code:

extends KinematicBody2D



func _ready():
   set_process(true)
   
func _process(delta):
   move(Vector2(0.04,0))

We are simply moving the body by 0.4 pixels per update.  As you can see from the results however collisions will occur between your game code controlled object and the physics simulation:

anim4

 

There is obviously quite a bit more to the physics simulation.  You can create joints and springs and define what objects collide with other objects, but that covers most of the basics.  Be sure to watch the video if you struggle, as it covers things in a bit more detail!

 

The Video

 

Programming , ,

Month List

DisqusCommentsSummary