How to Set up a Unity3D Master Server on Amazon EC2

Hi everyone!

I want to write a short guide on getting a Unity Master Server set up on Amazon Web Services (AWS) on an EC2 Micro Instance. Firstly, Amazon Web Services are free for the first year as long as you are using a one micro instance (5GB image). As long as you do not have unassigned Static IPs or multiple instances running, you should not incur any charges. To get more information on what defines the free-tier you can go here: Amazon AWS Free. Let’s get started!

  1. Create an Amazon AWS Account
  2. Go to the EC2 Instances page by clicking “EC2” then when that loads, in the lefthand navigation going to instances.
  3. Click the blue “Launch Instance” button
  4. Create a new Redhat Enterprise Linux Instance under the free tier in the preconfigured AMI’s
    amazon_01
  5. After you select it, it should ask about what instance type you like. This is where you skip this step and click on step 5, “Tag Instance.” You will see that an entry already exists, Name. You can go ahead and set the value for that to Unity Master Server for your convenience.
    amazon_02
  6. Go ahead and click on step 6: “Configure Security Group”. We need to configure the instance so that we can access the URL. The easiest way to do this is to open the instance on all ports on TCP and UDP. You will see that the instance is open on port 22 for SSH access, now we need to click the Add Rule button and add access via ALL TCP to anywhere on the IP and same with UDP
    amazon_03
  7. You do not need to configure anymore options. You can click the blue Review and Launch button then once you’ve review the details, go ahead and launch the Instance.
  8. You should be prompted to create a security key pair or use an existing one. This is VERY important. Do not lose the file you download when/if you create a new key pair! It is imperative that you download this .pem file to a secure location. If you don’t have it, there is no way that you will be able to access your VM.
  9. Ensure that it’s running by checking it’s status in the Instances page. If the instance state is not running, you may select it, right click, and command it to start with “Start” in the “Actions” section
  10. Now that the instance is created, we need to give it a public IP Address. Go to Elastic IPs under Networking and Security in the lefthand panel and create a new elastic IP. After you create this IP is VERY IMPORTANT that it is assigned to a RUNNING EC2 Instance. If you create an Elastic IP that is unassigned you are billed $0.005 every hour until it’s assigned. To assign it, just select it, then right click and go to “Associate Address”
  11. OK. we have a public IP for our instance, and it should be running. Good. We need to set up a way to SSH into the VM and starting messing around with the files. The best thing to do is to download PuTTY and install it
  12. Open PuTTYGen and then open your download .pem file in it (by selecting *.* All Files in the load file dialog). You can then go ahead and hit generate to create a ppk for the key file. You can put a password on it if you like. Just remember this password for later you will need to enter that in the putty console when you connect.
    putty_01
  13. Once that is complete you may open PuTTY and get your public DNS and place that in the Hostname box on the Sessions dialog.
  14. Before attempting to connect we need to navigate to the Connection section on the left and add our ppk into an SSH authorization section as you can see below:
    putty_02
  15. Now go back to the sessions page and you can save this configuration by putting a name like “Master Server” in the box below the “Saved Sessions” text and then then hitting the Save button.
  16. You should be able to connect without a snag. You will be prompted with a user account to log in with. If you type “root” it will tell you the correct user for that vm which could be something like: ec2-user.
  17. Once you’ve logged in you can go ahead and download the Unity Master Server using wget:
    wget http://unity3d.com/files/master-server/MasterServer-2.0.1f1.zip
  18. You need to unzip the file.
  19. Then build it:
    make
  20. You can then run it:
    ./MasterServer
  21. Then you’re done!

 

I hope you learned something in this tutorial and if you have any problems, just comment and I’ll do my best to help you!

Tom

Easy C# Custom XML Serialization

Hi everyone,

In the past, I spent time working with XML serialization for Grey: The Lost Technology, and I ended up writing a blog post about my findings and experience with “compressing” data to create smaller xml files, which is seen here: Grey Dev Diary: Problems of Storing Maps.

