Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

9. May 2012

 

I logged in to my Safari account this morning as part of my daily ritual to check which newbookcover books have been added and I discover they’ve added Beginning iOS 3D Unreal Games Development.  So what’s so special about this book?  Well, there are a couple of things… First off, although there are a half dozen books on using UDK on the market, this is to my knowledge the first book focused specifically on mobile, the area I am most interested in.  Second, I’ve been meaning to look closer into the Unreal engine and this book looks intriguing.  So this book has certainly been added to my reading list.

 

For those of you that don’t yet have a Safari account, the book is also available on Amazon.com and is shockingly inexpensive right now.  It’s currently $24.34 for the dead tree version and $17.59 for the kindle version.  If only all tech books were priced like this I wouldn’t have to subscribe to Safari! Smile

 

Anyone out there doing mobile development with UDK?  I would be curious to hear what your experiences have been.

General

7. May 2012

 

As the title suggests, this thread is going to be about using sprite sheets with PS Studio.  For those of you unfamiliar with the term, a spritesheet is a single image with multiple sprites.  You generally group your sprites together on a single sheet as it is much more efficient for loading and generally performs better than loading one texture per sprite.

 

EDIT(5/11/2012): If you are working with an actual Vita device and using the beta SDK, there is a bug on the Vita XML that prevents this from working. Read this post for a simple workaround. Hopefully in time Sony fixes this and you no longer need to apply the bug fix. Note, the problem only occurs on an actual device.

 

Instead of showing you how to generate a spritesheet, I am going to recycle a previous post I made on creating a spritesheet using Daz3D.  Fortunately Daz Studio is still available for free if you want to follow along.  Of course you can create your spritesheet however you want, or can simply download a freely available spritesheet such as those available at opengameart.org.  Or of course you can just use my sheet which will be available later.

 

In this example, I am going to use a different program than the GIMP for assembling the spritesheet.  The end result of my Daz tutorial is a directory full of 128x96 images like these:

 

Walk_left00Walk_left01Walk_left02

 

You can download a zipped copy of the sprites I rendered right here.

 

I generated 19 frames of walking animation in each direction.  This time I am going to use the free version of the tool TexturePacker to generate my sheet.  Download and fire up TexturePacker and you will be greeted with this interface:

 

image

 

The first thing you want to do is add your sprites to the sprite palette. You can either drag and drop the folder ( using Windows Explorer ) containing your sprites to the sprite panel on the right or hit the Add Sprites button and select the sprites individually.  Add all of the sprites you just created in Daz3D ( or the folder you downloaded and unzipped ) using either method.  Dropping a folder will automatically add those sprites in a folder by that name keeping things a bit more organized.  Here is the results of me dropping my walkCycle folder on the sprites panel:

 

image

 

As you can see, it added all of the sprites under a folder named WalkCycle and automatically layed out our sprite sheet as efficiently as possible.  As this point though, we don’t really care all that much about efficiency, so we are going to make a few small changes.  In the Texture Settings panel we want to fill in a couple options.  First drop down DataFormat and change it to “Generic XML”.  Next, under Data File, pick a directory and filename to save your sprite sheet, I choose c:\temp\walk.xml.  This will automatically set the texture file to c:\temp\walk.png.  Otherwise, these are the settings I used:

 

image

 

 

You of course can use whatever settings you want, but if you want exactly the same results as me, use the above.  Now that you are ready, hit the publish button.

image

 

The end result is a PNG file and an XML document. 

 

The resulting image file:

 

walk

 

You can download the generated image file here.

 

It also generated an XML file with all of the sprite details.  The contents of that XML file look like:

 

