Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
24. April 2015

 

As you may have guessed from the title, it today’s tutorial we are going to look at working with Sprites using Unreal Engine.  We already looked briefly at creating a sprite in the previous tutorial, but today we are going to get much more in-depth.

 

Before you can create a sprite, you need to have a texture to work with.  Unreal Engine supports textures in the following formats:

  • .bmp
  • .float
  • .pcx
  • .png
  • .psd
  • .tga
  • .jpg
  • .dds and .hdr ( cubemaps only, not applicable to 2D )

 

That said, not all textures are created equal.  Some formats such as bmp, jpg and pcx do not support an alpha channel.  This means if you texture requires any transparency at all, you cannot use these formats.  Other formats, such as PSD ( Photoshop’s native format ) are absolutely huge.  Others such as BMP have very poor compression rates and should generally be avoid.  At the end of the day, this generally means that your 2D textures should probably be in png or tga formats.  Unreal also wants your textures to be in Power of Two resolutions.  Meaning that width/height should be 2,4,8,16,32 … 512, 1024, 2048, etc…  pixels in size.  It will work with other sized textures, but MIP maps will not be generated (not a big deal in 2D) and performance could suffer(a big deal).  Keep in mind, your sprite doesn’t need to use all of the texture, as you will see shortly.  So it’s better to have empty wasted space then a non Power of Two size.

 

* Personally I’ve experienced all kinds of problems using PNG, such as distorted backgrounds, while TGA has always worked flawlessly. 

 

Adding a Texture to your game

 

Adding a Texture is simple as selecting a destination folder on the left, then dragging and dropping the appropriate file type (from the list above) from Finder/Exporter to the Content Browser window, shown below:

image

 

Alternately, you can click New –> Import

image

 

Then navigate to the file you wish to use and select it. 

 

You texture should now appear in the Content Browser.

 

Texture Editor

 

Now that you have a texture loaded, you can bring it up in the Texture Editor by either double clicking or right clicking and selecting Edit.  Here is the texture editor in action.  It is a modeless window that can be left open indepently of the primary Unreal Engine window.

 

image

 

The Texture Editor enables you to make changes to your image, such as altering it’s brightness, saturation, etc…  you can also change compression amounts here.  However, for our 2D game, we have one very critical task…  turning off MIP maps.

What's a MIP Map?

History lesson time! MIP stands for multum in parvo, Latin for "much in little". Doesn't exactly answer the question does it? Ok, lets try again. Essentially a MIP map is an optimiziation trick. As things in the 3D scene get further and further from the camera, they need less and less detail. So while right up close to an object you may see enough detail to justify a 2048x2048 resolution texture. However, as the rendered object gets farther away in the scene, the texture resolution doesn't need to be nearly as high. Therefore game engines often use MIPMaps, multiple resolution versions of the same texture. So, as the required detail gets lower and lower, it can use a smaller texture and thus less resources.
You know when you are playing a game and as you move rapidly, often textures in the background "pop" in or out? This is the mipmapping system screwing up! Instead of seamlessly transitioning between versions, you as the user are watching the transition occur.


Support for MIP maps is pretty much automatic in Unreal Engine.  However in the case of a 2D game, you don’t want mipmaps!  The depth never changes, there should never be different resolution versions of each texture.  Therefore, we want to turn them off, and the Texture Editor is the place to do it.  Simply select Mip Gen Setting and select NoMipmaps.

image

 

Before you close the Texture Editor, be sure to hit the Save button.

image

 

Creating A Sprite

 

Now that we have a Texture, we can create a sprite.  This is important, as you can’t otherwise position or display a Texture on it’s own.  So, then, what is a Sprite?  Well the nutshell version is, it’s a graphic that can be positioned and transformed.  The name goes back to the olden days of computer hardware, where there was dedicated hardware for drawing images that could move.  Think back to PacMan…  Sprites would be things like PacMan himself and the Ghosts in the scene.

 

In practical Unreal Engine terms, a Sprite has a texture ( or a portion of a texture, as we will see shortly ) and positional information.  You can have multiple sprites using the same texture, you can have multiple sprites within a texture, and the sprites source within a texture can also change.  Don’t worry, this will make sense shortly. In the meantime, you can think of it this way… if you draw it in 2D in Unreal Engine… it’s probably a Sprite!

 

