Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
9. October 2015

 

In this part of the SFML we will look at creating our first basic SFML application.  At the heart of every SFML application is the RenderWindow which provides both a way to draw things on screen and receive input events from the user.

 

As always, there is an HD video of this tutorial here.

 

At the heart of every non-trivial game is the game loop.  In some game engines it’s hidden away from you inside the engine, but it is always there somewhere.  In SFML it is your responsibility to implement, which is what we will do today.  A game loop is a pretty simple concept… it’s a loop that runs over and over until your game is completed.  Each pass through the loop the screen is cleared and new graphics are drawn (this is referred to as a frame, so when you hear Frames Per Second, this is what is being referred to).  There are several other tasks a game is responsible for handling… input and physics to name just two.

 

Let’s start off with a very simple application:

#include "SFML/Graphics.hpp"

int main(int argc, char ** argv) {
  sf::RenderWindow renderWindow(sf::VideoMode(640, 480), "SFML Demo");

  while (true) {
    renderWindow.clear();
    renderWindow.display();
  }

}

This represents about the simplest meaningful SFML application you can create.  We create a new RenderWindow, passing in both its dimensions and title.  Then we simply loop forever and each pass through the loop we clear the window then draw it again with a call to display().

 

When you run this code you will get a black 640x480 window on screen, however if you attempt to move or close this window you will quickly notice something is wrong.  It doesn’t respond to any of your actions.  In fact, if you lose focus (click on a different window) you can’t even get it to focus again!  This is because we aren’t responding to any events.  Let’s switch things up a bit so that are window is a tad more responsive.  Instead of simply looping forever, we will create a slightly more intelligent game loop.

  sf::Event event;
  while(renderWindow.isOpen()){
    // Check for all the events that occured since the last frame.
    while (renderWindow.pollEvent(event)){
      //Handle events here
      if (event.type == sf::Event::EventType::Closed)
        renderWindow.close();
    }
  
    renderWindow.clear();
    renderWindow.display();
  }

Now your window properly responds to events, it can be moved around and most importantly, it can be closed.  Let’s take a quick look at what we’ve done here.

 

First off, instead of looping forever, we instead loop until our RenderWindow is closed.  Next inside this loop we’ve implemented another while loop that calls pollEvent.  pollEvent checks for all of the events that occurred since the last time pollEvent was called.  It is called inside a while loop because it is possible that multiple events occurred since the last pass through the outer loop.  pollEvent() will return false when no more events exist.  Events exist for things such as mouse and keyboard actions or the window being resized.  In this particular case we are checking to see if the EventType is Closed, which means a close request has occured.  In the event that one does we call renderWindow.close() which will result in the next check of isOpen() to return false, thus ending our game.

 

We will cover events in more detail later, but for an idea of what EventTypes exist, click here.  There are two very important things to realize in this game loop.  Notice that the sf::Event is declared outside of the loop?  This code is going to be called ALOT.  Never put variable allocations, even stack based ones like this, inside a high frequency loop if it can be helped.  Second, notice how the clear() and display() calls are outside of the inner pollEvent() loop?  This is also important, as otherwise your screen with only update when an event occurs!

 

There is one final important concept to cover before we move on to the next tutorial… time.  It is quite common for a game engine to provide the elapsed time since the last frame.  This value is very useful to your entire game as we will see shortly.  In SFML however you are rolling your own game loop, so you are also rolling your own time tracking system.  Don’t worry though, the process is extremely simple.  That’s see one final complete sample that also keeps track of the elapsed time per frame.

#include "SFML/Graphics.hpp"
#include <iostream>