<?xml version="1.0" encoding="UTF-8"?> <!-- Created with TexturePacker http://texturepacker.com--> <!-- $TexturePacker:SmartUpdate:a6e51795dbe6b13cd639951a1f67241c$ --> <!--Format: n => name of the sprite x => sprite x pos in texture y => sprite y pos in texture w => sprite width (may be trimmed) h => sprite height (may be trimmed) oX => sprite's x-corner offset (only available if trimmed) oY => sprite's y-corner offset (only available if trimmed) oW => sprite's original width (only available if trimmed) oH => sprite's original height (only available if trimmed) r => 'y' only set if sprite is rotated --> <TextureAtlas imagePath="walk.png" width="512" height="960"> <sprite n="Walk_left00" x="0" y="0" w="128" h="96"/> <sprite n="Walk_left01" x="128" y="0" w="128" h="96"/> <sprite n="Walk_left02" x="256" y="0" w="128" h="96"/> <sprite n="Walk_left03" x="384" y="0" w="128" h="96"/> <sprite n="Walk_left04" x="0" y="96" w="128" h="96"/> <sprite n="Walk_left05" x="128" y="96" w="128" h="96"/> <sprite n="Walk_left06" x="256" y="96" w="128" h="96"/> <sprite n="Walk_left07" x="384" y="96" w="128" h="96"/> <sprite n="Walk_left08" x="0" y="192" w="128" h="96"/> <sprite n="Walk_left09" x="128" y="192" w="128" h="96"/> <sprite n="Walk_left10" x="256" y="192" w="128" h="96"/> <sprite n="Walk_left11" x="384" y="192" w="128" h="96"/> <sprite n="Walk_left12" x="0" y="288" w="128" h="96"/> <sprite n="Walk_left13" x="128" y="288" w="128" h="96"/> <sprite n="Walk_left14" x="256" y="288" w="128" h="96"/> <sprite n="Walk_left15" x="384" y="288" w="128" h="96"/> <sprite n="Walk_left16" x="0" y="384" w="128" h="96"/> <sprite n="Walk_left17" x="128" y="384" w="128" h="96"/> <sprite n="Walk_left18" x="256" y="384" w="128" h="96"/> <sprite n="Walk_right00" x="384" y="384" w="128" h="96"/> <sprite n="Walk_right01" x="0" y="480" w="128" h="96"/> <sprite n="Walk_right02" x="128" y="480" w="128" h="96"/> <sprite n="Walk_right03" x="256" y="480" w="128" h="96"/> <sprite n="Walk_right04" x="384" y="480" w="128" h="96"/> <sprite n="Walk_right05" x="0" y="576" w="128" h="96"/> <sprite n="Walk_right06" x="128" y="576" w="128" h="96"/> <sprite n="Walk_right07" x="256" y="576" w="128" h="96"/> <sprite n="Walk_right08" x="384" y="576" w="128" h="96"/> <sprite n="Walk_right09" x="0" y="672" w="128" h="96"/> <sprite n="Walk_right10" x="128" y="672" w="128" h="96"/> <sprite n="Walk_right11" x="256" y="672" w="128" h="96"/> <sprite n="Walk_right12" x="384" y="672" w="128" h="96"/> <sprite n="Walk_right13" x="0" y="768" w="128" h="96"/> <sprite n="Walk_right14" x="128" y="768" w="128" h="96"/> <sprite n="Walk_right15" x="256" y="768" w="128" h="96"/> <sprite n="Walk_right16" x="384" y="768" w="128" h="96"/> <sprite n="Walk_right17" x="0" y="864" w="128" h="96"/> <sprite n="Walk_right18" x="128" y="864" w="128" h="96"/> </TextureAtlas>

 

You can download the xml file here. This XML file contains the details about how our original sprites are arranged within the sprite sheet and will prove useful in a moment.

 

Alright, now that we have our spritesheet and our sprite map XML file, lets fire up PSSuite and get down to some coding.  This tutorial assumes you have already gone through my earlier tutorials, at the very least the two Hello World tutorials.

 

Now create a new solution in PlayStation Studio, I called mine SpriteSheet.  We need to add a couple of references right away, add a reference to GameEngine2D, System.Xml and System.Xml.Linq. Now add your spritesheet png and xml files to the project, right click them and set their build action to content.

 

 

First we are going to create our gameloop in AppMain.cs.  I want to point something out right away… this is not the way you handle game events!  So the way things are done in this example are *NOT* the way we will do things in the future.  I went this route because you are already familiar with most of the code here.  In a (very near) future tutorial, I will show the “proper” way to handle updating game objects.

 

With that warning in place, lets take a look at AppMain.cs

 

