10. June 2015

 

This tutorial is a quick guide on getting MonoGame up and running on Windows OS.  The process is incredibly straight forward, with two options on how to proceed.

 

First you are going to need a development environment, of which two options are available.  Xamarin’s Xamarin Studio or Microsoft’s Visual Studio.  If you wish to go the Xamarin Studio route, be sure to check the MacOS guide, as the process will be virtually identical.  The rest of this tutorial assumes that you chose to install Visual Studio, the industry standard IDE for Windows development which is now thankfully available for free.

 

So first things first, download and install Visual Studio 2013 Community.  Be sure that you select Community and not one of the 90 trial editions.  The community install is a complete and full functioning version of Visual Studio, but with some limitations on the size of your company.

 

As of time of writing, this is the version you want.

image

 

If you want to talk a walk on the wild side, the release candidate of Visual Studio 2015 will also work.  Of course, it’s a release candidate… so buyer beware. 

Installing either with the minimal recommendations or better will get you all that you need installed.

 

Install using the Installer

 

By far the easiest option, simply download and run the installer available here.  Be sure to shut down Visual Studio before installing.

Click Next, then agree to the EULA… after you read it and submit it to your lawyer for approval of course…

Next you will be prompted for the features you want installed.  The defaults are pretty solid, click Install:

image

 

 

Install using NuGet

Visual Studio integrates a package manager called NuGet.  This offers a few (potential) benefits over using the library’s standalone installer.

  • dependency resolution.  If it depends on other libraries, NuGet can handle those dependencies
  • package updating abilities.  Keep yourself up to date easier

Actually, that’s about it.  Basically if you want to be kept up to date on updates, this is the route to go.  The install process is certainly more complicated though, at least initially.

First of course you need the NuGet package manager installed.  It’s getting more and more common in use, so you will probably have it installed or need it installed shortly.   It is available as a Visual Studio extension or command line utility.

To install with NuGet, Launch Visual Studio, on first run you may have to make some configuration choices, don’t worry, most of these can be revisited later on.  Once configured, select the menu Tools->NuGet Package Manager->Package Manager Console:

image

Now you simply install the packages you want.  Unlike the installer you download the various packages independently.   The list of packages are available here.  Assuming you are going to develop initially on Windows, you probably want to start with the DirectX Windows version.  To install that in the Package Manager Console type:

Install-Package MonoGame.Framework.WindowsDX

This will download and install all the required files and dependencies.  For more details on the MonoGame NuGet packages please read this post on StackOverflow by the maintainer.

 

Your First Project

Now that you’ve got MonoGame installed let’s create our first project.  If not already done, load up Visual Studio.

 

Select File->New Project

image

 

In the resulting dialog, on the left hand side under installed templates, select Visual C#->MonoGame, then on the right hand side select MonoGame Windows Project, pick a location, a project name, if you want source control, then click OK.

image

 

As you can see, MonoGame ships out of the box with templates for a number of different targets and a few above may require a bit of an explanation.  The MonoGame Windows Project targets Windows desktop using Direct X for the backend.  The OpenGL project is another Windows target, but instead using OpenGL as the backend.  As DirectX is Windows, XBox and WinPhone only, you may find using the GL backend the most consistent if targeting Mac, Linux, Android and/or iOS, as those all use OpenGL on the back end.  A Windows 8.1 Universal project is an application that supports both Win 8 desktop and mobile targets with one code base, and if I am honest, with the announcement of Windows 10, is probably a complete dead end.

 

Ideally you will write most of your code as libraries, with only the platform specific portions in their own corresponding project file.  We will look at this process closer down the road.  For now we will KISS (Keep It Simple Stupid) and just target the platform we are developing on.

 

Once you click OK, the following simple project will be created:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Game1
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to 
        before starting to run.
        /// This is where it can query for any required services and 
        load any non-graphic
        /// related content.  Calling base.Initialize will enumerate 
        through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place 
        to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw 
            textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the 
        place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing 
        audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing 
                        values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == 
                ButtonState.Pressed || Keyboard.GetState().IsKeyDown(
                Keys.Escape))
                Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <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)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}

 

Don’t concern yourself overly with the code, we will explain it all shortly.  We just want to make sure that your MonoGame install is up and running.  To run your game hit F5 or press:

image

