Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

27. February 2015

 

In this tutorial, we look at animating sprites using the Animation class.  We look at loading sprites two different ways.  First creates them by splitting up a Texture loaded into memory.  The second example uses a texture atlas.  As always the code is provide below.

 

You can watch the video in HD here.

 

 

The Source

 

Example 1:

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class AnimationDemo extends ApplicationAdapter {
   SpriteBatch batch;
   Texture img;
   TextureRegion[] animationFrames;
   Animation animation;
   float elapsedTime;
   
   @Override
   public void create () {
      batch = new SpriteBatch();
      img = new Texture("walkcycle.png");

      TextureRegion[][] tmpFrames = TextureRegion.split(img,256,256);

      animationFrames = new TextureRegion[4];
      int index = 0;

      for (int i = 0; i < 2; i++){
         for(int j = 0; j < 2; j++) {
            animationFrames[index++] = tmpFrames[j][i];
         }
      }

      animation = new Animation(1f/4f,animationFrames);
   }

   @Override
   public void render () {
      elapsedTime += Gdx.graphics.getDeltaTime();
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      batch.begin();
      batch.draw(animation.getKeyFrame(elapsedTime,true),0,0);
      batch.end();
   }
}

 

Example 2:

package com.gamefromscratch.com;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;

public class TextureAtlasAnimationDemo extends ApplicationAdapter {
   SpriteBatch batch;
   private TextureAtlas textureAtlas;
   private Animation animation;
   private float elapsedTime = 0f;
   
   @Override
   public void create () {
      batch = new SpriteBatch();
      textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheets/myspritesheet.atlas"));
      animation = new Animation(1f/15f, textureAtlas.getRegions());
   }

   @Override
   public void dispose() {
      batch.dispose();
      textureAtlas.dispose();
   }

   @Override
   public void render () {
      elapsedTime += Gdx.graphics.getDeltaTime();
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      batch.begin();
      batch.draw(animation.getKeyFrame(elapsedTime,true),0,0);
      batch.end();
   }
}

Programming , , ,

24. February 2015

Unreal Engine 4.7 was released today and boy was it a good one.  In their words:

Unreal Engine 4.7 is our biggest release yet, with the power to render huge numbers of instanced objects in large worlds, beautiful rendering of leaves and foliage, HDR texture support,NewImage in-editor animation editing, along with hundreds of optimizations and improvements.

Many highly-requested features have been added: You can now assemble new actors using components right in your level, and even create your own custom component types using Blueprint visual scripting or C++! Speaking of scripting, the Blueprint Editor UI has been redesigned with a clean, unified layout. And it’s never been easier to import content in your project -- Unreal Editor now detects new asset files and imports them automatically!

HTML5 platform + WebGL is ready to use -- run your game in a compatible browser with a single click! You can also now build, cook and deploy Android devices on Mac. For virtual reality creators, new “VR Preview” feature immerses you in your world instantly from the editor. In addition, you can now access Leap Motion support if you’re building a code-based project. Finally, we now give you the full C++ engine source code in every release to make learning and debugging even easier!

 

Highlights of the update include:

  • HTML5 export ( this the biggie, Windows only though )
  • Realistic Foliage Lighting
  • Foliage Rendering for Large Worlds
  • In World Component Editing
  • Placeable empty actors
  • Blue-printable Components
  • Automatic Asset Importation
  • Redesigned BluePrint Editor UI
  • OpenEXR HDR Textures
  • Android Development on Mac
  • Full Engine C++ source and Dev Symbols installed with launcher ( big time saver )
  • VR Playback
  • Leap Motion Plugin in Beta
  • C++ Classes in Content Browser
  • Morph Target Exaggeration
  • Animation editing directly inside Persona
  • Instant Bone Controller preview
  • Record and save animations from physics simulations
  • New Project Launcher
  • Blueprint Merge tool
  • Git Source Control Plugin Beta
  • AI Perception System
  • New Tutorials
  • Paper2D Improved Map tools
  • Paper2D Flipbook collision detection
  • Custom cursor support
  • New widget binding system
  • Visual Logger for AI
  • Translucent Object ordering controls ( z sorting for 2D )
  • Desktop quality rendering on Android with OpenGL ES 3.1 (Beta)
  • DLC Packaging Beta
  • Android Movie Playback
  • Android SDK config in editor

 

WOW!  Really, just wow.  Great release Unreal!

You can read the blog post here, or the complete release notes here.

News

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 , ,

20. February 2015

 

This tutorial is available as an HD video here.

 

In this tutorial we are going to look at the UI aspects of the Godot game engine.  If you have prior experience with other game engines, you will probably be shocked by the number of UI widgets and containers that ship with Godot.  While many of these controls would never be used in a game, they are absolutely invaluable for creating tools.  Of course they are also great for making games, making implementing your UI a breeze.

 

Using Controls in Godot is just like using any other Node, although the relationship between them is where things vary the most.  Let’s take a quick look at what’s included:

image

 