using System; using System.Collections.Generic; using Sce.Pss.Core; using Sce.Pss.Core.Environment; using Sce.Pss.Core.Graphics; using Sce.Pss.Core.Input; using Sce.Pss.HighLevel.GameEngine2D; namespace SpriteSheet { public class AppMain { private static Walker walker; public static void Main (string[] args) { Director.Initialize(); Director.Instance.GL.Context.SetClearColor(255,255,255,0); walker = new Walker("walk.png","walk.xml"); var scene = new Scene(); scene.Camera.SetViewFromViewport(); var sprite = walker.Get("Walk_left00"); sprite.Position = scene.Camera.CalcBounds().Center; sprite.CenterSprite(); sprite.Scale = new Vector2(2,2); scene.AddChild(sprite); Director.Instance.RunWithScene(scene,true); System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); int spriteOffset = 0; timer.Start(); bool walkLeft = true; while(true) { if(timer.ElapsedMilliseconds > 100f) { string spriteName; if(walkLeft) spriteName= "Walk_left" + spriteOffset.ToString("00"); else spriteName= "Walk_right" + spriteOffset.ToString("00"); sprite.TileIndex2D = walker.Get (spriteName).TileIndex2D; if(spriteOffset >= 18) { spriteOffset = 0; walkLeft = !walkLeft; } else spriteOffset++; timer.Reset(); timer.Start(); } Sce.Pss.HighLevel.GameEngine2D.Director.Instance.Update (); Sce.Pss.HighLevel.GameEngine2D.Director.Instance.Render(); Sce.Pss.HighLevel.GameEngine2D.Director.Instance.GL.Context.SwapBuffers(); Sce.Pss.HighLevel.GameEngine2D.Director.Instance.PostSwap(); } } } }

Click here to download AppMain.cs

 

Most of the concepts in this code we’ve seen in a previous tutorial, so I will only highlight the new details.  First thing is we declare a Walker object, this is a class we are going to create shortly that is going to handle our sprite sheet.  As you can see, the Walker constructor takes the file name of the sprite texture and xml file you created earlier as parameters. 

 

Most of the remainder of this initial code is a matter of setting up our scene and sprite objects just like we did in Hello World.  A key difference is we are getting the sprite from our walker object instead of creating it from scratch or loading it from file.  The line:

sprite.Scale = new Vector2(2,2);

Is simply to double the size of our sprite in the viewport to see it better, you can easily remove this if you wish.

 

We create a Stopwatch ( a .NET object ) and start it counting up, then enter our infinite game loop.  Lets take a look at the new logic in our game loop

 

if(timer.ElapsedMilliseconds > 100f) { string spriteName; if(walkLeft) spriteName= "Walk_left" + spriteOffset.ToString("00"); else spriteName= "Walk_right" + spriteOffset.ToString("00"); sprite.TileIndex2D = walker.Get (spriteName).TileIndex2D; if(spriteOffset >= 18) { spriteOffset = 0; walkLeft = !walkLeft; } else spriteOffset++; timer.Reset(); timer.Start(); }

 

This is basically the “guts” of our game loop.  What we are doing here is waiting for the timer to reach 1/10th of a second.  Every tenth of a second we want to move on to the next frame of animation.  However we have only 19 ( walk_left00 to walk_left18 ) frames of animation in each direction and once we hit the end of our walk cycle, we want to walk in the other direction.  So what we do here is loop through each frame of animation until we hit walk_left18 or walk_right18, at which point we flip directions by inverting the value of the walkLeft bool.  This results in changing the spriteName text prefix, otherwise we simply increment to the next frame.  Then we start our timer over again to begin the process again a tenth of a second later.  One more time, this is not the proper way to handle updates!

 

The key line in all of that was:

sprite.TileIndex2D = walker.Get (spriteName).TileIndex2D;

 

This line actually tells our sprite to refer to a different sprite within our spritesheet, causing the animation.  That will make more sense in a second when we look at the code for Walker.cs.  Speaking of which, lets create it now!

 

To create a new cs file we either click the New icon ( image) or hit CTRL + N.  In the resulting dialog select General on the left, Empty Class on the right and name it Walker.cs, like such:

 

image

 

Now open up Walker.cs and enter the following code:

 