Assuming all went well, you should see a window drawn in CornFlower blue:

image

Congratulations, you’ve just created your first ever MonoGame application!

 

Let’s talk briefly about the Content Pipeline.  This is the way you get content into your MonoGame application.  If you look in the Solution Explorer, you will see a file named Content.mgcb.

image

 

Double click it, and the MonoGame Content Pipeline tool will open:

image

 

Let’s quickly add a texture to our project.  Select Edit->Add->Existing Item, navigate to an existing image file somewhere on your computer.

image

 

Next you will be prompted for how you want the file to be added, copied or linked, I chose copy to break the connection with the source image.  This means updates to the original image will not be propagated, nor will deleting it have any effect.

image

 

The image will be added to your content bundle, as as you can see with it selected, there are a number of properties exposed for how the image should be processed when building content:

image

There are several Import processors available for various different file types:

image

 

Each one exposes different parameters you can modify.  For images some of the key properties exposed are the option to automatically resize the image to a power of 2 dimension, to change the texture compression settings (TextureFormat) or setting the color key value used for transparencies.

Now select the Content root node and you will see the property details have changed:

image

The key setting here is Platform.  Each different platform can have slightly different requirements and the Content Pipeline takes care of that for you.  In this case we already have Windows set for the pipeline, so there is nothing that needs to be changed.

 

Now Build your content using the Buld->Build menu option, or by hitting F6.

image

 

Now back in Visual Studio, confirm that the build action on your Content.mgcb file is set correctly.  Right click the file and select Properties:

image

 

Make sure that Build Action is set to MonoGameContentReference.

image

 

This will enable you to use the content as if it was installed locally, making switching between platform versions trivial.

 

Now actually using content in code is as simple as:

 protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            var myImage = this.Content.Load<Texture2D>("SBO6h0Gk");
        }

Don't worry, we will cover this process in more detail later. Just note that the file extension is not used.

Behind the scenes, you may notice that the Content Pipeline tool created the following xnb file in the /bin/Windows subdirectory of Content:

image

Programming , ,

9. June 2015

 

This isn’t actually a topic I intended to cover, I was actually working on demos for a Sound tutorial and needed a simple UI.  I started using UMG to knock up a simple HUD, then realized the UI layer itself probably required a tutorial of it’s own!  So here we are, we are going to quickly explore the widgets of UMG to create a simple UI.  As always there is an HD video version of this tutorial.

First we should touch upon some of the technologies available in Unreal Engine, as it can get a bit confusing.  There are two different technologies for UI in Unreal,  Slate and Unreal Motion Graphics(UMG).

Slate

Slate is a UI framework built on top of Unreal Engine.  Much of the Unreal Engine editor itself was built using Slate.  Slate fills the same role as UI solutions such as Scaleform would often perform, although Slate is a bit lower level than that.  Slate uses a declaration language that is a subset of C++.

Unreal Motion Graphics

UMG is a more recent development and is in-fact built over top of Slate.  It is a collection of UI Widgets ( buttons, labels, panels, etc ) exposed using Blueprints.  On top it includes visual designer for composing UIs.  UMG is the preferred technology for creating in game UIs.  In simple terms, it’s a UI layer that enabled you to work visually and using blueprints.

 

Creating a Widget Blueprint

 

To start creating your own UI, create a Widget Blueprint via Add New->User Interface->Widget Blueprint

image

 

I renamed it MyUI, somewhat unimaginatively.

image

Double click the Widget Blueprint to bring up the Designer:

image

 

The Palette has a collection of UI Widgets you can assemble in your own widget.  You may notice in the Hierarchy panel, we start with a Canvas Panel as our root element.

 

Creating a UI is as simple as drag and drop, like so:

gif

 

As you can see, the properties for each widget can be set on the right hand side.  You can then wire events up to the UI component by clicking the + icon to the right of the Event you want to respond to.

image

This will create a new event in the UI widget event graph. 

image

 

We will do a simple Print String on button click, like so:

image

 

Now that we have a UI we need to display it.  To do so, in the Level Blueprint, add the following:

image

When the level loads, we create a new MyUI widget, and add it to the viewport.  The other bit of this blueprint gets the character controller and sets the mouse cursor visible.

Now when you run it, you should see:

image

 