Once you have a Texture in your project, you can easily create a sprite using the entire texture by right clicking the Texture and selecting Create Sprite, like so:

image

 

You can also create a new sprite using New->Miscellaneous->Sprite

image

 

This will then open up the Sprite Editor.  If you created the Sprite using an existing texture, the texture will already be assigned.  Otherwise you have to do it manually.  Simply click the Texture in the Content Browser.  Then click the arrow icon in the Details panel of the Sprite Editor on the field named Source Texture:

image

 

Your texture should now appear like so:

image

 

You can pan and zoom the texture in the view window using the right mouse button and the scroll wheel.

 

Now remember earlier when I said “all or part of the texture”?  Well a Sprite can easily use a portion of a texture, and that’s set using the Edit Source Region mode:

image

 

This changes the view panel so you can now select a sub rectangle of the image to use as your sprite source.  For example, if you only wanted to use Megatrons head, you could change it like:

image

 

Then when you flip back to View, your texture will be:

image

 

When dealing with sprite sheets, this becomes a great deal more useful, as you will see shortly. 

 

There are a couple other critical functions in the Sprite Editor that we will cover later.  Most importantly, you can define collision polygons and control the physics type used.  We will look at these functions later on when we discuss physics. 

 

Two very important settings available here are:

image

 

Pixels Per Unit and Pivot Mode.

 

Pixels per unit is exactly what it says… a mapping from pixels to Unreal units, which default as mm.  So right now, each pixel is 2.56mm in size.  Pivot Mode on the other hand determines where a sprite is transformed relative to.  So when you say rotate 90 degrees, you are rotating 90 degrees around the sprites center by default.  Sometimes top left or bottom left can be easier to work with, this is where you would change it.

 

The final important point here is the Default Material, seen here:

image

 

This part is about to look a lot scarier than it is!  Just know up front, if you prefer, you can ignore this part of Unreal Engine completely!

 

Materials

 

Every mesh in Unreal Engine has a material attached, and when you peel back all of the layers, a Sprite is still ultimately a mesh… granted, a very simple one.  There are two default options available to you included in the engine, although depending on how you created your project, you may have to change your view settings to access them:

image

 

Then you will find the two provided materials for sprites:

image

 

The name kind of gives away the difference… DefaultLitSpriteMaterial takes into account lighting used in the scene.  DefaultSpriteMaterial ignores lighting completely.  Unless you are using dynamic lighting, generally you will most likely want the DefaultSpriteMaterial.  You can edit the Material by double clicking:

image

 

This is the Material Editor and it is used to create node based materials.  Basically it’s a visual shader programming language, behind the scenes it ultimately is generating a GLSL or HLSL shader in the end.  Truth is the process is way beyond the scope of what I can cover here and in most cases you will be fine with the default shader.  If you do want to get in to advanced graphic effects, you will have to dive deeper into the Material Editor.

 

Creating a Sprite

 

Now that we have our texture and made a Sprite from it, it’s time to instance a Sprite.  That is, add one to our scene.  This is about as simple as it gets, simply drag a Sprite from the Content Browser to the Scene, like so:

 

g1

 

Now that you’ve created a Sprite, you will notice that there area  number of details you can set in the Details panel:

image

 

All sprites by default share the same source sprite and material, but you can override it on an instance by instance basis.  For example, if you wanted a single sprite to be lit and all the others to be unlit, you can change the Material Override on that single sprite.  Obviously using Details you can also set the sprites positioning information and some other settings we probably wont need for now.

 

 

Next up, we will look at sprite animation using a flipbook.

Programming


8. April 2015

 

The first tutorial in the Unreal Engine vs Unity tutorial series is now live.  In this tutorial we look at using Unreal Engine.  It’s an introduction to Unreal Engine, a guided tour around the editor, then we create a simple Hello World application using Blueprints.

 

I will be creating a companion text tutorial to go along with this video shortly.

 

You can see the video in full 1080p here.

 

The Video

 

Programming


19. March 2015

 

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

 

You can watch the video here, or embedded below.

 

Checking for Collisions

 

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

image

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

anim

 

Let’s take a look at the script now:

extends Sprite

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

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



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

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

 

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

 

Physics Simulations

 

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

 

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

 