Now I want to show you a specific method that I use when writing a custom serializer for an object that needs special processing during (de)serialization. First, you would implement the ISerializable interface, and you would need to implement the following functions:

public System.Xml.Schema.XmlSchema GetSchema()
{
    return null;
}

public void ReadXml(XmlReader reader)
{
}

public void WriteXml(XmlWriter writer)
{
}

For me, reading the XML had always been the hardest part, until I came up with this:

public void ReadXml(XmlReader reader)
{
    while (reader.Read())
    {
        if (reader.IsStartElement())
        {
            switch (reader.Name)
            {
                case "Name":
                    Name = reader.ReadElementContentAsString();
                    break;
                case "ValueA" :
                    ValueA = reader.ReadElementContentAsInt();
                    break;
                case "ValueB" :
                    ValueB = reader.ReadElementContentAsInt();
                    break;
                case "DeeperObject":
                    //If object has more information and is its own class, deserialize that one.
                    reader.ReadStartElement();
                    DeepObjectInstance = (ObjectTypeClass)new XmlSerializer(typeof(ObjectTypeClass)).Deserialize(reader);
                    reader.ReadEndElement();
                    break;
                default:
                    //Do something if no case for the start element
                    break;
            }
        }
    }

    //Any sort of post processing
}

The main idea is that you loop through the start element of each entry, and then if you have a case for it, read the values. It’s super simple, and if you need to scale the object you’ve been serializing you won’t break anything.

Writing the XML is just as simple, but you don’t need to loop through anything to do it.

public void WriteXml(XmlWriter writer)
{
    writer.WriteElementString("Name", Name);
    writer.WriteElementString("ValueA", ValueA.ToString());
    writer.WriteElementString("ValueB", ValueB.ToString());

    //Don't forget you can call the WriteXML of another object and serialize it in the
    //same file as the one you're already writing to. It just means more processing later.
    //OtherObject.WriteXml(ref writer);

    writer.WriteStartElement("DeepObject");
    new XmlSerializer(DeeperObjectInstance.GetType()).Serialize(writer, DeeperObjectInstance);
    writer.WriteEndElement();
}

That’s all I have for you! If you have any questions, don’t hesitate to comment!

C++ Library Wrapping Weather.gov REST API

I’ve began creating a library that wraps the REST API offered by weather.gov. It’s not much right now, you can only input a latitude and longitude to get the highs and lows for the next 7 days, but it’s pretty neat nonetheless, and I had a pretty good time trying to get everything to work the way that I wanted it to.

Information

Why create a library for this? TO LEARN! I wanted to learn how to make a library in C++, and learn how to use the CURL library in C++, and then take these libraries and use them in a project. I don’t have a real project to use them in for now, but eventually I will use it, and add more to it.

Pro-Tips for C++ Libraries

In Visual Studio, you’ll see that there is a template for creating a Class Library in C++. This is for creating a library that uses managed code that is compiled with CLR (Common Language Runtime). This is not what you want. It’s a pain to get this set up if you plan on solely using C++ for your library. The best way to do it is to create an empty project then go from there.

Quick Tutorial:

First, create a new Empty Project, call it TestApp. Now, in the same solution, create a new project, and make it an Empty Project, this will be our library. You can call it TestDLL. The next thing we are going to do is create some classes to use in our library. Add in a header file called TestAPI.h. We will not be adding in any C++ Source Files (.cpp) because it creates issues in the namespacing. We are going to start it off really simple:

#pragma once //sorry, windows only. Too lazy to make ifndef

namespace TestAPI
{
	class Mathematics
	{
	public:

		Mathematics() {}

		int Multiply( int num1, int num2 )
		{
			return num1 * num2;
		}

	};
}

That’s all you need as far as code for the library. Now we are going to configure our TestApp project to use our library:

 