int main(int argc, char ** argv) {
  sf::RenderWindow renderWindow(sf::VideoMode(640, 480), "SFML Demo");

  sf::Event event;

  // A Clock starts counting as soon as it's created
  sf::Clock clock;
  
  while(renderWindow.isOpen()){
    // Check for all the events that occured since the last frame.
    while (renderWindow.pollEvent(event)){
      //Handle events here
      if (event.type == sf::Event::EventType::Closed)
        renderWindow.close();
    }
  
    // A microsecond is 1/1,000,000th of a second, 1000 microseconds == 1 millisecond
    std::cout << "Elapsed time since previous frame(microseconds): " << clock.getElapsedTime().asMicroseconds() << std::endl;
    // Start the countdown over.  Think of laps on a stop watch.
    clock.restart();


    renderWindow.clear();
    renderWindow.display();
  }

}

You will notice the addition of an sf::Clock to our game.  The Clock provides the most accurate time that the underlying OS is capable of giving (different timers have different resolutions, and this timer needs to be very precise!).  As soon as it is declared, it starts counting.  Think of sf::Clock like a stopwatch that starts automatically.  Each “lap” you can read the elapsed time using getElapsedTime() and you can start a new lap by calling restart().   In this example we get the elapsed time in microseconds.  There are 1000 microseconds in a millisecond, and 1000 milliseconds in a second, so a microsecond is one millionth of a second.  Like I said, we need precision!

 

So that is the process of creating a very simple SFML application, clearing and displaying the window, tracking how much time elapsed and handling events.  In the next tutorial we will look at events a bit closer and see how best to handle keyboard input.

 

The Video

 

Programming


28. July 2015

 

We covered viewports a while back but now we are going to go into a bit more detail, as it’s an important subject.

 

There is a 1080p version of this tutorial available here.   Please note, the full screen portions didn’t display properly in the video.

 

One very important thing to understand is, the very root of your scene, the node that owns all of the nodes in a scene, is ultimately a viewport.  Consider this hierarchy:

image

In that node if you run the code:

func _ready():
   print(get_node("/root"))

 

You will see:

image

 

So, no matter how you create your scene, you will always have at least one viewport.  On the other hand, you can create more viewports within the scene as we will see later.

 

Full Screen Applications

 

It’s possible to set your application to run full screen, both using code or in the application settings.  To do it with code, create a new autoload script as described here.  This is a script, derived from node, that gets run automatically when your game launches.  Use the following code:

extends Node

func _ready():
   var root = get_node("/root")
   root.connect("size_changed",self,"resize")
   OS.set_window_fullscreen(true)
   set_process_input(true)
   
#Event called when viewport size changed  
func resize():
   var root = get_node("/root")
   var resolution = root.get_rect()
   print(resolution)
   
#Input handler, listen for ESC to exit app
func _input(event):
   if(event.is_pressed()):
      if(event.scancode == KEY_ESCAPE):
         get_tree().quit() 

 

Of course this code does a lot more than just set the application full screen.  Due to the app going full screen, it is no longer easy to close the window, so I’ve also wired in some code to handle shutting down if the user hits Esc.  There is also an event handler connected to fire when the resolution changes, we simple print the resolution to the console when it changes.

 

You can accomplish the exact same thing (much easier) using project settings, like so:

image

Please note there are two check boxes to enable!  First you need to enable the fullscreen setting, then you need to turn it on.

 

Viewport Scaling

Now to illustrate how resolution works in Godot, I’ve created a Sprite Node( not centered, at 0,0 ) using this image, which illustrates the various screen resolutions.

image

 

The actual image is 1920x1080 in size, so it should show us the results that various settings have on our game.  Here is a run, using default settings on my laptop which has a 1600x900 display. 

The following display settings are very important.

image

The following screenshots are all scaled down but maintain the aspect ratio of the source image.  The Viewport setting has a profound effect on the results.  The options are:

image

 

Viewport == disabled.  Resolution is 1600x900 ( my native resolution ) and display resolution settings ignored.

image

 

Mode == 2d.  Image size is 1600x900.

image

 

Viewport stretch mode.  Image size is 800x600.

image

 