using System; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Collections.Generic; using Sce.Pss.Core.Graphics; using Sce.Pss.HighLevel.GameEngine2D; using Sce.Pss.HighLevel.GameEngine2D.Base; namespace SpriteSheet { public class Walker { private TextureInfo _textureInfo; private Texture2D _texture; private System.Collections.Generic.Dictionary<string,Sce.Pss.HighLevel.GameEngine2D.Base.Vector2i> _sprites; public Walker (string imageFilename, string imageDetailsFilename) { XDocument doc = XDocument.Load ("application/" + imageDetailsFilename); var lines = from sprite in doc.Root.Elements("sprite") select new { Name = sprite.Attribute("n").Value, X1 = (int)sprite.Attribute ("x"), Y1 = (int)sprite.Attribute ("y"), Height = (int)sprite.Attribute ("h"), Width = (int)sprite.Attribute("w") }; _sprites = new Dictionary<string,Sce.Pss.HighLevel.GameEngine2D.Base.Vector2i>(); foreach(var curLine in lines) { _sprites.Add(curLine.Name,new Vector2i((curLine.X1/curLine.Width),9-(curLine.Y1/curLine.Height))); } _texture = new Texture2D("/Application/" + imageFilename,false); _textureInfo = new TextureInfo(_texture,new Vector2i(4,10)); } ~Walker() { _texture.Dispose(); _textureInfo.Dispose (); } public Sce.Pss.HighLevel.GameEngine2D.SpriteTile Get(int x, int y) { var spriteTile = new SpriteTile(_textureInfo); spriteTile.TileIndex2D = new Vector2i(x,y); spriteTile.Quad.S = new Sce.Pss.Core.Vector2(128,96); return spriteTile; } public Sce.Pss.HighLevel.GameEngine2D.SpriteTile Get(string name) { return Get (_sprites[name].X,_sprites[name].Y); } } }

Click here to download Walker.cs

 

Our Walker class is in charge of loading and handling our spritesheet.  TextureInfo and Texture2D you have already been exposed to and in this case, nothing is different here.  Next up we declare a Dictionary of <string,Vector2i> named _sprites.  The Vector2i type is declared in GameEngine2D.Base and is simple a pair of ints. _sprites is used to store the x,y location of each individual sprite in our spritesheet, accessed by the sprites filename.

 

Let’s take a look first at the constructor.  This code is pretty straight forward if you have ever worked with Linq or XML.  We are simply opening our XML file, the filename of which we passed in from AppMain.  Note that we added “application/” to our paths, all your files on Vita are located under this subdirectory.  Next we read the XML file and extract each <sprite> entry into a new anonymous type composed of Name, X1, Y1, Height and Width.  Name represents the file name of the source image, X1 and Y1 represent the pixel coordinates within the generated spritesheet, while Height and Width are the dimensions of the sprite within the sprite sheet.  Given that all of our sprites are the same size, these values are of little importance.

 

Now that we’ve parsed out our XML file, we populate our _sprites dictionary using these values ( minus height and width which we don’t need past this point ).  However, we don’t actually want the x and y pixel coordinates of our image, but instead the offset within the spritesheet texture.  We can determine this value by dividing the X and Y values by the sprite Width and Height respectively.  Keep in mind, this works because all our sprites are the same size ( 128x96 ) and would require different logic if you had sprites of differing sizes in your sprite sheet.  You may notice I subtract 9 from the height value… this is because GameEngine2D SpriteTile’s locations start from the bottom left instead of the top left!  I prefer top right and this is how I generated the sheet, so invert the values.  If you design your sprite sheets to start at the bottom left ( so the first frame is at the bottom left corner ), you wont need to perform this calculation.  Now you may be wondering… why 9?  Well that’s the number of sprites we have in each row on the sprite sheet (10, counting from 0 equals 9).

 

Finally we load our texture using the filename we passed in to the constructor.  Again we prepend “Application/” to our filename.  The last thing of note here is the second value in our TextureInfo constructor.  This Vector2i informs the TextureInfo the dimensions of our sprite sheet, telling it at there are 4 columns of 10 rows of sprites.  It doesn’t matter that the last row isn’t full of sprites ( there are only 2 in the spritesheets bottom row ), if you try to access them you will simply get an empty space or whatever the background colour of your spritesheet is.

 