Resolve some dependencies
Add a reference to the TestDLL Library

Now, after that, you should be able to just reference your Mathematics class really easily. Now lets create the main function for our TestApp project that’s going to use our library. Go ahead and create a C++ Source File called main.cpp, and add the following code:

#include <iostream>
#include "TestAPI.h"

using namespace std;

int main()
{
	TestAPI::Mathematics math;
	int result = math.Multiply(3, 5);

	cout << "Results: " << result << endl;
	// Results: 15

	return 0;
}

That’s it!

Problems

In my implementation of the Weather REST API, I found that when I tried to use libcurl in my project, I had to include it in both my TestApp and my TestDLL. Other than that, everything went smoothly.

 

Download: C++ Weather REST API Wrapper

C++ Event System using Delegates

Recently I’ve been working on an Event System in C++. You might be reading that right now and wonder why that small sentence makes it sound like a true endeavor. Well, it was. As many of you may know I’m a student at Champlain College, and in one of my classes, each of the students are tasked to use an event system or a messaging system in their game. The teacher provided us with one, and it’s really great and all, but I couldn’t help but feeling restricted, especially after having used C# for so long where the code is so forgiving, and easy.

I did some research and it turns out that a lot of event systems in C++ are organized in such a way that when you want to do events you must:

  • Create an EventManager class (nothing wrong with this)
  • Create an EventListener class (for setting up events)
  • Create and Event base class
  • Be restricted to use only one function to handle your events
  • Create a huge enum holding a key for each of your events (Can hash it for speed)

I saw those and my heart dropped. I immediately thought that is way to restrictive, there must be an easier way to get events to work. And so the researching began.

Continue reading “C++ Event System using Delegates”

Understanding C# 2D XNA HLSL – Part 2

Read the first part here

I know a lot of you loved the first part of this breakdown, and now I’m back to continue the explaining!

Breakdown of Effect Parameter

Continuing from the end of the first part: What the effect parameter does here is that it takes our effect and then applies it to all of the textures that you draw then on. This is effective for coloration effects such as black and white, or inverting colors, but if you have an effect that works based on certain coordinates or is constricted similarly, then you need to be  very careful! To avoid issues like that, there is a rather simple solution when you want to apply an aforementioned size/position constricted effect to the screen.

Further Implementation

Adjusting the Effect parameter of the SpriteBatch.Begin() function is not the only way to use HLSL effects in your projects. Another method that you can do is draw all of your textures to one RenderTarget2D (Think of this as an empty texture, or a blank canvas). After you’ve drawn all your textures to that, it’s really easy to apply your effect to “the screen”.

RenderTarget2D MainTexture;

//In the Initialize function set up the rendertarget:
PresentationParameters pp = GraphicsDevice.PresentationParameters;
MainTexture = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight);

        //Then create a function to draw your game textures to, and draw it all up       

        private void DrawGame(GameTime gameTime)
        {
            GraphicsDevice.SetRenderTarget(MainTexture);
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            spriteBatch.Draw(bg, GraphicsDevice.Viewport.Bounds, Color.White);
            spriteBatch.Draw(player, new Vector2(200, 300), new Rectangle(0, 0, 128, 128), Color.White);

            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(null);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            DrawGame(gameTime);

            GraphicsDevice.Clear(Color.Black);

            // Use Immediate mode and our effect to draw the scene again, using our pixel shader.
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);

            mainEffect.CurrentTechnique.Passes[0].Apply(); // for every pass that you have you can apply
                                                           // all them to the texture if you want.
            spriteBatch.Draw(MainTexture, Vector2.Zero, Color.White);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }

Alternatively, you can use the effect parameter in the spriteBatch.Begin() function when drawing MainTexture, because remember: The effect is applied to the texture in every Draw() function call. If you only have to draw one texture and want all the passes applied when drawn, then you can use the Effect parameter.

Why do this?