First we start by creating a RigidBody2D node:

image

 

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

image

 

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

anim2

 

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

 

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

image

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

 

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

 

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

 

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

 

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

 

The answer is trust ole project settings:

image

 

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

 

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

image

 

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

 

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

 

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

 

Collisions Physics Style

 

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

image

 

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

image

 

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

image

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

image

 

Now when you run the game:

anim3

 

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

 

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

image

 

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

image

 

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

image

 

And once closed:

image

A MUCH more accurate representation of your object for collisions!

 

Kinematic Nodes

 

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

 

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

image

 

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

extends KinematicBody2D



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

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

anim4

 

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

 

The Video

 

Programming


23. February 2015

 

Until this point in the series we have only created single scene games.  In any non trivial application you are often going to want to have several scenes make up your game.  For example you might have a scene for your title screen/intro, then a main menu, then a game playing then finally a game over scene.  Today we are going to look at how to do exactly this.  We are also going to look at sharing information between those scenes.

 

This scene is available as an HD video here.

 

Creating Multiple Scenes

 

First and foremost, you always need to have at least one scene to start up.  Let’s go ahead and create one, the Title screen seems logical enough.  Create a scene that draws a simple graphic, called it “title_scene.scn” and set it as your startup scene.  If you are unfamiliar with this step, please see prior tutorial parts.  Once complete it should look something like this:

image

 

Next we want to create a scene to transition to.  I called mine game.scn.  It may not be completely obvious, but you actually close your scene to create the new scene.  Select Scene->New Scene:

 

Then say yes to the scary dialog that pops up ( of course, we assume you’ve saved your scene and set it as the startup scene already! ):

image

 

Now in the second scene, I just created a simple Panel, with a pair of label controls, like so:

image

 

It doesn’t really matter what you do.  The labels are just to show that information can be shared between Scenes.  Our game isn’t actually going to do anything.

 

 

Ok… so now we have our two scenes… how are we going to wire them all together?  Well that requires a script.  Re-open the title_scene.scn scene.  There is a handy Open Prev Scene menu option, or you can use open Scene…

image

 

Adding a Script to control scene switching

 

Now that we have our original scene selected, we need to add a script to it.  To do this, switch to the Resources tab and select the New Resource icon:

image

 

For type select GDScript:

image

 

I named mine ‘global.gd’.

 

Now we write out our script.  We are going to be auto loading this as a node into our game when our application starts, so we need to inherit from Node or a Node derived class.  In my case I used node.  You can inherit a class using the extends keyword.

 

Here is the code for our simple Node script.  We create a function so scenes can switch between scenes, and demonstrate getting a session variable, as well as setting a global variable.

extends Node

#The currently active scene
var currentScene = null

#just some data for our game.  It could be HPs, Alignment, Direction, etc...
var PlayerName = "Mike"


func _ready():
   #On load set the current scene to the last scene available
   currentScene = get_tree().get_root().get_child(get_tree().get_root().get_child_count() -1)
   #Demonstrate setting a global variable.
   Globals.set("MAX_POWER_LEVEL",9000)
   
# create a function to switch between scenes 
func setScene(scene):
   #clean up the current scene
   currentScene.queue_free()
   #load the file passed in as the param "scene"
   var s = ResourceLoader.load(scene)
   #create an instance of our scene
   currentScene = s.instance()
   # add scene to root
   get_tree().get_root().add_child(currentScene)
   
   
#simple accessor function to retrieve playerName   
func getPlayerName():
   return PlayerName

 

Autoload script on startup

 

Be sure to save your newly created script.  Now we want to set it so that this screen runs automatically when our game is started.

To do this, go to Scene->Project Settings.

In the resulting dialog, you want to select the AutoLoad tab.  Now you specify the script you want to autoload, and the name you want the node to be known as.  This is case sensitive by the way.

In path, select your newly created global.gd.  In Node Name call it globals then click Add:

image

 

Now this script will be run automatically when your game or application starts up!

 

Now that we can switch scenes, let’s make us of this ability.  In your title_scene.scn project, attach a script to the image you used.  Personally I used a TextureFrame to hold my title screen.    We are simply going to check for the user pressing the left mouse button, and if they do, we are going to switch scenes.

extends TextureFrame


func _ready():
   set_process(true)
   
