Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

15. December 2015

 

Over the years there have been many tutorial series here on GameFromScratch, many of them aimed at beginning game developers.  What there has never been is a series for complete beginners.  Every single programming tutorial I have ever written has assumed prior programming experience.  Today I am launching a new series that will change this.

image

Welcome to the newest tutorial series on GameFromScratch, Game Development for Complete Beginners.  I aim to teach game development with a focus on programming in this series.  However I am going to assume zero prior programming experience.  This means we will learn about the programming process, about variables, program flow and other key concepts.  We will also look at tools, debugging, profiling.  All critical tasks to learn for game development.  Of course this requires choosing a programming language and game engine or library.  For this, as you may guess from this page’s title, I chose Love ( or LÖVE/Love2D ) which uses the Lua programming language.  I will explain the reasons in more detail later, but for now simply realize it’s a beginner friendly combination and it’s a programming language that remains useful long past the beginning stages.

 

Of course this isn’t the kind of thing I can cover in a tutorial or two.  This will require a complete tutorial series.  I am actually composing it in chapter form and will publish each chapter here on GameFromScratch.  I will also be compiling the results together in e-book for Patreon supporters.  For each chapter there will also be one or more videos covering the same material.

 

In fact, there is already a video companion for this announcement post! Winking smile

 

Of course your feedback is always appreciated.  Hopefully this series helps makes entry into the world of game programming easier for new developers and it provides some mild amusement for more experienced readers!  Stay tuned for more.

Programming ,

13. December 2015

 

GDX AI, a Java based AI library that works with (but doesn’t require) LibGDX just released version 1.7.

 

From the change log:

[1.7.0]

- Updated to libgdx 1.7.1

- API Addition: added GdxAI service locator that reduces coupling with libgdx and allows you to use gdx-ai

out of a libgdx application without having to initialize libgdx environment, so avoiding the waste of resources

and the need of native libraries; see https://github.com/libgdx/gdx-ai/wiki/Initializing-and-Using-gdxAI

- API Change and Addition: Messaging API

* Removed delta time argument from the update method of the MessageDispatcher; the new GdxAI.getTimepiece().getTime() is internally used instead.

* Added return receipt support, see https://github.com/libgdx/gdx-ai/wiki/Message-Handling#return-receipt

* The report method of PendingMessageCallback now takes an additional argument for the return receipt.

- API Change and Addition: State Machine API

* Now the StateMachine interface has a generic type parameter for the state.

* Added owner's getter and setter to the DefaultStateMachine; also, the owner is now optional in constructor.

- API Change and Addition: Behavior tree API revised and improved, see https://github.com/libgdx/gdx-ai/wiki/Behavior-Trees

* Now tasks have a status that is updated each time they run.

* Added enum support in behavior tree files.

* Now parallel task can specify sequence or selector policy.

* Added cancel method for task termination, mainly used by the parallel task.

* Now you can add listeners to the tree in order to be notified when a task has run and a child is added.

* Now task methods setControl, success and fail are final.

* Now method addChild is final and Task's subclasses have to implement addChildToTask.

* Added decorator tasks Repeat and Random.

* Added leaf tasks Failure, Success and Wait.

* Added branch tasks RandomSelector and RandomSequence; removed deterministic attribute from Selector and Sequence.

* Now the UntilFail decorator succeeds when its child fails.

* Added ability to clone tasks through third-party libraries like Kryo.

* Added support for custom distributions in behavior tree files.

* Now LeafTask usage is less error prone thanks to the execute method.

GdxAI is available on Github or as part of the LibGDX setup.

GameDev News, Programming ,

11. December 2015

 

Don’t you just love it when someone else does your job for you?  As part of my recently completed Tiled tutorial series I was considering doing a pretty detailed tutorial on integrating it into one of the modern C# based game engines.  One engine certainly up for consideration was the Wave Engine, somewhat recently featured in the Closer Look At series.  Well thankfully I didn’t, because they went ahead and did it for me!

 

From the WaveEngine blog:

Using TiledMap to create your 2D game level