The following function I wired up to a On key handler for toggling the visibility of the UI.  UI layer is a variable I set from the return type of Create MyUI Widget from the blueprint above.

image

 

Of course, this only brushes the very surface of what you can do with UMG, you can do very flash like timeline based animations and create much more involved UIs, but that goes beyond the scope of what I intend to cover today.

 

The Video

Programming , ,

9. June 2015

 

Unity 5.1 was released today.   Unity 5.1 new features are:

 

UNITY 5.1

Unity 5.1 features a highly-optimized rendering pipeline for VR and AR devices to help you achieve exceptional frame rates, as well as new networking APIs, and our Multiplayer Service with Matchmaker and Relay servers (in preview) for easy multiplatform networked games.

We’ve worked hard to deliver a stable release, beating down over 170 bugs and introducing some significant refactoring including a new unified OpenGL rendering backend.

Get the full release rundown below!

RELEASE NOTES

FEATURES

  • New multiplayer networking feature introduced, see the manual and UnityEngine.Networking namespace in the script reference for details. This includes low level API (transport layer) and a higher level API with many features to help implement multiplayer functionality in games. Cloud based relay service can be used to get past NAT restrictions, and a simple matchmaking service can be used for game/host discovery. To configure the services go to https://multiplayer.unity3d.com. The current RakNet based multiplayer system will be deprecated but still functional in this release.
  • New network components and NetworkBehaviour base class for network aware scripts:

description

  • New NetworkManager to control and configure multiplayer games:

description

  • Added integrated support for Oculus Rift in Editor and Standalone Players, see the Manual and UnityEngine.VR namespace script reference for details Once Virtual Reality is enabled in Player Settings, pressing play in the editor will show your game view on the Rift. It is recommended to "Maximize on Play" the game view and run the Oculus Rift in Extended mode in order to achieve the smoothest rendering. Be sure to remove any previous Oculus plugins and assets from your project, or update to the latest version that supports 5.1.
    • VR optimization: Render shadows only once and share between eyes.
    • VR optimization: Cull once for both eyes.
    • Support for Oculus 0.6.0-beta runtime

description

  • New HDR Color Picker
    • Improves the Standard shader workflow for changing the emission color property.
    • The emission color can now be animated from the animation window.
    • Using scripting API to change emission will now be reflected in the shader gui.
    • Color Presets now also support HDR colors. Saving a HDR color will overlay a lowercase 'h' on the preset swatch.
    • Color property fields can now be customized with the ColorUsageAttribute (show/hide alpha value, is HDR)
    • Added Hex color field

description

  • Graphics: Crunch texture compression format on platforms which support DXT. This is a lossy compression that is both small on disk/download and compressed (DXT1/DXT5) for the GPU.

description

  • Graphics: Experimental support for OpenGL 4.5 and ES 3.1 on Windows. Use -force-glcore, -force-gles(20|30|31|31aep) arguments to enable. This enables testing OpenGL ES 3.1 features on desktop. Note: no GL4 support on Mac or Linux yet.
    • Graphics: OpenGL ES 3.1 support on Android
    • New graphics levels (OpenGL ES 3.1, OpenGL ES 3.1 + AEP)
    • Compute shaders
    • Geometry shaders
    • Tessellation shaders
    • Advanced blend modes
    • Note: OpenGL ES 3.0/3.1 uses a new shader compiler backend; see Changes below.
  • New runtime assertion library under UnityEngine.Assertions namespace. The library provides a set of methods for setting assertions in your code.
    • The method calls will be conditionally compiled out from non-developer’s builds.
    • The conditional compilation is controlled by UNITY_ASSERTION define.
    • Defines DEBUG and TRACE are now also defined for non-developer’s builds.
    • A wrapping library providing extension methods is also available under UnityEngine.Assertions.Must namespace.
  • Unity Analytics: new, built-in Analytics functionality introduced (currently in “Preview”), under the UnityEngine.Analytics namespace.
    • Basic Integration can be completed by inserting a unique ProjectId into “Cloud Project Id” in PlayerSettings.

description

  • The ProjectId is a unique identifier that links your Editor project with the data on your Analytics dashboard, and is generated during the Basic Integration process.
    • Go to http://analytics.unity3d.com to get started with Basic Integration, as well as access the relevant documentation and integration instructions.
    • Additionally, the library provides methods to track Monetization, Custom Events, and User Attributes (otherwise known as Advanced Integration options).