All controls inherit from Control, which in turn inherits from CanvasItem, which allows it to be drawn on screen.  At the end of the day there are three categories of Controls: UI Wdigets, Containers and Popup Windows.  The containers are controls that contain other controls.  Quite often they will automatically arrange their contents for you.  Popup Windows are exactly that, dialog boxes you can display for things like messages, file selection, etc.  Then there is everything else…  these are the various widgets you can use in your application, things like Buttons, Labels and even video players.

 

Your First GUI Application

 

Let’s jump right in, show how controls work and the relationship between containers and controls.  We are going to create a simple menu where our controls are automatically laid out vertically.

 

Start out by creating a VBoxContainer, which is a box of controls that automatically arranges it’s children vertically.

Create a VBoxContainer Node:

image

 

Size it somewhat centered on your screen, like so:

image

 

Now in the Scene tab, make sure VBoxController is selected and create a new node:

image

 

Select MenuButton:

image

 

Repeat a couple times so you have multiple buttons.  Your scene hierarchy should look like this:

image

 

Next select MenuButton and in the Inspector set the Text:

image

 

You can set a number of properties that control the button’s appearance.  Keep in mind, like all other nodes in Godot, the Control inherits positional information from it’s parent container.

 

As you add text to your controls, you can see that the container automatically aligns them vertically within:

image

 

Now, what if you want to expand the labels to use the entire space available within the parent control?  That can easily be accomplished too.  For each button, go into the Inspector and drop down the Vertical setting and make sure Expand is selected:

image

Now you should see the menu laid out like this:

image

 

You may find the Font to be laughably small… so lets quickly create a new font.  We covered this in the past but a quick recap.  Select Import->Font:

image

 

Select a ttf file and save it as a fnt file, like so:

image

 

Now you can the font of each menu item using the Load option of Custom Font in the Inspector with a Button selected, like so:

image

 

After setting the font, sizes should change automatically, like so:

image

 

You need to perform this task for each Button… or…

 

Using a Theme

 

Godot has limited theming support, but in reality that mostly just means you can set a common font.  Select the VBoxContainer, locate Theme and create a new one:

image

 

Now drop it down again and select Edit:

image

This will now bring you to the theme editor window, which contains a preview of how your theme looks with various controls:

image

 

In the Inspector, select Theme->Default Font and load our font:

image

 

When happy with your theme, select Save Resource button:

image

 

Save it as a .thm file:

image

 

Now all of the controls in your container should be updated ( You may have to load the theme again using Theme->Load ):

image

 

Connecting Code to your Control

 

Now that we have our controls wired up, lets go ahead and wire them up to do something. 

 

First lets attach a script to our container.  In the Scene tab, select the VBoxController and click the new script button:

image

 

Create it using whatever settings you wish, like so:

image

 

Now select your first MenuButton and click the Connections button:

image

 

Select Pressed, then press the Connect button:

image

 

Make sure the container is selected, then press Connect:

image

 

This will create a method named _on_MenuButton_pressed in the VBoxContainer script.

 

Now edit your code like so:

image

 

Now run your game and you should see:

image

 

And if you click the first button you should see:

image

 

There are several more controls available, but the basic process of using them is nearly identical so I wont go into it.  For more details on laying out controls or more examples ( such as using pop-ups and Bitmap buttons ), be sure to watch the video tutorial as well!

 

The Video Version

 

Programming ,

19. February 2015

 

In their ongoing quest to take over the development world, Unreal have announced something really cool…  5 million dollars in grants to Unreal Developers!  Each project can receive between $5,000 and $50,000.  To be eligible you must have a working prototype.

 

So, what’s the catch?

 

None.

 

Really… nothing.  

 

Although obviously if your game rocks and sells millions and millions of copies, Unreal wins too.  Pretty awesome really.   The entire blog post follows:

 

Since Unreal Engine 4’s launch, we’ve been amazed at the groundswell of cool projects in development by the Unreal community. One thing we’ve heard many times: While development can be fueled by creativity and determination alone, finishing and releasing a commercial project often requires money.

We know this firsthand, as Epic’s early projects were built on shoestring budgets funded by such sources as Tim Sweeney’s lawn-mowing earnings, and Mark Rein’s credit card (before they took it away from him!). A small budget can make all the difference in shipping a project with the content, marketing materials, and promotional expenses necessary for it to gain traction.

So, Epic Games has created a $5,000,000 fund to provide grants ranging from $5,000 to $50,000 to select projects being built with and around Unreal Engine 4. Any project that has reached the “working prototype” stage of development is eligible for nomination, and all nominations will be considered based on merit.

The best part? There are absolutely no strings attached. Your project remains yours; you own your IP and publishing rights and you can spend any grant funds however you like. Epic’s goal is simply to help UE4 developers succeed because when you succeed, we succeed.

Unreal Dev Grants are open to games of all kinds on all platforms from developers anywhere in the world, and to cool non-game projects as well.  

If you have or know of a UE4 project which is up and running, nominate it for an Unreal Dev Grant by visiting Unreal Dev Grants information page, or stop by Epic’s booth #1024 South at GDC. Grants will be considered based on a review of a working prototype of the project, and will be awarded over time as the cool stuff rolls in!

News

Month List

Popular Comments