It’s the ultimate results that make the difference.  When viewport is set to disabled, the width/height are ignored completely and the resolution of the device is used.  In viewport set to 2D, the width and height are used and the results are simply scaled up (or down) to match the resolution of the actual device.  While in Viewport, the results are actually scaled down to the resolution specified.  This means our actual render results are at 800x600 ( or whatever resolution you specified ).   You would generally use this last mode if you were trying to create a pixel perfect game, or if you are trying to render to a lower resolution to improved performance.  Keep in mind on most machines the results will look somewhat horrible.

 

 

 

Handling Aspect Ratios

Now this resizing works great when you are dealing with the same aspect ratios, but once they start changing, it has a much more pronounced effect.  For example, content designed for a 4:3 screen ( iPad ) will look horrible on a 16:9 screen ( Galaxy Note ) for example.  You also need to decide HOW you are going to deal with different aspect ratios.  This isn’t a new problem, people watching single def signals on HD displays have been dealing with this issue for years.

I created a new Sprite, this time using a sprite 379x124 pixels in size, like so:

image

Then automatically position it in the center of the viewport on load:

 

func _ready():
   self.set_pos(Vector2(get_viewport_rect().size.width/2,
                get_viewport_rect().size.height/2))

 

As mentioned earlier, my laptops native resolution is 1600x900, so everything looks fine with an HD resolution.  For example, here is the result rendered at 1280x720 full screen (but scaled down on the blog):

image

 

Looking good!  Now lets try 640x480, a not so HD aspect ratio:

image

 

Ewwww…. ok… obviously not what we want.  The result of the resampling to fit a 640x480 image on a 1600x900 screen as stretched our ship almost to the point of being unrecognizable.

You do however have options here, once again under display settings called stretch_aspect.

image

 

Lets see the result on our 640x480 scene:

 

ignore

image

keep

IMAG0363

keep_width

IMAG0364

keep_height

IMAG0365

 

You may notice the pictures are literally camera shots of my laptop.  This is because the screenshots don’t capture the black bar portions of the image.

Basically you can choose to simply rescale the aspect ratio, which causes the sprites to distort if the source and destination resolutions don’t have a similar aspect ratio.  Choosing Keep will cause it to keep the aspect ratio specified and generate black bars, either horizontally or vertically, whichever is needed.  You can also tell it to keep the height or the width aspect ratio.  The remaining dimension ( height if you chose Keep_width for example ) will then be scaled to fit, causing distortion in that direction.

 

Sub-Viewport

As mentioned earlier, the root node in the scene is always a viewport.  You can however create a viewport node within the scene or embedded within another node.

 

Consider this hierarchy of Nodes for example:

image

 

In the Editor it looks like a complete mess:

image

But when you run it, you can immediately see the results:

image

The nodes added to the child viewport are positioned relative to, and rendered within that viewport.

 

Cameras

 

The Camera2D class in Godot is mostly just responsible for manipulating the transform of the viewport.  A Camera automatically applies itself to the closest viewport above it in the node hierarchy, and if there isn’t one, it affects the root node instead.  Only one camera can be active at a time per viewport.

 

Otherwise using a camera is extremely simple.  Consider a scene like this that extends beyond the viewport:

image

 

Simply drop a Camera2D node into the scene:

image

 

Set Current To On

image

 

And your view will automatically update to represent the camera’s position

image

 

 

Taking a Screen Shot

 

When running full screen, capturing a screen shot can become a bit tricky.  I got around it by handling the logic in code.  If you are interested, here is how I captured a screenshot using Godot:

      if(event.scancode == KEY_SPACE):
         print("Screenshot")
         get_viewport().queue_screen_capture()
         yield(get_tree(), "idle_frame")
         yield(get_tree(), "idle_frame")
         var screenshot = get_viewport().get_screen_capture()
         screenshot.save_png("user://screenshot.png")

The location of “user://” is going to change from platform to platform.  On Windows 8.1 the screenshot was located at C:\Users\Mike\AppData\Roaming\Godot\app_userdata\Viewport on my computer.  On Linux, check for a directory named .godot in your home directory.

 