Our destructor is nothing special, just cleans up like a good little citizen should.  Remember it’s your responsibility to dispose of any objects you own and are no longer using.  C# is garbage collected, but its still easy to run out of memory in a hurry if you don’t keep things tidy.

 

Finally we have a pair of Get() methods.  The one takes a sprite name, looks it up in our _sprite dictionary, retrieves the X and Y offset of the sprite within the texture, then passes those values into the other Get() method.  This Get() method then creates a new SpriteTile assigning it our already created _textureInfo.  Next it sets the tiles index within the texture using the passed in coordinates to represent our currently selected sprite, sets the tiles dimensions to 128x96 (pixels) and returns our sprite.  Please notice there is absolutely no error checking or handling here in order to keep things short.  You really should have a wee bit more error checking in your own code! Winking smile

 

The end result of all this activity:

 

walkcycle

 

 

Click here to download the entire project source. In addition to the full project source, the zip also includes all the image files used in this tutorial.

Programming , , , , ,

6. May 2012

 

I just ran in to one of those massive annoyances while working on another PlayStation SDK tutorial covering the SpriteTile class.

 

 

A SpriteTile is used to group multiple sprites together in a single texture.  There are literally dozens of utilities for packing sprites and every single one of them starts at the top left.  For some bizarre reason though, SpriteTile starts from the bottom left!

 

So as I was flipping through my sprite structure, the on screen results were almost inverted… this would be the reason why.  So, if you are working with SpriteTile, be aware of this!

General

4. May 2012

 

 

I have to say, Nathan does quick work, much faster than I do! Smile

 

As I said in this earlier post Nathan volunteered to port my SFML C++ tutorial to SFML 2.0.  Well, he is done.  So in addition to the 1.6 projects, you can now download source for SFML 2.0.

 

Keep in mind, the instruction are still for 1.6, that hasn’t changed, but you can now see code for either version.  Shortly I will edit the tutorial posts themselves to include the new download option, but for now you can download the 2.0 version sources here.  Part 8 does not include the FMOD sources, which were for demonstration purposes only and made the project quite a bit larger.

 

GameFromScratch C++ Edition SFML 2.0 downloads:

Part 6

Part 7

Part 8

Part 9

 

 

While he was porting, he ran into and reminded me of a bug that I encountered and Ninja-edited for future versions.  You may find that on occasion the ball disappears completely, at least in versions before part 9.  That was because GameBall used a counter from when the game started, instead of when play started.  So if you took a while to start the game, the ball could actually move on its own ( and off screen ).  The fix was a fairly simple flag I added in part 9.  For the fix details, take a look at the first few lines of GameBall::Update().

 

Thanks again Nathan.

Programming , ,

2. May 2012

 

I decided to take a quick look at the RIM Gameplay SDK I mentioned a few days ago.  I haven’t really gotten much into coding with it, but I have to say WOW did it ever get up and runningimage quickly.  Cross-platform gaming libraries normally require a number of hoops be jumped through before you get anywhere ( see PlayN for example ).  With GamePlay I was up and going in about 15 minutes, 10 of those was waiting for my computer to compile the source.

 

 

Here’s the process.

 

Head over to Github and download gameplay.  I used the zip link shown below:

image

https://github.com/blackberry/GamePlay/zipball/master

 

Extract that archive somewhere.

 

In the archive, find and double click gameplay-newproject.bat.

Now you will be asked a series of questions, all pretty straight forward.

 

I personally answered: GamePlayTest, GamePlayTest, GamePlayTest, com.gamefromscratch.GamePlayTest, Bob Dole,MyTestGame.

 

Finally when asked for a path, I entered c:\temp.  The following directory structure is created:

 

image

 

 

Open up TestGamePlay.vcxproj, or whatever your version is called.

 

Now is the only tricky part, add a reference to the gameplay library.  In Solution Explorer, right click the Solution->Add->Existing Project…

 

image

 

Navigate to directory you unzipped gameplay, open the subdirectory gameplay and choose gameplay.vxcproj and click Add.

 

image

 

Now right click your game project in Solution Explorer and select Project Dependencies…

 

image

 

In the dialog, make sure gameplay is checked then click OK.

 

image

 

You are now done.  Now hit CTRL + SHIFT + B to build, and go grab a cup of tea.

 