description

  • Note: 4.x and 5.0 Editor users can still use Analytics by integrating the downloadable SDK package. For 5.1 users, adding the plug-in should not result in errors, nor will it result in duplicate data, but we still advise that you remove the old plug-in assets.
  • Home Window Login integration. You can now login or work offline using the home window or command-line arguments.

 

You can download Unity right here.

Programming

7. June 2015

 

In the previous tutorial we covered Sprite Animation, although to be honest it was more about creating animation ready sprites.  The actual way we performed animation wasn’t ideal.  Fortunately we are about to cover a way that is very much ideal… and capable of a great deal more than just animating sprites!

 

As always, there is an HD video of the this tutorial available right here or embedded below.  It’s important to have followed the previous tutorial, as we will be building directly on top of it.

 

Keyframes Explained

 

Before we get to far into this tutorial I think it’s pretty critical to cover a key concept in animation, keyframing.  Essentially you animate by setting a number of “key” frames in the animations timeline, then let the computer take care of the rest.  You can set a keyframe on just about any property available in Godot as we will soon see.  For example you can create a key on the position value of a sprite.  Then advance the timeline, set another key at a different position.  The computer will then interpolate the position over time between those two keys.  This interpolation between key frames is often referred to as a “tweening” as in “inbetween”.  Don’t worry, it will make a lot more sense when we jump in shortly.

 

AnimationPlayer

 

In the previous tutorial, we created a simple animation using code to increment the current frame at a fixed play rate.  Now we are going to accomplish the same thing using the built in animation system in Godot. 

Start by opening up the previous project and remove the code from our AnimatedSprite.  Now add a AnimationPlayer node under the root of your scene, like so:

image

 

With the AnimationPlayer selected, you will notice a new editor across the bottom of the 2D window:

image

 

This is your animation timeline control.  Let’s create a new animation named “walkcycle”

Click the New Animation icon

image

 

Name your animation and click Ok

image

 

Click the Edit icon

image

 

This will extend the animation options even more.

image

 

First let’s set the duration of our animation to 2 seconds:

image

 

You can then adjust the resolution of the animation timeline using the Zoom slider:

image

 

Here we’ve zoomed in slightly to show just over 2 seconds:

image

 

Now that we are in edit mode with our AnimationPlayer selected, in the 2D view, you will notice there are new options available across the top

image

 

This is a quick way to set keys for a nodes positioning information.  You can toggle on or off whether the key will store location, rotation and/or scale data.  You set a key by pressing the Key icon.  The first time you press the key icon you will be prompted if you want to create a new track of animation.

Select your sprite, make sure the timeline is at 0 and create a key. Advance the timeline to 2secconds, then move the sprite to the right slighly, then hit the key icon again to create another key frame.

g1

 

Press the play icon in the AnimationPlayer to see the animation you just created:

g2

 

Well that’s certainly movement, but pretty crap as far as animations go eh?  How about we add some frame animation to our mix.  Here is where you start to see the power of animation in Godot.

 

With the AnimationPlayer selected, rewind the timeline back to zero, make sure you select your AnimatedSprite, then in the Details panel you will notice that all of the properties have a little key beside them:

image

 

This is because you can keyframe just about any value in Godot.  We are now going to do it with the Frame value.  This is the value we programmatically increased to create our animation before.  Now we will instead do it using keyframes.  With the timeline at 0, set Frame to 0 then click the Key icon to it’s right.  Click Create when it prompts you if you wish to create a new track.  Then move the timeline to the end, increase Frame to the final frame (21 in my case), then click the Key again.  This will create a new track of animation:

image

 

You can see the different track names across the left.  The blue dots represent each key frame in the animation.  There is one final change we have to make.  Drop down the icon to the right of the animation track and change the type to Continuous, like so:

image

 

Now when you press play, you should see:

g3

 

Playing Your Animation

 

While your animation appears properly if you press Play in the AnimationPlayer interface, if you press Play on your game, nothing happens.  Why is this?

 

Well simply put, you need to start your animation.  There are two approaches to starting an animation.

 

Play Animation Automatically

You can set the animation to play automatically.  This means when the animation player is created it will automatically start the selected animation.  You can toggle if an animation will play automatically using this icon in the Animation Player controls.