The command queue_screen_capture() doesn’t happen immediately.  This is why we yeild two frames before calling get_screen_capture(), which will have the results of queue_screen_capture() or return an empty image if it hasn’t occurred yet.

 

The Video

Programming


12. July 2015

 

In today’s “A Closer Look At” guide we will be taking a look at the App Game Kit 2 game engine.  The Closer Look at Series is a combination preview, review and imagegetting started tutorial aimed at giving you a solid overview of what working in a particular game engine is like.  App Game Kit is a cross platform game engine capable of making games for Windows, Mac, iOS, Android and Blackberry devices using Mac or Windows development environments.  App Game Kit regularly costs $99, although if you are reading this near the publish date ( 7/12/15 ) it is currently available in the Humble Gamedev Bundle with several other tools.

 

AppGameKit is a cross platform, mobile friendly 2D/3D game engine, although 3D is a work in progress.  AGK is programmed primarily using AGK Script, which is a BASIC dialect with some C++ style features.  If the word BASIC caused you to recoil in terror from your screen, don’t worry, AGK is also available as a C++ library.  If the word C++ just recoiled from your screen, hey… there’s always AGK Script… :)  Over the course of this article we will take a quick look at both.  AppGameKit 2 was the result of a successful Kickstarter campaign and is a product of The Game Creators who previously developed Dark Basic and 3D Gamemaker.

 

There is also an HD video version of this article available here or embedded below.

 

Hello AGK

Let’s jump right in with a pair of Code samples.  First in AGK Script, then in C++.

 

AGK Script Example

// Project: test 
// Created: 2015-07-10

// Setup the main Window
SetWindowTitle( "My Game Is Awesome!" )
SetWindowSize( 640, 480, 0 )

// set display properties
SetVirtualResolution( 640, 480 )
SetOrientationAllowed( 1, 1, 1, 1 )

// Create a Cube 100x100x100 at the Origin
box = CreateObjectBox(100,100,100)
SetObjectPosition(box,0,0,0)

// Add a light to the scene
CreateLightDirectional(1,-1,-1,-0.5,255,255,255)

// Set the position of the camera and aim it back at the origin
SetCameraPosition(1,0,100,-150)
SetCameraLookAt(1,0,0,0,0)

rotationY# = 0