In a project I was working on I really wanted to have an INFINITE amount of 2D lights in my game, and after countless attempts at getting a high number lights (higher than 5) from all HLSL effects, I found that by drawing a my lights to a texture, and then my game to another, I could then use an HLSL effect to blend my lights together.

 

I hope this helped.

-Tom

Using Git with a Subversion Repository

Using git bash with a subversion repository is very easy when you know how to use it!

First, you’ll want to head over to the Git Website and get the latest release of the git application (we’ll be using git bash)

NOTE: when you install, consider checking “Git Bash Here” as a context menu option:

After it’s installed, go ahead and open git bash and cd to a directory where you want to download the repo to, or if you chose to install that context menu option, navigate to your folder in explorer (or finder) and right click on it then “Git Bash here”.

After that go ahead and run the “git svn clone” command on your repo, example:

git svn clone https://svn.webhost.com/svn/sp12egp31001

Alternatively, you can clone a subdirectory of the svn repository by simply writing the directory name at the end of the repo address. This is particularly useful when you’re working on a large project and don’t want to download all the files on the server.

git svn clone https://svn.webhost.com/svn/sp12egp31001/subdirectory

After you run the command you’ll be prompted for authentication, go ahead and fill that out and your repository will be downloaded onto your machine.

From there you’ll be able to modify the code, or whatever it is as you would regularly, then when you are ready to push changes back to the server, all you have to do is add these changes, and get them ready for commiting.

To start, go ahead and run this command:

git status

That should list out all the files you’ve modified, added, or deleted.

To track these changes run the add command:

git add .

The “.” at the signifies that you would like to track all the changes that were made. Another thing to note is that if you deleted a lot of files you would want to run the add command with another optional parameter:

git add -u .

This should track all the changes made, regardless of deleted, added, or changed.

Once you are satisfied you will need to make a commit to your local git repository by running the git command:

git commit -m "Your message goes here!"

Something to note about the commit command: You don’t have to use the -m parameter, it’s just that it’s much easier to do this, rather than being taken to a command line text editor to write a message.

Once you’ve commited your changes to your local git repository, you’re ready to push them to online subversion repository!

When pushing your git changes back to the online repository, you’ll want to run the subversion rebase command. What this command does is download all the changed files from the repository. You won’t be able to add your changes to the online repository if you don’t do this:

git svn rebase

After you’ve run that command, the only thing left is to commit those changes to your online svn repository:

git svn dcommit

And, that’s it! You’ve successfully learned to use the git bash with a subversion repository!

One more thing to note if you work on multiple machines. If you’ve cloned your repository on multiple machines you’ll need to run the rebase command:

git svn rebase

to download any changes from the server that you’ve commited from your other machine BEFORE you start working on your code on your current machine.

 

Now you’re ready to get working with git on your subversion repositories!

How to make a platform engine in QuickBox2D – Part 2

Read Part One of the article, it covers some of the basics, and explains a few things.

With the release of QuickBox2D 1.0 I figure I should update my game engine articles. I won’t actually update the first one, but instead I will provide updated versions here, with links to download the files (source).

One of the best things about the new QuickBox2D is the addition of QuickContacts.

var contacts:QuickContacts = sim.addContactListener();
contacts.addEventListener(QuickContacts.ADD, onAdd);
contacts.addEventListener(QuickContacts.PERSIST, onPersist);
contacts.addEventListener(QuickContacts.REMOVE, onRemove);

function onAdd(evt:Event):void{
	if(contacts.currentPoint.shape1 == main.shape || contacts.currentPoint.shape2 == main.shape){
		if(contacts.currentPoint.normal.y >= -1 && contacts.currentPoint.normal.y < 0){
			grounded = true;
		}
	}
}
function onPersist(evt:Event):void{
	if(contacts.currentPoint.shape1 == main.shape || contacts.currentPoint.shape2 == main.shape){
		if(contacts.currentPoint.normal.y >= -1 && contacts.currentPoint.normal.y < 0){
			grounded = true;
		}
	}
}
function onRemove(evt:Event):void{
	grounded = false;
}