image

 

Play an Animation Using Code

Of course, AnimationPlayer also has a programmatic interface.  The following code can be used from the scene root to play an animation:

extends Node

func _ready():
   get_node("AnimationPlayer").play("walkcycle")

 

Scripting the AnimationPlayer

 

Say you want to add a bit of logic to your keyframed animation…  with AnimationPlayer you have a couple options we can explore.

 

First there are the events that are built into the AnimationPlayer itself:

image

For simple actions like running a script when an animation changes or ends, using AnimationPlayer connections should be more than enough.

 

What about if you wanted to execute some code as part of your animation sequence?  Well that is possible too.  In your Animation editor window, click the Tracks button to add a new animation track:

image

 

Select Add Call Func Track:

image

 

Another track will appear in your animation.  Click the green + to add a new keyframe.

image

 

Now left click and drag the new key to about the halfway (1 second) mark.  Switch to edit mode by clicking the pen over a dot icon, then click your keyframe to edit it.  In the name field enter halfway.  This is the name of the method we are going to call:

g4

 

Add a method to your root scene named halfway:

extends Node

func _ready():
   get_node("AnimationPlayer").play("walkcycle")

func halfway():
   print("Halfway there")

 

When the keyframe is hit, the halfway method will be called.  Adding more function calls is as simple as adding more keys, or complete Call Func tracks.  As you may have noticed in the video above, you have the ability to pass parameters to the called function:

image

 

Finally, you can also access animations, tracks and even keys directly using code.  The following example changes the destination of our pos track.  This script was attached to the AnimationPlayer object:

extends AnimationPlayer


func _ready():
   var animation = self.get_animation("walkcycle")
   animation.track_set_key_value(animation.find_track("AnimatedSprite:transform/pos"),1,Vector2(400,400))

 

Now when you run the code you should see:

g5

 

The Video

Programming , , ,

3. June 2015

 

In this tutorial we are going to look at Sprite Animation in Godot Engine, specifically on using the AnimatedSprite class.  We are going to import and create a node that has multiple frames of animation, then look at some code to flip between frames.  In the immediately following tutorial, we will then cover a much better animation method using AnimationPlayer.

 

As always, there is an HD Video version of this tutorial available right here or embedded below.

 

Alright, let’s just right in with AnimatedSprite.

 

Sprite Animation

AnimatedSprite is a handy Node2D derived class that enables you to have a node with multiple SpriteFrames.  In plain English, this class enables us to have a sprite with multiple frames of animation. 

 

Speaking of frames of animation, this is the sequence of png images I am going to use for this example:

image

 

You can download the zip file containing these images here, or of course you can use whatever images you want.

 

Now we simply want to import them to our using the standard Import->2D Texture method.  Be aware, you can multi select in the Importer, so you can import the entire sequence in one go.  Assuming you’ve done it right, your FileSystem should look somewhat like:

image

 

Now add an AnimatedSprite node to your scene like so:

image

 

Now we add the frames to our AnimatedSprite by selecting Frame->New SpriteFrames

image

 

Now drop it down again and select Edit:

image

 

The 2D editor will now be replaced with the SpriteFrames editor.  Click the open icon:

image

 

Shift select all of the sprite frames and select OK

image

 

All of your sprites should now appear in the editor:

image

 

Now let’s add some code to flip through the frames of our AnimatedSprite.  Attach a script to the AnimatedSprite node, then use the following code:


extends AnimatedSprite

var tempElapsed = 0

func _ready():
   set_process(true)
   
func _process(delta):
   tempElapsed = tempElapsed + delta
   
   if(tempElapsed > 0.1):
      if(get_frame() == self.get_sprite_frames().get_frame_count()-1):
         set_frame(0)
      else:
         self.set_frame(get_frame() + 1)
      
      tempElapsed = 0
   
   print(str(get_frame() + 1))

The logic is pretty simple.  In our process tick we increment a variable tempElapsed, until 1/10th of a second has elapsed, at which point we move on to the next frame.  If we are at the last frame of our available animation, we then go back to the very first frame.

 

When you run it, you should see:

walking

 

Pretty cool!  However, instead of advancing the frame using code there is a much better approach to animation, that we will see in the next tutorial.  Stay tuned.

 

The Video

Programming , , ,

Month List

DisqusCommentsSummary