// Gameloop
do
   // Display the current FPS
   Print( ScreenFPS() )
   // Rotate our Object
    SetObjectRotation(box,0,rotationY#,0)
    // Display back buffer
    Sync()
    // Update Rotation
    rotationY# = rotationY# + 1
loop

 

Here is this code example running:

g1

 

C++ Example

// Includes
#include "template.h"

// Namespace
using namespace AGK;

app App;

void app::Begin(void)
{
   agk::SetVirtualResolution (640, 480);
   agk::SetClearColor( 0,0,0 ); 
   agk::SetSyncRate(60,0);
   agk::SetScissor(0,0,0,0);


   // Load a Sprite at index 1
   agk::LoadSprite(1,"logo.png");
   // Scale the sprite to 25% of it's size
   agk::SetSpriteScale(1, 0.25, 0.25);

   
}

void app::Loop(void)
{
   agk::Print(agk::ScreenFPS());

   // On gamepad press, spacebar hit, touch or left click enable 
   physics on our sprite
   // And make that sucker bouncy, gravity does the rest
   if (agk::GetButtonPressed(1) || agk::GetPointerPressed()){
      agk::SetSpritePhysicsOn(1, 2);
      agk::SetSpritePhysicsRestitution(1, 0.8);
   }

   agk::Sync();
}


void app::End (void)
{

}

 

Here is this code sample running:

g2

 

There is a bit more to the C++ example than the code shown here.  AGK is provided as a library for C++ use.  To get started there are also a number of templates that you can copy and start from.  Each template has a bootstrap class containing the required code to start AGK.  For example the Visual Studio project provides a WinMain implementation for you.  Here are the currently available templates for a Windows install (MacOS has XCode projects available for iOS and Mac):

image

 

Of course you can of course create your own application and simple use AGK as a C++ library if you prefer.

 

Tools Included

 

AGK IDE

If you are working with AGK Script, the majority of your development will be done in AGK IDE.  AGK IDE is a Code::Blocks derived IDE with full text editing, syntax highlighting, code completion and debugging support for AGK Script.

image

 

I experienced no lag when using the IDE.  Most of the features you would expect in a modern IDE are available, including code folding, find/replace, intellisense and code hints:

image

 

Refactoring tools are all but non-existent and unfortunately there is no local help.  (We will discuss help files shortly).

 

Debugging is supported:

image

But the implementation is barebones, limited to break points, step over/out and displaying the call stack.  You can inspect variable values, but you have to enter them manually in the Variables area.  There is no ability to inspect, add watch or set conditional breakpoints.  I believe this functionality is relatively new, so hopefully it will be extended with time.

 

If you choose to work with C++, you will not use AGK IDE at all, instead working in your C++ IDE of choice.  As mentioned earlier, several templates are provided.

 

Placement Editor

AGK also ships with the Placement Editor, a fairly simplistic tiled level creator:

image

 

It enables you to place varying sized tiles, perform transforms such as rotation and mirroring, layer up and down and supports grid snapping to grid for precise layouts.  The UI however leaves something to be desired, with the scroll bars only supporting movement via the arrows and panning controlled using an onscreen controller.  Additionally you have to exit the application and copy graphics to the media directory to add new tiles.  Unfortunately it’s also lacking some seriously required functionality such as defining collision volumes or physics properties.  It does however enable quick creation of tiled backgrounds.

AGK Player

One other cool feature of AppGameKit is the AGK Player, available on mobile devices:

ss

 

By pressing Broadcast in the IDE, you can easily see your code running on device without having to bundle/sign/deploy like normal.  It is available for download in the app store, except on iOS where you have to build and deploy it yourself using XCode.  This tool enables rapid on device testing during development and can be a huge time saver.

 

Samples and Demos

AppGameKit ships with an impressive number of AGK Script code samples:

image

Including a few complete games:

image

And some user provided examples:

image

 

Here is the SpaceShooter example in action:

g3

 

Documentation and Help

 

I mentioned earlier that there is no local documentation available, which is unfortunate.  There also doesn’t appear to be a generated class library reference, which is also unfortunate.   That said, the documentation available for AGK is actually rather solid and has been complete from my experiences.  It is available entirely online so you can check it out yourself.

 

The scripting language itself is quite simple and documented here in reference form.  While a more broad language introduction and overview is available here.  As mentioned earlier, there are also dozens of examples included to learn from.  There are a series of guides available covering specific topics such as networking , platform publishing and more.  The closest thing to a class reference is the Commands documentation, you can toggle between C++ and BASIC code examples:

image

 

AGK also has a very active developer forum available.

 

The Library

 

Of course we should talk about what functionality is available in AGK.  Over all it’s quite comprehensive, although the 3D functionality is very actively under development and some functionality is obviously missing or under development ( such as animated 3D model support ).

 

The follow feature list is taken directly from the AGK site.

  • Write once, deploy technology
  • Code in BASIC or native (C++)
  • Device independent
  • Cross Platform IDE
    • Develop on Windows or Mac and deploy to Windows / Mac / iOS / Android / Blackberry 10
    • Broadcast test apps to devices over Wifi
    • Auto Complete
    • Function Lists
    • Code Folding
    • Export to exe/app/apk/ipa
  • 2D Games Engine
    • Tweening
    • Blending modes
    • Spine Support
    • Box 2D Physics
    • Particles
    • Drawing commands
    • Text support - fixed and variable width
  • 3D Engine
    • Primitives
    • Positioning
    • Rotation
    • Shaders
    • Collision
    • Cameras
    • Lights
  • Audio/Visual
    • Video Playback
    • Sound
    • Music
  • Input Agnostic
    • Direct Input Control
    • Touch
    • Keyboard
    • Mouse
    • Accelerometer
    • Joystick/Controllers
  • Sensors
    • Camera Access *
    • GPS *
    • Geo-location *
    • Inclinometer *
    • Light Sensor
  • Mobile
    • Rating an app *
    • In-App Purchasing *
    • Adverts *
    • - Chartboost
    • - Admob
  • Networking
    • Messages
    • Shared Variables
  • Misc
    • File IO
    • Facebook *
    • File IO
    • Extensive help & tutorials
    • Time & Date
    • Enhanced image control
    • QR Codes
    • HTTP
    • Edit Boxes
    • Zip file control
  • Coming Soon...
    • Debugger
    • 3D Engine Enhancements
    • File IO
    • 3D Bullet Physics
    • Extension System

    * Selected platforms only.

 

Conclusion

 

I certainly haven’t spent enough time with AGK to consider this a full review by any means.  The following are my initial impressions when working with AGK.  I am personally not a huge fan of the BASIC language, even as a beginner recommendation, but AGK Script is accessible and the included tooling make AGK an appropriate choice for beginners, especially with the included examples and solid documentation.  I was able to use the library very much by intuition and the ability to code entirely in C++ will appeal to several developers.  The mapping between C++ and BASIC is very natural but this also comes at a cost.  The C++ side of the equation is very “flat” in structure, using no OOP and a disconcerting number of “magic number” type variables.  In a simple project, AGK is a solid and approachable choice.  In more complex projects, without writing an organizational layer over top, I could see quickly developing a mess of unmaintainable code.

 

The tools included with AGK are functional but could both use a bit of polish.  The editing experience in AGK script is fine but the debugger is fairly young and needs some work and the some more refactoring support would be nice.  Integrated and context sensitive help would also be a huge boon.  For the most part though there is enough functionality in the IDE that working in AGK Script wouldn’t feel like a chore.  The level editing tool is nice in that it exists, but the functionality is extremely limited and the UI isn’t the best.  For anything but the most trivial game, I would imagine you would find yourself wanting a more mature tool like Tiled, although a loader is available, so this is certainly an option.  Also, the editor is only available on Windows machines.

 

From a developer perspective, for a 2D game, AGK provides pretty much all of the functionality you would expect and some that is a bit unexpected, like cross platform video playback.  3D is coming along but missing some key functionality.  The code experience is incredible consistent, once you’ve figured out how to do one task, you can generally guess how other tasks are going to be performed.  You can accomplish a great deal in AGK in a very short period of time, but I do question how well the design would scale to larger projects.  As a C++ library, AGK could also be considered as a cross platform competitor to libraries such as SFML or SDL.  AGK does appear to be a good solution for new developers, especially if you like the BASIC programming language or wish to work with an approachable C++ library.  For more experienced developers, AGK is a productive and easy to learn library supporting a respectable number of platforms with the option of high and low level development.  I just don’t know how well this product would scale with project complexity.

 

The Video

Programming


9. July 2015

 

In this part we are going to explore using Particles in the Godot Engine.  Particles are generally sprites, either provided by you or generated programmatically, that are controlled by a unified system.  Think of a rain storm, each drop of rain would represent a particle, but the entire storm itself would be the particle system.  You would not control each drop individually, instead you would simply say “rain here” and the system takes care of the rest.  Particles are often used for special effects such as smoke, fire or sparks.  The Godot game engine makes working with particles quite simple.

 

There is an HD video version of this tutorial available here or embedded below.

 

This particular tutorial isn’t going to go into a great deal of detail over the effects of each setting, as there is already an excellent illustrated guide right here.  Instead I will focus on using particles in a hands example.  As I mentioned earlier, particle systems are often used to create fire effects, and that’s exactly what we are going to do here, create a flaming/smoking torch.

 

Creating a particle system is as simple as creating a Particles2D node:

image

Creating one will create a simple system for you:

part1

 

As always, the properties are controlled in the Inspector.  In this case we are creating 32 particles with a lifespan of 2 seconds aimed down and affected by gravity:

image

 

Now let’s suit it to our needs.  First we want to change the direction of our particles to up instead of down. This is set by setting the direction property, this is a value in degrees for the particles to be emitted in.

image

 

Here is the result:

part2

Next, since this is a torch, we don’t want the particles to be affected by gravity.  Under Params, simply set Gravity Strength to 0:

image

And the result:

part3

Now white dots are exactly convincing flames… so lets add a bit of color.  This can be done using Color Phases.  These are the colors the a particle will go through during it’s lifetime.  For a torch, we will start with a brilliant white, then orange and finally red, like so:

image

Be sure to set the Count to 3.  You can have up to 4 phases if needed.  Now our results look like:

part4

A bit better.  Now we want to work on the size a bit.  Let’s start our particles off bigger and shrink as they move away from the source of the flame.

image

Resulting in:

part5

 

Finally we slow it down slightly and decrease the spread:

image

 

And voila:

part6

 

A fairly passable torch.  You could play with it a bit, use an image instead of a square particle, change the alpha value of each color phase or add another overlapping particle system to provide smoke.  Keep in mind though, more particles, more processing.

 

Here is a simple layer of smoke added as a separate particle system and the alpha lowered on the final two color phases:

part7

 

Particles are as much an art to create as a texture or 3D model.  Play around until you achieve the effect you want.  Be sure to read that link I post earlier for the effects various settings have on your particle system.  One other area I never touch on was randomization.  In addition to numerous settings for controlling how particles are created, you can also randomize each of those values so your particles end up being less consistent.

 

As mentioned earlier, a particle can also be created from a texture or series of textures.  To set a texture, simply set it’s texture property:

image

 

In this example I am going to use this spritesheet to create a flock of animated birds:

robincropped

 

Set H and V to correspond to the number of rows and columns in your TextureAtlas:

image

 

I am unsure of how to deal with TextureAtlases with empty squares, there doesn’t seem to be a way to set a total count, but I may have overlooked it.  Next you are going to want to specify the speed you want it to jump between frames of animation using Anim Speed Scale

image

I tweaked a few more settings:

image

And my final results are a fairly nice flock of birds:

part8

 

One other feature available is the particle attractor ParticleAttractor2D, which can be used to attract particles, to either fling them out the other side or absorb them.  Think of it like a black hole that either sucks in or spits out the particles in it’s radius of influence:

image

part9

Keep in mind that particles all have a lifespan, and once that lifespan has elapsed, it will fade away.

 

Particles provide a powerful way of implementing tons of graphically similar effects ( like fire, fog, flocking etc ) with a single controlling system.  They are as much art as programming though, so will take some time playing around to get the effect just right.

 

The Video

 

Programming


23. June 2015

 

With the release of version 4.8 of Unreal Engine, playing audio actually became a great deal easier for 2D games with the addition of PlaySound2D.  In this section we are going to learn how to import and play audio files in Unreal Engine.  For the application controller I created a simple UI that fire off the playing of audio.  If unfamiliar with creating a UI with UMG ( Unreal Motion Graphics ), be sure to read the previous tutorial.

 

As always there is an HD video version of this tutorial available right here.

We are going to be creating a simple UI to fire off audio events:

image

 

We will simply wire each button to fire off our examples.  I also needed several audio samples.  I personally downloaded each one from freesound.org.

 

Importing Audio Files

 

First we need some audio to work with.  So then… what audio files work with Unreal Engine?  Mp3, mp4, ogg?  Nope… WAV.  You can import your sound files in whatever format you want, so long as it’s wav.  Don’t worry, this isn’t as big of a hindrance as it sounds, as Unreal simply takes care of the compression and conversion steps required for you.  So the fact your soundtrack is 10MB in size isn’t as damning as it seems, as Unreal will take care of the required conversions for you.  Being in an uncompressed source format enables Unreal to offer a lot of power as you will see shortly.  Also it neatly steps around a number of licensing concerns, such as the patent minefield that is mp3.  If you’re source files aren’t in wav format, you can easily convert using the freely available and completely awesome Audacity sound editor.

 

Your WAV files can be in PCM, ADPCM or DVI ADPCM format, although if using defaults you most likely don’t need to worry about this detail.  They should be 16 bit, little endian (again… generally don’t worry) uncompressed format at any bitrate. 22khz and 44.1khz are recommended however, with the later being the bit rate CD quality audio is encoded at.  Your audio files can be either mono (single channel) or stereo (dual channel), plus you can import up to 8 channels of audio ( generally 8 mono WAV files ) to encoded 7.1 surround sound.  This is way beyond the scope of what we will be covering but more details about 7.1 encoding can be found here.  Importing audio is as simple as using the Import button in the Content Browser, or simple drag and drop.

 

Once imported, you can double click your audio asset to bring up the editor.

image

 

Here you can set a number of properties including the compression amount, wether to loop, the pitch, even add subtitle information.  There isn’t anything we need to modify right now though.  I have imported a couple different mono format wav files, like so:

image

 

And created a simple button to play the audio when pressed:

image

 

Playing Sounds

 

Now let’s wire up the OnClick event to play Thunder.wav, with the following blueprint:

image

 

Yeah… that’s all you need to do, drop in a Play Sound 2D function, pick the Wave file to play and done.  Before 4.8 the only option was Play Sound at Location, which is virtually identical but required a Position component as well.  You can achieve the same effect this way:

image

 

Both Play Sound at Location and Play Sound 2D are fire and forget, in that you have no control over them after the sound has begun to play (other than at a global level, like muting all audio ).  Neither moves with the actor either.

 

What if you want the audio to come from or move with a node in the scene?  This is possible too.   First let’s create a Paper2D character to attach the audio component to.  This process was covered in this tutorial in case you need a refresher.  Don’t forget to create a GameMode as well and configure your newly created controller to be active.

 

Using the Audio Component

 

I created this hierarchy of a character:

image

Notice the Audio component I’ve added?  There are several properties that can be set in the Details panel for the audio component, but the most important is the sound.

image

I went ahead and attached my “music” Sound Wave.  You can set the music file to automatically play using the Activation property:

image

There is also an event available that will fire when your audio file has finished playing. 

image

Unlike PlaySound2D, this sound isn’t fire and forget.   It can also be changed dynamically using the following Blueprint:

image

This blueprint finds the Audio component of our Pawn and then set’s it’s Sound using a call to Play Sound Attached.  As you can see, there are several available properties to set and you can easily position the audio in the world.

 

As I mentioned earlier, you can also manipulate a running Sound wave when attached as an audio component, like so:

image

 

Paradoxically, there doesn’t actually seem to be a method to get the current volume.  The obvious solution is to keep the volume as a variable and pass it to Adjust Volume Level.

 

Sound Cues

So far we’ve only used directly imported Sound Wave files, but every location we used a Wave, we could have also used a Cue.  As you will see, Cues give you an enormous amount of control over your audio.

 

Start by creating a new Sound Cue object:

image

Name it then double click to bring up the Sound Que editor:

image

This is well beyond the scope of this tutorial, but you can essentially make complex sounds out of Sound nodes, like this simple graph mixing two sounds together:

image

 

Again, any of the earlier functions such as Play Sound 2D will take a Cue in place of a Wave.

 

We have only scratched the very surface of audio functionality built into Unreal Engine, but this should be more than enough to get you started in 2D.

 

The Video

Programming


AppGameKit Studio

See More Tutorials on DevGa.me!

Month List