func _process(delta):
   if(Input.is_mouse_button_pressed(BUTTON_LEFT)):
      get_node("/root/globals").setScene("res://game.scn")

 

As you can see you can access the script by getting it as a node using the name you provided in the AutoLoad dialog.  Once again this value is case sensitive and you have to include the /root/ part. 

 

So, once we click our title image, it should load our other scene.  Let’s add a bit of logic to it.  Load the game.scn ( yes, I wish their was a project mode that prevented this switching between scenes stuff… ), attach a script and add the following code:

extends Panel


func _ready():
   var name = get_node("/root/globals").getPlayerName()
   get_node("Label").set_text(str(name, " is the greatest player ever!"))

   var powerLevel = Globals.get("MAX_POWER_LEVEL")
   get_node("Label2").set_text(str("Maximum power level is ", powerLevel))

 

This code illustrates too simple concepts... calling a global instance ( Singleton in Godot parlance btw ), such as setScene() or getPlayerName() or calling a global variable. Both methods make it very easy to share data between various scenes, escentially forming the backbone of your application.

 

The Video

 

Programming


6. February 2015

 

This tutorial is available as an HD video here.

Today we are going to look at using audio with Godot.  If you’ve used other game engines you will find the process is probably quite a bit different and perhaps a little unintuitive but in the end rather simple and quite power.  It is a bit of a multistep process so let’s jump right in.

 

For this example you are going to need a couple audio files.  Personally I get most of the audio files for my tutorials from a site called http://www.freesound.org/.  Now a moment about audio formats.

 

The Two Kinds of Audio

 

There are two audio types in Godot ( and many other game engines ).  Samples and Streams.  A sample is an uncompressed piece of sound that is loaded into memory.  Samples take up more memory but a great deal less processing power.  In Godot you create samples by importing them as WAV files.  Streams on the other hand are instead compressed audio files (think MP3), often much longer in duration.  These you simply copy into your project, Godot supports MPC and Ogg Vorbis formats. 

 

Generally samples are used for in game quick sound effects, while streams are used for background music.  There is a pretty good chance your audio isn’t in WAV, Ogg or MPC format.  If it isn’t, I highly recommend the free program Audacity for converting between formats.

 

Playing an Audio Sample

 

As I said earlier, samples are uncompressed audio files generally used for sound effects and it’s a multistep process loading and playing one.  Its also quite common to play multiple of the sample sample at once.  Ok, let’s look at that process.

 

First you need to create a SamplePlayer.  This is a node you can add to your scene.  There are 3 kinds of players, SamplePlayer, SamplePlayer2D and SpatialSamplePlayer.  They all accomplish the same thing, however 2D has additional stereo support and can be positioned in your 2D world, while Spatial enables you to position your audio source in 3D to simulate positional audio.  In this tutorial we are just going to use the simple SamplePlayer.  We may cover the other two in later tutorials.

 

Creating the SamplePlayer Node

Add a new SamplePlayer node to your scene:

image

 

 

Creating a new SampleLibrary

 

Now we need to create a Sample library.  With your SamplePlayer selected in the Scene panel, in Inspector locate Samples, drop in down and select New SampleLibrary:

image

 

Now drop it down again and select Edit:

image

 

This will change your active view to the samples library view.  Note, the tabs above ( 2d, 3d, etc ) will not navigate you out of this screen currently.  To get back to your 2D scene view, select a different node in the Scene panel to the right.

image

 

Importing an Audio Sample

 

We can now use this window to add our samples to the library… guess we need a sample.  For that you use the Import menu.  Select Import->Audio Sample:

image

 

This will bring up an Import Audio Samples dialog like so:

image

Under source, navigate to the WAV file you want to import.  For target path select the location within your project you want it to reside.  Under options you have several configuration settings, such as changing the amount of data used/fidelity of your sound ( Max Rate Hz ), making it Mono vs Stereo or forcing it to be 8bit, which is a really low fidelity, single channel but tiny audio file.  For now just use the default settings.  When you click Import a new “smp” file will be added to your project:

image

 

Adding Sample to Audio Library

 

Now that we have our sample, we need to add it to our library.  You can use the same sample in multiple libraries.  In the Edit Sample window select the open icon:

image

 

Select your newly imported sample.  It should now appear in the list like so:

image

Here you can preview the sample, change it’s default volume using dB (decibel) or change it’s pitch using the PScale value.  You can add multiple samples to the sample library.  The yellow blob you see in the middle of the screen is the waveform of the audio… there are two of them because this is a stereo example.  As you can see by the fact they are identical waveforms, this is actually really wasteful, so you would be best to save the file size and import this as a mono sample instead!

 

Playing an Audio Sample using SamplePlayer

 

Now that we have an SampleLibrary with a sample in it, we can now go ahead and play it.  Let’s add a script to our SamplePlayer node that will automatically play the sound when we begin.  It’s incredibly simple, like so:

extends SamplePlayer


func _ready():
   play("siren")

Yeah... that's it.  You simply call the play method of SamplePlayer and pass in the name as defined in the Sample Library.

 

Of course, rarely are you going to have a SamplePlayer play it’s own sounds.  What is much more likely is you would add a SamplePlayer to the base of your scene tree, then call it from child nodes within the scene.  Don’t worry, that is equally simple… let’s do it!

 

Add a Button Node to your scene, attach a script to it, then hit the Connections icon and create a default handler for the “pressed()” connection.

image 

image

 

Generally you wouldn’t use the SamplePlayer as the root scene node, but that’s what I’ve got so I went with it…  Now in your button handler, you can get a reference to the SamplePlayer using:

 

extends Button

func _ready():
   pass


func _on_Button_pressed():
    get_tree().get_root().get_node("SamplePlayer").play("siren")

 

One important thing to be aware of…  the value passed into play() is case sensitive!  So if I passed in “Siren” it wouldn’t play anything!  So basically playing a sample is simply a matter of getting a reference to the SamplePlayer node and calling the play method.

 

So… that’s how you play a single sound… how do you play multiple at once… well, that’s a matter of voices.  A Voice can be thought of as a playing instance of a single sound.  If you want multiple sounds to play at once, you need multiple voices in your SamplePlayer.  You can set that value in the Inspector of the player, like so:

image

 

Now when you run the application, each time you click the button a new version of your sound effect will start playing concurrent to the previous version.  What if you only want a single instance of a sound effect to play at a time?  Well that can be done too…  when you call play() there is an optional second parameter that tells Godot wether the sound is unqiue or not.  Set it to true, like so:

 

get_tree().get_root().get_node("SamplePlayer").play("siren",true)

And each time your press the button the sound effect will instead start over.

 

One final critical thing to understand is how to manipulate ( stop, pause, change volume, etc… ) a single instance of a sound playing.  This is done using Voice IDs, once of which is returned when you play a sample.  So the following example plays a sound and immediately sets it’s volume to 50%:

 

func _on_Button_pressed():
   var player = get_tree().get_root().get_node("SamplePlayer")
   var voiceID = player.play("siren")
   player.set_volume(voiceID, 0.5)
   

 

So you used the voice ID to interact with already running samples.  These only last as along as the sample is playing.

 

Playing Music

 

Now let’s look at streaming a file instead.  The process is very similar, but instead you add a StreamPlayer node:

image

 

Now copy an MPC or OGG file into your project file folder using Windows Explorer or Mac Finder.  Now in Inspector with StreamPlayer selected, locate the Stream property and select the appropriate type, I’m using AudioStreamOGGVorbis:

image

Now drop it down again and select Load:

image

 

Select the file you copied into your project.  Attach a script to a Node in your Scene… for demo reasons I’m just adding it to the StreamPlayer itself.  Then you can use the code:


extends StreamPlayer


func _ready():
   self.play()

 

You don’t actually need code to accomplish this.  If you want the StreamPlayer to play it’s song automatically, you can simply set the Autoplay property:

image

 

Now one really common thing to do in games is to play a different song after the current song finished playing… let’s take a look at how you can accomplish this:

 

extends StreamPlayer

var song1
var song2
var currentSong = song1

func _ready():
   set_process(true)
   song2 = load("song2.ogg")
   
func _process(delta):
   if(self.is_playing() != true):
      if(self.get_stream() == song1):
         self.set_stream(song2)
      else:
         self.set_stream(song1)
      self.play()

 

 

The Video Version

 

Programming


GFS On YouTube

See More Tutorials on DevGa.me!

Month List