With TiledMap, developing 2D games in WaveEngine will not be the same anymore. Tiled maps have been used for a long time in games, now you can load and integrate TiledMap (.TMX) files, created by theTiled Map Editor (http://www.mapeditor.org/), the most popular map editor based in tiles. With Tiled, you can easily design your 2D map levels and run in WaveEngine like a charm.

Load a TiledMap (.tmx) in WaveEngine

1. Install WaveEngine.TiledMap NuGet package

First of all, you need to install WaveEngine.TiledMap NuGet package into your Game solution. This action allows you to use the TiledMap components into your project:

 

series continues here. 

 

With the NuGet TiledMap package, the process is actually quite simple.  They also have a Tiled map example available on Github.

Programming , ,

8. December 2015

 

This tutorial came about as a result of a question on my YouTube channel, although it is one of those things that you are going to need to know before long in 3D game programming, so I have made the answer part of the official Godot Engine tutorial series.  The question was:

I am making a 3d game and I want to use a sort [of] top down style camera.


I want it so that if an object gets between the player and the camera, that same object will become transparent. For that ( I think ) I can use the "Use Alpha" function in the fixed material settings.
So I think I need a raycast shooting rays ( between the player and the camera ) and if it hits something it needs to "find' which object was hit en change the material settings so it becomes transparent.


Now, the problem is that I don't know how to set this up;
-how can I get which object is hit by the ray and how to change the material?
-do I need to create a separate layer for this?

This is one of those things even the most simple 3D game is going to encounter, but the solution isn’t obvious, although the questioner was extremely close in his guess.  You can solve this using Ray casting, it’s probably just the how of it all that is difficult to figure out.

 

As always there is a video version of this tutorial available here.

 

If you have a situation like the above, where you want to determine if something is in the way of your camera, it’s exactly RayCasting that you want.  Let’s take a look at how.

 

Setting Up The Scene

 

First you need your scene to be set up correctly.  This means that each entity in your scene that can be collided with has to be a physics object of some kind.  I created the following scene arrangement:

image

 

As you can see, I have a camera and two Rigid Body objects, each with a CollisionShape (Cube) and a Test Cube child.  Additionally I created a RayCast object as a child of my camera.  Be sure to create the RayCast child before you transform your camera, so it is positioned properly.  For my RayCast I use the following settings:

image

 

My scene ends up looking like this:

image

 

The Code

 

As you can see, the Ray extends from my camera and through both objects in the scene.  In this example we want to see if we hit the first cube (“RigidBody 2”) and if we do, we want to hide it.  Time to look at some code, the following script was attached to the camera:

extends Camera


var ray = null

func _ready():
	ray = get_node("RayCast")
	set_process(true)


func _process(delta):
	if(Input.is_key_pressed(KEY_UP)):
		self.translate(Vector3(0,0.1,0))
	if(Input.is_key_pressed(KEY_DOWN)):
		self.translate(Vector3(0,-0.1,0))
	if(ray.is_enabled() and ray.is_colliding()):
		var collidedWithObject = ray.get_collider()
		if(collidedWithObject.get_name() == "RigidBody 2"):
			collidedWithObject.hide()
	else:
		get_parent().get_node("RigidBody 2").show()

 

… and that’s it.  We check to see that our ray is enabled and if it is currently colliding with something.  If it is, the first collided object is returned by the call get_collider().  In a bit of a hard coded hack, we check the name of that object, and if its our second cube, we hide the entire hierarchy.  In the event that no collision occurs, we make sure that RIgid Body 2 is visible with a call to Show().  You will notice that there is code in there to move the camera on press of the Up and Down arrow keys.  As you will see, as you move the camera, when the ray isn’t colliding, the second cube is shown, otherwise it is, like so:

 

GIF

 

It is also possible to create the ray programmatically using the PhysicsServer, like so:

extends Camera

func _ready():
	set_fixed_process(true)

func _fixed_process(delta):
	if(Input.is_key_pressed(KEY_UP)):
		self.translate(Vector3(0,0.1,0))
	if(Input.is_key_pressed(KEY_DOWN)):
		self.translate(Vector3(0,-0.1,0))

	var directState = PhysicsServer.space_get_direct_state(self.get_world().get_space())
	var collisions = directState.intersect_ray(get_translation(),Vector3(0,0,0))
	
	if(collisions.size() and collisions["collider"].get_name() == "RigidBody 2"):
		collisions["collider"].hide()
	else:
		get_parent().get_node("RigidBody 2").show()

 

Note that _process what changed to _fixed_process().  This is because space_get_direct_state() is only valid during _fixed_process or _integrate_forces() calls.  Otherwise we crate an intersect_ray() between the camera position and the origin, which in turn returns if there is a collision between those two points.  If there is, we hide the collided objects, otherwise we call show().

 

The Video

Programming ,

2. December 2015

 

I find once you’ve learned a couple of programming languages, the way you learn future programming languages changes a bit.  Instead of learning a language feature by feature, you instead tend to jump right in and learn the language relative to languages you already know.  In this case I find it handy to create a quick cheat sheet or Coles/Cliff notes version as I learn that programming language.  This is that sheet, so if you already know a couple programming languages and want to learn Kotlin, hopefully this will be as useful as any tutorial at getting you going quickly.  Keep in mind I don’t even pretend to be a subject matter expert here!

 

Hello World

Starting off with a Hello World example is all but required by law, so here it is:

fun main(args: Array<String>){
    println("Hello World")
}

As you can see the app entry point is main() just like most C influenced programming languages.  Functions are marked with fun keyword and unlike Java, they do not have to be in a class nor in a package really cutting down the code count.  Variables and parameters are named in the format  name:type, it is increasingly popular for variable type to be on the right ( Haxe, Swift, Go, etc ).  Otherwise nothing shocking here.  It should be noted that semicolon line terminators are completely optional.

 

Variables

Read Only Vs. Variant Types

Let's look at a simple example with variables allocated.

fun main(args: Array<String>){
    val meaningOfLife:Int = 42;
    var meaningOfDeath = meaningOfLife +1
    meaningOfLife++ // NOT ALLOWED!!!
}

Notice val and var.  A val type is read only and once initialized cannot be altered.  A var type is a traditional variable and as you can see in this case, type can be inferred automatically by the compiler.  The final line there will not compile because meaningOfLife is a read only type.  If it was a var type however, that line would compile just fine (in other words, there is a postfix increment operator in Kotlin).  Oh and Kotlin supports C++ style // Comments.  Speaking of comments…

 

Commenting

All the traditional C++ style comments are supported, as are JDoc style

// This is a comment
/*
And so is this
 */
/**
 * And this is a JDoc/KDoc style comment
 * @param args Comment documenting param args meaning
 */
fun main(args: Array<String>){

}

 

Numeric Types

Kotlin has several built in number types: Char, Byte, Short, Int, Float, Long and Double:

fun main(args: Array<String>){
    var byte: Byte = 127 // Signed byte, -128 to 127
    var char: Char = 'A' // A 16bit Unicode character
    var short: Short = Short.MAX_VALUE //16bit signed MAX_VALUE == 32767
    var int: Int = 0xff // 32bit signed, Hex can be used with 0x prefix
    var long:Long = 0b11101101// 64bit signed, binary can be used with 0b prefix
    var float:Float = 3.14f // 32bit floating point number, floats designated with f postfix
    var double:Double = 3.1e10 // 64bit floating point, IEEE notation can be used too

    //double = float; // automatic down conversation is not allowed
    //float = double; // Nor is up conversion!

    double = float.toDouble() //Explicit conversion is allowed
    float = double.toFloat()

    byte = short.toByte() // allowed, but value too big so value is -1
    short = 42;
    byte = short.toByte() // value fits, new val would be 42
}

Bigger and smaller types share no relationship, so automatic conversation does not exist, except in the case of literals.  So you cant automatically assign a short to a byte, nor a byte to a short without calling the appropriate to() method.  Truncation will occur if the type doesn’t fit the new type.

 

Functions

As we’ve seen already, functions are marked with the fun keyword.  The format is “fun named(args): return type” like so:

fun doSomething(a:Int, b:String): String {
    return "$b $a";
}

fun main(args: Array<String>){
    println(doSomething(42,"Meaning of Life is"));
}

This example declares a function that takes and Int and a String and returns a String.  This example also illustrates the use of string templates in Kotlin.  Inside a string you can use the $ symbol to do a C printf style format.  If however you need to use a dollar sign in a literal string you can escape it in the form {‘$’}.

 

Nullable Types

Functions can also return a null value, but need to be marked as such using the ? operator, like so:

fun setName(name:String) : String? {
    if(name == "Mike")
        return "Mike"
    else
        return null;
}
fun main(args: Array<String>) {
    var name = setName("Mike");
    if (name is String) {
        // in if block containing an is, no casting is required
        println(name);
    }
}

As you can see, with a type preceded with a ? can be set to null.  This example also illustrates the is operator, which is the Kotlin analog of typeof in C++.  Another neat trick is illustrated here, within the scope of an if using the is operator, typecasts are not required.  Speaking of typecasts…

 

Typecasts

As we saw earlier, all of the built in numeric types have a toXXX() method for type conversion.  However to straight casts, Kotlin has “safe” and “unsafe” casts.  An unsafe cast could potentially result in an exception because the type cast isn’t possible.  To perform an unsafe cast, use the as operator, like so:

    var i:Int = 42;
    println(i as String);

However if you run this code, BOOM!

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String.

If there is a possibility your cast could fail, instead use the operator as? like so:

 

    var i:Int = 42;
    println(i as? String);

This will result in either the casted value being returned, but if the cast cannot be performed, instead of throwing an exception, it instead returns null.

 

Conditionals and Flow Control

Kotlin works much like most modern languages with a couple exceptions.  if works pretty much like you would expect, except its an expression and returns a value ( the evaluated conditional ) like so:

    var a = 1; var b = 2;
    var bigger = if( a > b) a else b;
    println(bigger); // Prints 2

As a result Kotlin does not have C's confusing ternary ? operators. Additionally you can also set the value returned within an if block, it's simply the last value within the block. Like so:

enum class Enemies { Orc, Skeleton, Pigeon}
fun main(args: Array<String>) {
    var enemy = Enemies.Pigeon;
    println("Enemy was of type " +
        if(enemy == Enemies.Orc){
            // Do Orc related code
            "Orc";
        }
        else{
            "Not Orc";
        }
    );
}

As you can see, the final value in the if block is the returned value by the if statement.  Oh yeah… and Kotlin supports enums, as you can see from this example.

 

One other major difference in Kotlin is there is no else if, nor is there a switch statement.  Instead you have the somewhat confusingly named when that fills both roles, like so:

enum class Enemies { Orc, Skeleton, Pigeon}
fun main(args: Array<String>) {
    var enemy = Enemies.Pigeon;
    when(enemy){
        Enemies.Pigeon -> print("Pigeon");
        Enemies.Orc -> print("Orc");
        else -> {
            print("Who the heck knows at this point??")
        }
    }
}

Much like a C/C++ style switch statement except there is no case keyword, default is replaced with an else statement and you use –> instead of a colon.

You can also do ranges in when statements, like so:

fun main(args: Array<String>) {
    var meaningOfLife:Int = 42;
    when(meaningOfLife){
        in 1..22 -> print("Between 1 and 22");
        !in 22..44 -> print("Not between 22 and 44");
        else -> {
            // None of the above
        }
    }
}

 

For, while and do-while loops all work pretty much the same as other languages.  Kotlin supports break, return and continue statements and they work as expected ( and can be used to short circuit a when statement ).  You can however set a label using the @ postfix then specify it specifically in the break/continue/return statement, like so:

fun main(args: Array<String>) {
    outer@ for(i in 1..100){
        inner@ for(j in 1..100) {
            if (j == 42) {
                continue@outer;
            }
        }
    }
}

This above example will immediately cause the outer loop to jump to it’s next iteration when the inner loops condition is true, effectively short circuiting the inner loop. (Yes, an un-labeled break would have the exact same result)

 

Extension Method

Class can be easily via extensions methods.

class A {}

fun A.somethingNew() {
    print("Gave A new superpowers, woot")
}

fun String.toA() : A {
    return A();
}
fun main(args: Array<String>) {
    var a = A();
    a.somethingNew()

    var s = "Meaningless initial value";
    s.toA().somethingNew();

}

As you can see any class can be extended using the form 'fun classname.newMethod". You can also extended built-in classes, like shown here with String.

 

And that brings us nicely too…

 

Classes

As we just saw, a class is declared like:

class MyClass {
    
}

 

In fact for an empty class like this, you can omit the body entirely, like:

class MyClass;

fun main(args: Array<String>) {
    var myClass = MyClass();
}

Of course, that code wont actually do anything.  As you can see from this and earlier examples there is no new operator.

 

Constructors

Kotlin has a primary constructor, which is similar to a default constructor in C++.   However no code can be contained in the constructor.  Here is an example:

class MyClass(myString:String){};

fun main(args: Array<String>) {
    var myClass = MyClass("test");
}

If you need to set initial values programmatically, you can do so in the init block, like so:

class MyClass(stringParam:String){
    var myString:String;
    val valToAppend: String = "42";
    init {
        myString = stringParam;
        myString += valToAppend;
    }

    constructor(stringParam:String, myInt:Int) : this(stringParam){
        myString += myInt.toString();
    }
};

fun main(args: Array<String>) {
    var myClass = MyClass("test");
    print(myClass.myString); // Prints test42

    var myClass2 = MyClass("test", 43);
    print(myClass2.myString); //Prints test4243 !!!!
}

This example also showed how to set a secondary constructor using the constructor keyword.  Note the call back to the default constructor in the secondary constructor.  Also note the result on myClass as per the comment, showing the order of constructor calls.

 

Inheritance

 

The base class of all classes in Kotlin is Any, which is analogous to object in Java ( and there is no equivalent in C++ ).  Inheritance looks almost exactly like Java, like so:

open class Base{};

class Derived : Base() {};

The only major difference is the parent class is marked open, otherwise it would be marked final. If the base class has a constructor, you must call it in the derived class like so:

open class Base(param:Int){};

class Derived : Base(42) {};

 

If a derived class has no primary constructor then it’s secondary constructors need to call the base class using super like so:

open class Base(param:Int){};

class Derived : Base {
    constructor(param:Int) : super(param){}
}

 

Method inheritance is done with a combination of open and override, like so:

open class Base {
    open fun baseFunc() {
        println("base");
    }
};

class Derived : Base() {
    override fun baseFunc() {
        println("derived");
    }
}

fun main(args: Array<String>) {
    var derived = Derived()
    derived.baseFunc() // prints "derived"
}

 

There are also interfaces in Kotlin, but they are probably a bit different than what you expect, as the interface can contain both abstract functions as well as implementations, like so:

interface BaseInterface {
    fun a()
    fun b() {print("b");}
};

class implementation : BaseInterface {
    override fun a() { print("a");}
}

fun main(args: Array<String>) {
    var imp = implementation()
    imp.a();
    imp.b();
}

The abstract method must be implemented in the derived class.  The only difference between an interface and abstract class is an interface does not have state.  Like Java you can only have one base class but as many interfaces as wanted.  If you name collision, it can be resolved like so:

interface A {
    fun a(){print("A")};
};
interface B {
    fun a(){print("B")};
};


class implementation : A,B {
    override fun a() {
        super<A>.a();
        super<B>.a();
    }
}

fun main(args: Array<String>) {
    var imp = implementation()
    imp.a();
}

 

Functional Programming

Kotlin also has good functional programming capabilities, consider the following example that takes a function, both anonymous or named:

fun onCallback(callback:() -> Unit) {
    return callback();
}
fun otherFunc() { print("Maybe"); }

fun main(args: Array<String>) {
    onCallback({print("Callme")});
    onCallback(::otherFunc);
}

 

An anonymous function takes the form (params) –> return.  In the above example there are no params and no return.  In Kotlin Unit is the equivalent of void in C.  The :: operator returns a callable reference.

 

 

This material should be more than enough to get started making a game in Kotlin.  I guess we shall see.  Of course, this is just a quick start, to dig deeper the entire language reference is available here.

Programming , ,

Month List

Popular Comments