QuickContacts is a class that uses the b2ContactListener class that comes stock with Box2D. If you remember, we actually modified that class so we could detect if we were touching things (this way our character could jump). With this addition, we won’t actually need to modify that, AND we won’t have to make that global class. We can just do all the code on the timeline.

On the first part of the series, someone commented saying that if you add an object that does NOT have a zero density, that game would get pretty messed up. Well, he was right. That was because in the b2ContactListener, when we checked to see if we were grounded, the class was actually checking every single object against each other. Meaning that any object with zero density was being checked, and since it was sitting on the boxes right, it would set our grounded variable to true.

One more addition to the platform engine is the ability to make platforms that you can jump through the bottom, this isn’t really new feature, but it’s pretty nice. To be honest, the code that actually makes it so you can jump through the bottom of platforms was originally taken from a snippet on Actionsnippet.com, the creator of QB2D. So, thanks Zevan.

I also made numerous fixes to the code from the last version. One of these fixes include changing direct modification of gravity, to setting the main character object to sleep. I would change the gravity to 0 when the main character was standing on a platform, specifically on a slope, so that the character wouldn’t slide down. However, it turns out to be a better plan to set the object to sleep. Why? Well, if you push one of those non-zero density spheres off a platform, it won’t actually fall with the old system, whereas the new system fixes that.

Test the QB2D Engine

Download the source

What should I add to the new version? Suggestions?

Tom

How to make a platform engine in QuickBox2D

Check out part 2 RIGHT HERE

What’s up? Ready to learn a little something about QuickBox2D? Wait, you don’t know what QuickBox2D is? Well, QuickBox2D is a simpler way of using Box2D — A physics library originally written in C++ and ported to many other platforms including AS3 — and is much cleaner and easier to use than the straight Box2D library. Anyways, QuickBox2D was made by Zevan Rosser, who is a teacher at the School of Visual Arts in NYC. You can see a lot of great examples of how to use QuickBox2D at his blog, ActionSnippet.

Let’s get started here. First thing you need to do is get the latest version of Box2D and QuickBox2D at these links:
Box2DFlashAS3
QuickBox2D
And Save them in a new folder called ‘PhysicsPlatformer’.

Now open Flash CS3/4 and create a new Flash AS3 Document File. Go back to the File menu button and add another file, this time we are going to add an Actionscript Document (.as file). Save the .fla as game.fla, and save the .as file as global.as.

The global.as file is going to contain one variable (kind of a waste, I know, but it can be useful when you expand your engine a little bit more, like for implementing wall-jumping, it could be useful). Since global.as is the smallest, we’ll start with that. This is the code that should be in your global.as class file:

package {

	public class global {

		public static var grounded:Boolean = false;

		public function global():void {

		}
	}
}

The important thing to notice here is ‘static’ on line 5. When you use the word static in the definition of a variable, it means that you can access the variable by stating the class name then the variable name without instantiating the class. This is really great because when we need to access our boolean, grounded, all we type is “global.grounded”.

The next part is probably the hardest part to do, actually making the engine. When I was in works of creating the engine, I had some real trouble getting the main character (a ball in our case) to stay still on a slope, and i came up with an ingenious way of fixing this problem, and you’ll see in the tutorial here how I did it.

Lets start by setting up our QuickBox2D simulation:

import com.actionsnippet.qbox.*;

var sim:QuickBox2D = new QuickBox2D(this);
sim.setDefault({lineAlpha:0, fillColor:0x333333});
sim.createStageWalls();

sim.start();

If you paste this in the timeline of game.fla and test it, you should see a dark grey box surrounding your stage, If not, then look through your code checking for typos or something because we have a long way to go.

Next we can add our character, a simple ball will do:

import com.actionsnippet.qbox.*;

var sim:QuickBox2D = new QuickBox2D(this);
sim.setDefault({lineAlpha:0, fillColor:0x333333});
sim.createStageWalls();

var main:QuickObject = sim.addCircle({x:3, y:3, restitution:0, lineAlpha:1, fillColor:0x888888, allowSleep:false, fixedRotation:true});

sim.start();

There is obviously only one addition to this, it’s on line 7. First we make a new variable that’s typcasted as a QuickObject, then we set it equal to the results of the addCircle function. You’ll notice in the function that there is one argument, and it’s an object with a lot of stuff in it. I’ll point out the most important parts of those parameters. allowSleeping: false. If our object could ‘sleep’ then we would not be able to move it unless we wake it up, I suppose it’s fine to leave this as true (by default) and then whenever you want to move the character wake it up, but it’s not making the hugest impact on the game right now, so don’t worry about it. And, fixedRotation: true. Let’s say we are controlling our circle and we get to a slope, and we are trucking up the slope, but then we have to stop for a second because a friend is calling or something, when we let go of our keys, the ball will just start rolling down the slope, and we can’t have that.

So, great, we have a ball. How do we move it? We move the ball by adjusting it’s linear velocity. But first we have to set up a few functions to handle our keyboard input and such:

import com.actionsnippet.qbox.*;
import Box2D.Common.Math.*

var sim:QuickBox2D = new QuickBox2D(this);
sim.setDefault({lineAlpha:0, fillColor:0x333333});
sim.createStageWalls();

var main:QuickObject = sim.addCircle({x:3, y:3, restitution:0, lineAlpha:1, fillColor:0x888888, allowSleep:false, fixedRotation:true});

sim.start();

stage.addEventListener(Event.ENTER_FRAME, loop);
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeysUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown);

var keyArray:Array = new Array();
var speed:int = 5;
for (var i=0; i<222; i++) {
	keyArray.push(false);
}

function loop(e:Event):void {
	if(keyisdown(39)){
		main.body.SetLinearVelocity(new b2Vec2(speed, main.body.GetLinearVelocity().y));
	}
	if(keyisdown(37)){
		main.body.SetLinearVelocity(new b2Vec2(-speed, main.body.GetLinearVelocity().y));
	}
}

function checkKeysDown(event:KeyboardEvent):void {
	keyArray[event.keyCode]=true;
}
function checkKeysUp(event:KeyboardEvent):void {
	keyArray[event.keyCode]=false;
}
function keyisdown(X:Number):Boolean {
	return keyArray[X];
}

Continue reading “How to make a platform engine in QuickBox2D”

Flash Tutorial #2 – The Basics of Actionscript 3.0

Hey there. I just finished up another tutorial about the basics of Actionscript 3.0 (AS3). The video is about 36 minutes long and covers a wide range of topics, including: variables, conditionals, operators, functions, events, and other general basic ideas in Actionscript 3.0 (and many other languages). By the way, I talk about all those pretty much in that order, slipping in little bits of data about other things as I progress through the video.

I also finally got around to submitting SpaceFlyer online, so the project page is now updated with a playable link to the game, or you can click here. I’ll be straight about this game, it isn’t really pretty, and it doesn’t exactly have a great story line, BUT there are some sweet mechanics!

Hope you enjoy them both
-Tom

Video Tutorial #1 – The Basics of Flash CS4

Flash LogoThe Basics of Flash

In this awesome tutorial, I cover the basics of Flash  CS4, I mean, the BASICS. This is probably as simple as it gets for you,  so, don’t count on other tutorials being this simple.

 

SO, this is the future of my website. I will probably be doing tutorials for… the rest of my life. I feel like I made a real connection here.

Nah. But I will be making more tutorials in the future that will cover Actionscript 3.0 ideas in Adobe Flash as well as other programming languages, such as C# (for XNA), and C++.