Gameplay will have created the following game cpp to get started with consisting of the following code:

 

//#include "MyTestGame.h" // Declare our game instance MyTestGame game; MyTestGame::MyTestGame() : _scene(NULL) { } void MyTestGame::initialize() { // Load game scene from file Bundle* bundle = Bundle::create("res/box.gpb"); _scene = bundle->loadScene(); SAFE_RELEASE(bundle); // Set the aspect ratio for the scene's camera to match the current resolution _scene->getActiveCamera()->setAspectRatio((float)getWidth() / (float)getHeight()); // Get light node Node* lightNode = _scene->findNode("directionalLight"); Light* light = lightNode->getLight(); // Initialize box model Node* boxNode = _scene->findNode("box"); Model* boxModel = boxNode->getModel(); Material* boxMaterial = boxModel->setMaterial("res/box.material"); boxMaterial->getParameter("u_lightColor")->setValue(light->getColor()); boxMaterial->getParameter("u_lightDirection")->setValue(lightNode->getForwardVectorView()); } void MyTestGame::finalize() { SAFE_RELEASE(_scene); } void MyTestGame::update(long elapsedTime) { // Rotate model _scene->findNode("box")->rotateY(MATH_DEG_TO_RAD((float)elapsedTime / 1000.0f * 180.0f)); } void MyTestGame::render(long elapsedTime) { // Clear the color and depth buffers clear(CLEAR_COLOR_DEPTH, Vector4::zero(), 1.0f, 0); // Visit all the nodes in the scene for drawing _scene->visit(this, &MyTestGame::drawScene); } bool MyTestGame::drawScene(Node* node) { // If the node visited contains a model, draw it Model* model = node->getModel(); if (model) { model->draw(); } return true; } void MyTestGame::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex) { switch (evt) { case Touch::TOUCH_PRESS: break; case Touch::TOUCH_RELEASE: break; case Touch::TOUCH_MOVE: break; }; }

 

 

And:

 

#ifndef MyTestGame_H_ #define MyTestGame_H_ #include "gameplay.h" using namespace gameplay; /** * Main game class. */ class MyTestGame: public Game { public: /** * Constructror. */ MyTestGame(); /** * @see Game::touchEvent */ void touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex); protected: /** * @see Game::initialize */ void initialize(); /** * @see Game::finalize */ void finalize(); /** * @see Game::update */ void update(long elapsedTime); /** * @see Game::render */ void render(long elapsedTime); private: /** * Draws the scene each frame. */ bool drawScene(Node* node); Scene* _scene; }; #endif

 

 

The results of this code (although animated):

 

capture_002_02052012_210105_138

 

 

That code is Windows only at this point, but the BAT file created XCode and Android projects for easily compiling for iOS and Android respectively.

 

That was a remarkably simple process.  Zero to spinning cube in 10-15 minutes (3/4 of it waiting for my compiler), I’m impressed.  They have done a very good job of making it the kind of product you can just jump into.  Now to jump into the code a bit more and see if I stay impressed.

 

 

A Quick look around the SDK

 

 

external-deps is where all the libraries gameplay depends on are located.  By the way, those libraries are bullet, collada-dom, freetype2, glew, libpng, oggvorbis, openal, pcre and zlib.

 

gameplay directory is where the gameplay library itself resides.  We linked to it earlier as a project dependency.

 

In the gameplay-api folder, there is gameplay.html which contains the system generated HTML class library references.

 

In gameplay-docs are the development guide, and three sample tutorials ( longboard, spaceship and character ) in rtf and pdf formats.  Longboard is a skateboarding game controlled using the motion controls, spaceship is a 2D sidescroller that is actually 3D and character is a 3D scene, that is mostly about demonstrating the 3D pipeline (using Maya ).

 

Longboard:

image

Spaceship Tutorial:

image

Character Tutorial:

image

 

gameplay-encoder contains the project for the gameplay-encoder, which is the utility used to encode assets in the gpb format.  See the Character tutorial for more details on how this utility works.

 

gameplay-samples contains all three tutorial projects I mentioned earlier, as well as a mesh and particle sample.

 

 

Again, nice work overall.

Programming

Month List

Popular Comments