# Question
Title: Engine programming, is it supposed to be enjoyable?
*Now this might sound like a silly question and I apologize if this sort of question is not suited for stackexchange. But I am genuinely wondering this, and I feel like I get alot more proffesional awnsers on here.*

I'm getting into game development and have only worked solo since my study is not primairly about games. I'm only interested at 2D games atm, so am not really in need of any external engines for physics and rendering and such. So usually write the engines myself.

I absolutely hate writing things as quadtree's and pathfinding algorithims, most of the time I wish I could just skip those parts and move on to programming the actual gameplay elements. Things that happen in the background don't really interest me at all. But at the same time, I can't stand it I don't know whats/how everything is happening in the background.

My dislike might be explained by my weak mathematical skills. My motivation gets me through, but it can take alot of time before I grasp the technical solution behind a problem.

---

Now is it normal to have such a dislike towards engine programming? Or do you (people who also work solo) enjoy programming the engine?

# Answer
It's not supposed to be enjoyable if you don't like it... I mean it's not the most rewarding part of the job. You don't see the results immediately, there are more "interesting things" that you could be creating right now...

If you feel that way then yes it's normal, you are simply not an engine guy. You are attracted to the creative part of video games dev, not the engineering ;)

I don't mean that engine work leaves no room for creativity... to the contrary! I enjoy it from time to time. But wen you like visuals and interactions, it's not the most rewarding part that's it.
> 3 votes

# Answer
Different programmers are interested in different kinds of programming. I'm just the opposite to you - I love doing the low-level "systems" stuff, but I'm bored by coding gameplay mechanics, player controls, AI etc. It takes both engine coders and gameplay coders as well as others to make a well-rounded team.

If you're working on your own I'd recommend learning to use an off-the-shelf engine. You'll save a lot of time and jump right to the things that interest you. If you're curious about how some feature works, you can always poke around in their code to get an idea what's going on, but you don't need to understand every last detail the way you would to write it yourself.
> 3 votes

---
Tags: software-engineering
---


# Question
Title: XNA: Perform Collision Detection Against 3D Scene Geometry
How would one perform collision detection between a simple scene like the one below and a simple object like a sphere?

I assume the best solution would involve convex hulls in some way but I have no idea how that works (still learning :)

# Answer
> 1 votes
If the terrain is fixed you can do some precalculations to cut down on the problem size. For example, for each sector (pick reasonable sizes to work with) you can define a guaranteed-clear altitude. Each object also has a maximum object height variable.

If the object position - object height is greater than the known safe altitude then no further checks need to be done. This won't do anything about your worst time but if you have a lot of moving objects that are mostly clear of the terrain then it will do a lot for your average time.

# Answer
> 0 votes
For simple scenes, use an aggregate of geometric primitives for collision testing. Your example can be broken down into a finite plane, box and rectangular prism. Since the only object interacting is a single sphere, your testing can be kept very simple. If your scene is considerably larger, an quadtree or octree approach to organizing collision shapes is sufficient enough and can ensure that you only test what is close to the sphere.

Convex hulls would apply to the moving sphere, for representing the space that the sphere moves within a given time frame. This space is best envisioned as a short capsule with round ends. For collision detection, you can break this into one cylinder and two half-spheres and test for those.

Going back to the quadtree, you will first recursively check which leaves/nodes the *capsule shape* is occupying, not the sphere (capsule-box intersection). Then iterate through the collision shapes that are in them and do a test case for each.

It's probably not the most efficient method for collision checking (sweep and prune handle many more scenarios) but for one sphere this is good enough.

# Answer
> 0 votes
I use Mogre3D, but I think this could work in XNA as well.

Use a raycast that is cast downward, check where the ray hits the poly or face so that your character does not fall through the level.

Don't start the ray for very high, just something above your character, so the character can still walk under a bridge or something.

If you are using high detailed scenes, try creating a very low poly mesh that you can use with your ray, so that the performance is improved greatly.

Then for doodads, or scene objects, use a collision sphere, some kind of fixed radius or bounding box when running around your character.

For speeding up the loading of your game, you could already pre-calculate the triangles of the scene mesh.

Hope this helps.

T.

---
Tags: xna, 3d, collision-detection
---


# Question
Title: Why unity crashes when using shell32 in unity3d?
I'm using shell 32 to get some file descriptions. It works perfect in Visual Studio 2010, but when it comes inside unity3d it crashes.

The code is:

```
using Shell32;

ShellClass shell = new ShellClass();
Folder objFolder = shell.NameSpace(path);

string fileTitle = objFolder.GetDetailsOf(objFolder.Items().item(0),21); //Crash on this line

```

I appreciate your help.

# Answer
Using Shell32 isn't portable.

Have you tried using the .net equivalents?

http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.aspx
> 3 votes

# Answer
Yes, use the System.IO; namespace

there you have multiple interesting methods like

File.Exists(...) Directory.Exists( ...) Path.GetDirectoryName(...) Path.Combine(path, filename) Path.GetFileNameOnly(...)

( note: the method I wrote are not exactly correctly named, but you get the picture) :)

Cheers T.
> 2 votes

---
Tags: unity
---


title: Rendering skinned model with DirectX

text:
# Question
Title: Rendering skinned model with DirectX
I'm learning character animation with DirectX 9, and I'm new to 3D programming too.

I'm trying to use examples with my model that I'll be working with. They are from the book Character Animation with Direct3D, example 3.2 — hardware skinning.

Why loading of the Mesh and rendering works good:

Skinned version of the example code produces horrible results. (The same code works fine with the sample model that's provided with the example).

Please help me with ideas of where the mistake is. I don't have the intuition in 3D \[yet\].

...

Here is the render part of the hardware skinning:

```
void SkinnedMesh::Render(Bone *bone)
{
    if(bone == NULL)bone = (Bone*)m_pRootBone;

    //If there is a mesh to render...
    if(bone->pMeshContainer != NULL)
    {
        BoneMesh *boneMesh = (BoneMesh*)bone->pMeshContainer;

        if (boneMesh->pSkinInfo != NULL)
        {
            // set up bone transforms
            int numBones = boneMesh->pSkinInfo->GetNumBones();
            for(int i=0;i < numBones;i++)
            {
                D3DXMatrixMultiply(&boneMesh->currentBoneMatrices[i],
                                   &boneMesh->boneOffsetMatrices[i],
                                   boneMesh->boneMatrixPtrs[i]);
            }

            //Set HW matrix palette
            D3DXMATRIX view, proj;
            g_pEffect->SetMatrixArray("MatrixPalette", boneMesh->currentBoneMatrices, boneMesh->pSkinInfo->GetNumBones());

            //Render the mesh
            for(int i=0;i < (int)boneMesh->NumAttributeGroups;i++)
            {
                int mtrlIndex = boneMesh->attributeTable[i].AttribId;
                if (mtrlIndex >= boneMesh->materials.size())
                    mtrlIndex = 0;
                g_pDevice->SetMaterial(&(boneMesh->materials[mtrlIndex]));
                g_pDevice->SetTexture(0, boneMesh->textures[mtrlIndex]);

                g_pEffect->SetTexture("texDiffuse", boneMesh->textures[mtrlIndex]);
                D3DXHANDLE hTech = g_pEffect->GetTechniqueByName("Skinning");
                g_pEffect->SetTechnique(hTech);
                g_pEffect->Begin(NULL, NULL);
                g_pEffect->BeginPass(0);

                boneMesh->MeshData.pMesh->DrawSubset(mtrlIndex);

                g_pEffect->EndPass();
                g_pEffect->End();
            }
        }
    }

    if(bone->pFrameSibling != NULL)Render((Bone*)bone->pFrameSibling);
    if(bone->pFrameFirstChild != NULL)Render((Bone*)bone->pFrameFirstChild);
}

```

where shaders are:

```
//////////////////////////////////////////////////////////////////////////
//                  Character Animation with Direct3D                   //
//                         Author: C. Granberg                          //
//                             2008 - 2009                              //
//////////////////////////////////////////////////////////////////////////

//Transformation Matrices
matrix matW;
matrix matVP;

//World Light Position
float3 lightPos;

//Texture
texture texDiffuse;

//Sampler
sampler DiffuseSampler = sampler_state
{
   Texture = (texDiffuse);
   MinFilter = Linear;   MagFilter = Linear;   MipFilter = Linear;
   AddressU  = Wrap;     AddressV  = Wrap;     AddressW  = Wrap;
   MaxAnisotropy = 16;
};

//Vertex Input
struct VS_INPUT
{
     float4 position : POSITION0;
     float3 normal   : NORMAL;
     float2 tex0     : TEXCOORD0;
};

//Vertex Output / Pixel Shader Input
struct VS_OUTPUT
{
     float4 position : POSITION0;
     float2 tex0     : TEXCOORD0;
     float  shade    : TEXCOORD1;
};

//Vertex Shader
VS_OUTPUT vs_lighting(VS_INPUT IN)
{
    VS_OUTPUT OUT = (VS_OUTPUT)0;

    //getting the position of the vertex in the world
    float4 posWorld = mul(IN.position, matW);
    float4 normal = normalize(mul(IN.normal, matW));

    //getting to position to object space
    OUT.position = mul(posWorld, matVP);

    OUT.shade = max(dot(normal, normalize(lightPos - posWorld)), 0.2f);

    OUT.tex0 = IN.tex0;

    return OUT;
}

//Pixel Shader
float4 ps_lighting(VS_OUTPUT IN) : COLOR0
{
    float4 color = tex2D(DiffuseSampler, IN.tex0);
    return color * IN.shade;
}

//Lighting Technique
technique Lighting
{
    pass P0
    {
        Lighting = false;

        VertexShader = compile vs_2_0 vs_lighting();
        PixelShader  = compile ps_2_0 ps_lighting();
    }
}

//Pixel Shader
float4 ps_shadow(VS_OUTPUT IN) : COLOR0
{
    return float4(0.3f, 0.3f, 0.3f, 1.0f);
}

//Shadow Technique
technique Shadow
{
    pass P0
    {
        Lighting = false;

        VertexShader = compile vs_2_0 vs_lighting();
        PixelShader  = compile ps_2_0 ps_shadow();
    }
}

////////////////////////////////////////////////////////////////////////////

extern float4x4 MatrixPalette[35];
extern int numBoneInfluences = 2;

//Vertex Input
struct VS_INPUT_SKIN
{
     float4 position : POSITION0;
     float3 normal   : NORMAL;
     float2 tex0     : TEXCOORD0;
     float4 weights  : BLENDWEIGHT0;
     int4   boneIndices : BLENDINDICES0;
};

VS_OUTPUT vs_Skinning(VS_INPUT_SKIN IN)
{
    VS_OUTPUT OUT = (VS_OUTPUT)0;

    float4 p = float4(0.0f, 0.0f, 0.0f, 1.0f);
    float3 norm = float3(0.0f, 0.0f, 0.0f);
    float lastWeight = 0.0f;
    int n = numBoneInfluences-1;
    IN.normal = normalize(IN.normal);

    //Blend vertex position & normal
    for(int i = 0; i < n; ++i)
    {
        lastWeight += IN.weights[i];
        p += IN.weights[i] * mul(IN.position, MatrixPalette[IN.boneIndices[i]]);
        norm += IN.weights[i] * mul(IN.normal, MatrixPalette[IN.boneIndices[i]]);
    }
    lastWeight = 1.0f - lastWeight;

    p += lastWeight * mul(IN.position, MatrixPalette[IN.boneIndices[n]]);
    norm += lastWeight * mul(IN.normal, MatrixPalette[IN.boneIndices[n]]);
    p.w = 1.0f;

    //Transform vertex to world space
    float4 posWorld = mul(p, matW);

    //... then to screen space
    OUT.position = mul(posWorld, matVP);

    //Copy UV coordinate
    OUT.tex0 = IN.tex0;

    //Calculate Lighting
    norm = normalize(norm);
    norm = mul(norm, matW);
    OUT.shade = max(dot(norm, normalize(lightPos - posWorld)), 0.2f);

    return OUT;
}

technique Skinning
{
    pass P0
    {
        Lighting = false;

        VertexShader = compile vs_2_0 vs_Skinning();
        PixelShader  = compile ps_2_0 ps_lighting();
    }
}

```

# Answer
If it works with one mesh but not the other then the code and the shader are okay, the model is not.

I did skinmesh with DirtectX a Loong time ago, there were this buggy exporter from microsoft you needed to fix and compile yourself. There seems to be an unpgraded version of that one (or a new one, I don't know but it seems it works), digging around I found it should be in the DirectX 9.0 SDK Extras

What you need to do is to COMPILE the plugin and for that you'll need a compiler like MSVC and the 3dsMax SDK (if you have a typical installation of 3dsMax you won't have it (the SDK ^^), relaunch the install and install the SDK too).

This will definitely work, it's a bit cumbersome though but who knows, there might be precompiled versions out there some where but it won't work if it isn't the same version of 3dsMax...

Good luck, skinmeshes are Hell (to be nice) to get up and running flawlessly but it's so nice when they do...
> 1 votes

# Answer
Take a look at this tutorial, it may give you a hint on what you are not doing, or doing wrong

Mesh Based Bone animation in XNA
> 0 votes

---
Tags: directx9, skeletal-animation
---


# Question
Title: Would a Python game run on multiple platforms?
I have plans to write a game in Python and probably some SQL. I'm concerned about how versatile my program will be when I finish it, ideally I'd like it to run on Windows, Mac, Android, and iPhone... however I have a feeling the phones would be off-limits for this sort of thing. How would I go about writing a program that runs on multiple platforms? Is this even feasible for a beginner programmer?

# Answer
Python is pretty portable in itself (runs on many platforms), but you have to take into account the following:

* **What are the limitations of the platform you're targeting? Do you want to sell through a mobile store?**

For instance, the WP7 marketplace only allows to sell apps written in managed code (.NET). The AppStore is pretty locked down too and only allows native application written in Objective-C. Android allows running both Java and native code through the NDK. People have developed workarounds to allow running for instance JavaScript in native apps in iOS or converting Web apps to native apps
* **How portables are the libraries you want to use?**

Here's an example: **Cocos2D** is a Python library with an Objective-C port. You can build your game in Python for desktop platforms and rewrite it in Objective-C, keeping most of the structure thanks to the library. But then you only have support for desktop + iOS.

Overall, Python is not an easy fit for mobile platforms, because of lack of support. Here are three workable alternatives:

* **XNA** was created to make games for Windows, Xbox 360 and Windows Phone 7. There are two projects (MonoGame and ExEn) that allow to turn those games, with almost no modification, into iOS & Android apps. Originally these mobile options had an additional cost (due to Xamarin licensing), but as of 2015 they are now free.
* **Unity** is very portable and allows targeting almost all platforms (though there's no Linux support yet)

It's free for desktop games. They have a Pro version but for most games you can do just fine without it. There's a chart comparing the various editions for each platform: http://unity3d.com/unity/licenses
* **Web applications** (so-called HTML5) with the Canvas 2D API or WebGL run on recent browsers and smartphones. The support will only get better over time. There are many engines like the aforementioned ImpactJS or Three.JS for making 3D stuff.
> 12 votes

# Answer
PyGame says this in their About page:

> **Truly portable.** Supports Linux (pygame comes with most main stream linux distributions), Windows (95, 98, ME, 2000, XP, Vista, 64-bit Windows, etc), Windows CE, BeOS, MacOS, Mac OS X, FreeBSD, NetBSD, OpenBSD, BSD/OS, Solaris, IRIX, and QNX. The code contains support for AmigaOS, Dreamcast, Atari, AIX, OSF/Tru64, RISC OS, SymbianOS, and OS/2, but these are not officially supported. You can use it on hand held devices, game consoles, and the One Laptop Per Child (OLPC) computer.

Python itself is extremely portable, and easy enough to port to new platforms (assuming someone hasn't already done it for you). Things will get "interesting" whenever you need to access some platform-specific bits, which is where PyGame can help you, if it supports the platforms you're looking at, or you can port it.

A semi-related issue is that some distribution methods (app stores) might not allow applications that can run unknown third party code. You'll have to lock down your Python and its scripts so they can't access anything outside of the application, and possibly prevent it from running scripts that you didn't provide as part of the game.
> 3 votes

# Answer
I'm not sure about Android, but Python can't run on iPhone. Currently the best tools for deploying a game on Windows, Mac, Android, and iPhone would be to use HTML5 or Unity3D. There are a bunch of other tools that are lesser known and thus less vouched for, like Ideaworks Gamestudio.
> 1 votes

---
Tags: python, cross-platform
---


# Question
Title: SpriteBatch.Draw() rectangle is different from destinationRectangle passed in
When I ask SpriteBatch to draw a rectangle as within the following method :

```
    public static void DrawSolidRectangle(Rectangle rectangle, Color color)
    {
        // the output from this is shown in the screenshot
        System.Console.WriteLine(rectangle.ToString());
        spriteBatch.Draw(pixel, rectangle, color);
    }

```

I am getting different sized rectangles to the rectangles I am providing. This is an issue I am having after resizing the window. As you can see in the screenshots, the difference in width of the two rectangles is only 2 pixels and there is an offset of 1 pixel, while the two gray rectangular draw results clearly have greater than a 3 pixel difference in width.

screen shot of issue http://users.tpg.com.au/gavinw77//SpriteBatchIssue.jpg

Does anyone know what's going on ? Is this a known issue with SpriteBatch or the BackBuffer after resizing or what ?

# Answer
Well, this is both funny and painful because of how much time I spent trying to resolve this issue. The corruption might have been a clue. I loaded up the program tonight and the issue is non-existent now. It turned out to be a driver issue, because I have just installed the AMD Catalyst 11.10 Preview driver and haven't touched the re-sizing code. That makes sense. :)
> 1 votes

# Answer
You may need to update some viewport config so the framework/dx updates your projection transform attributes (it seems to be working with the older view/projection matrix). I don't know how XNA works, but DirectX works that way, with *normalized screen coords*, which are subject to pipeline transforms. If the view/projection transform is not updated to match your new window size, the image enlarges to sides proportional to the size change, instead of keeping absolute "pixel coordinates" (because normalized coords are relative to window size).

ID3DXSprite behaves this way at least (it seems to build matrices from viewport sizes, or swapchain sizes, not sure which one), and I believe SpriteBatch is no different in this situation, so you will have to find out how to make XNA properly apply it's screen-to-normalized-to-screen-cord transforms. This is because either the DX pipeline expects normalized coords (emulates sprites with 3d vertices and shaders) or the GPU expects to work with normalized coords, or both, instead of raw pixel coordinates.
> 2 votes

# Answer
When you resize, the backbuffer changes... so you have to recalc your control sizes...

in the game class you can subscribe to this event to recalc your controls:

```
   this.Window.ClientSizeChanged+= Recalc;

```

if you are recalculating the difference maybe due the float precission lost when you convert to int.
> 1 votes

# Answer
I still haven't resolved this issue, although I also haven't fully absorbed Pablo's suggestions. That goes a bit beyond my level perhaps. I'm starting to think though, that it's not any issue with my code, and that the spriteBatch or device simply isn't doing it's job at resizing as I expect it should be (I see that Pablo was saying this basically). To demonstrate that my back-buffer, client bounds and viewport are all in sync immediately before the spriteBatch draw call, I am outputting the width values to the window title.

Here is a screenshot of how the window looks at startup. This is the good result. screenshot showing good result http://users.tpg.com.au/gavinw77//Issue\_good.JPG Here is a screenshot of how the window looks after a few re-size's, I bring it back to the original width of 800 to emphasize the difference. This is not desirable. screenshot showing bad result http://users.tpg.com.au/gavinw77//Issue\_bad.JPG

Clearly the rectangle that the spritebatch is drawing in the second example is larger than 792 pixels, as it clearly consumes the entire client bounds.

Here's the code that gather's the info and sends the spriteBatch draw call

```
game.Window.Title =      "spriteBatch.gd.pp.BackBufferWidth="+spriteBatch.GraphicsDevice.PresentationParameters.BackBufferWidth.ToString();
        game.Window.Title += " | windows.ClientBounds= " + game.Window.ClientBounds.Width;
        game.Window.Title += " | Viewport.Width" + spriteBatch.GraphicsDevice.Viewport.Width;
        game.Window.Title += " | sb draw rect=" + rectangle.Width;

        spriteBatch.Draw(pixel, rectangle, color);

```

I just feel like either I'm doing something fundamentally wrong with my resize handling to cause it to glitch out like that, or else xna is glitching out, I simply cant locate any problem in code. As the numbers above demonstrate, everything actually looks ok. I have two different frames, both with back-buffers of 800, both with window client bounds of 800, both rendering a rectangle of 792, but they are different !
> 0 votes

---
Tags: xna, spritebatch
---


# Question
Title: How can I convert .X files from text to binary form?
Is there a tool for Linux (preferably a command-line tool) that can convert from the .x text format to the binary format? I wish to use this format with Irrlicht but the text format is loading very slowly (taking around 8 seconds to load one model), so I'm wondering if the binary format will be faster.

I have seen this question, but that seems to be asking more for pointers on learning the .x format, whereas I am specifically looking for a Linux tool.

# Answer
> 2 votes
As far as I'm aware, there is no such tool -- at least not one dedicated to this task that would run on Linux (or, for that matter, Windows -- the closest you might is `meshconvert.exe` which was part of the SDK, but even if it would run via wine it probably won't do what you need it to).

The best option is probably to use a tool like Blender to do file format conversions, or write such a tool yourself. At that point it may be better to select a different file format (as you appear to have), since .X is pretty verbose and long-in-the-tooth these days (as PatrickB noted).

---
Tags: directx, file-format, linux
---


# Question
Title: Where is ID3D10EffectShaderResourceVariable::SetResourceArray in SlimDX?
I don't know if I'm just not looking in the right place, but I can't find ID3D10EffectShaderResourceVariable::SetResourceArray anywhere in SlimDX.

Anyone have any idea how I should be calling this?

# Answer
> 2 votes
This was a bug in SlimDX; we just left the method out. It was fixed in revision 2134 and should be in the binaries for our September release (which, the name notwithstanding, was shipped in October a few days ago).

You can simply call `SetResourceArray` with an array of shader resource views on any `EffectResourceVariable` now.

---
Tags: slimdx, directx10
---


# Question
Title: How to drag my dragging object in 'game'-unity?
I have made a dragging sphere which drags, problem is how can I drag it using keyboard keys , I dont want to build it again on iphone simulator after experimenting with my code. for dragging it is not accepting mouse or any keyboard keys. Is it possible ?

# Answer
Well I did a quick search on unity forum and I found a great example Unity Drag an Object without seeing your code though, I am not 100% sure what you want.
> 7 votes

---
Tags: unity, tower-defense
---


# Question
Title: What are some current techniques for rendering deformable landscapes?
What are the current techniques than can be used for **efficiently rendering 3D heightmap-based deformable landscapes?**

For example, in the non-deformable landscape problem, ROAM used to be the way to these landscapes, but as GPUs advanced it lost favour to the newer geomipmapping/clipmaps (which is not as CPU-bound; but still had big enough wins for current generation GPUs).

Has there been any advancement in terms of deformable landscape rendering? Not only in terms of rendering, but also throughput during deform operations.

*Although I am personally targeting SM3.0/DirectX 9.0c, please don't restrict your answers to that.*

# Answer
> 4 votes
See the second slideshow here http://repi.blogspot.com/2009/01/conference-slides.html "Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)" by one of the architects of the Frostbite (2) engine. He boasts 'easy destruction' as one of the benefits of his technique and it's used in BF:BC2 and probably also in BF3.

---
Tags: terrain-rendering, terrain
---


# Question
Title: How can I solve these errors when using SimpleAudioEngine?
I want to use SimpleAudioEngine for the music in a cocos2d game I'm working on. When I import SimpleAudioEngine.h in my game layer I get syntax errors in CVPixelBuffer.h and CMFormatDescription.h.

I've created a new clean cocos2d application and imported SimpleAudioEngine and it worked just fine, thus the error is in the code of my application.

What do you think causes the errors with SimpleAudioEngine? How can I fix this?

EDIT:

Looks like the problem is with `size_t width` when creating CVPixelBuffer.

In this code:

```
CV_EXPORT CVReturn CVPixelBufferCreate(CFAllocatorRef allocator,
                                  size_t width,
                                  size_t height,
                                  OSType pixelFormatType,
                                  CFDictionaryRef pixelBufferAttributes,
                                  CVPixelBufferRef *pixelBufferOut) __OSX_AVAILABLE_STARTING(__MAC_10_4,__IPHONE_4_0);

```

It raises error for `size_t width` and saying:

```
/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks/CoreVideo.framework/Headers/CVPixelBuffer.h:183: error: expected ';', ',' or ')' before numeric constant

```

# Answer
> 0 votes
I don't understand why you're using `CVPixelBufferCreate` here?

In my cocos2d projects I use the SimpleAudioEngine like this:

```
// play effect
[[SimpleAudioEngine sharedEngine] playEffect:@"MySoundEffect.caf"];

// play background music
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"MySoundLoop.mp3"];

```

Here's the API docs if you need to know about further methods.

---
Tags: iphone, cocos2d-iphone, cocos2d
---


# Question
Title: How can I implement dialog trees into my game?
What is the best way to implement a dialog tree system in my game? I want an NPC to give the player different sets of responses, some which may only appear when the Player has an item or a previous event has occurred.

# Answer
Dialog Trees should be done using XML. You store the conditions for the responses and the response in nested trees with a reference to a script file if you need to do something more complex.

You should keep the scripts and dialog separate especially if you are putting together an RPG which has a metric ton worth of conversations. You can then use a library like simpleXML to read the XML file.

There's a similar question over on SO with an example: https://stackoverflow.com/questions/372915/game-logic-in-xml-files
> 19 votes

# Answer
I would look into a embedding a scripting language like lua or ruby and coding dialog interactions in that.

Thus a dialog script could look like:

```
switch showDialog "Why don't you just leave me along!", "Okay", "But I found your dog!"
    case 1:
        showDialog "And stay gone!"
    case 2:
        if playerHasObject "dog"
            showDialog "Thank you!"
        else
            showDialog "Liar!"

```

This also works well for coding AI and other simple things that are useful to tweak during run time. You can even add an editor built into your application that can be invoked when running in debug (or as an Easter Egg).
> 20 votes

# Answer
In the game Stendhal we use a finite state machine to implement NPCs.

The following diagram shows a little example from the how to write quests tutorial.

At the beginning, the NPC is in an IDLE state and may be walking around. A player can start a conversation by saying "hi" and the NPC will go to state ATTENDING. In this state it answers to questions about his "job" and offers some game "help". The player might ask for a quest and the NPC will go to state QUEST\_OFFERED waiting for the player to accept ("yes") or decline ("no") it.

We have defined a set of conditions that can be attached to transitions. For example completing a quest may only be possible if a PlayerHasItemWithHimCondition is met.

After a transition was executed the NPC may say some text and/or execute an action. Similar to the conditions we have defined a reusable set of actions like EquipItemAction which is used to give a quest reward to a player.

Multiple conditions can be combined using AndCondition, OrCondition and NotCondition. Usually there is a number of actions to be done on quest completion, so there is a MultipleActions class as well.

While the actual implementation in Stendhal suffers from not being translatable in other (human) languages easily, I think the general concept is good.
> 17 votes

# Answer
I think for adding in translations, you could still use XML for the logic as stated above. When you're getting into that type of complexity you should write your own dialogue tool. Your dialogue text would get stored as a key to a database that you could swap out depending on the language you'd want to display.

For example you could have:

```
<dialogue id="101" condition="!npc.carsFixed">
  <message>Localize.FixMyCar</message>
  <choices>
    <choice condition="hero.carFixingSkill > 5" priority="7" id="Localize.Sure">
      <command>hero.carFixingSkills += 1</command>
      <command>npc.carFixed = true</command>
      <command>hero.playSmokeAnimation()</command>
      <command>nextDialogue = 104</command>
    </choice>
    <choice condition="hero.carFixingSkill <= 5" id="Localize.CantFix">
      <command>nextDialogue = 105</command>
    </choice>
    <choice id="Localize.FixYourself">
      <command>npc.likesHero -= 1</command>
    </choice>
  </choices>
</dialogue>

```

You would then have the quest text renderer replace "Localize.FixMyCar" with the appropriately translated text.

Your tool would display what the player would see in a selectable language alongside the editable raw XML.

Similarly you could use something like this from the example you referenced:

```
npc.add(ConversationStates.ATTENDING,
        ConversationPhrases.QUEST_MESSAGES,
        null,
        ConversationStates.QUEST_OFFERED,
        Localization[ "BringMeABeer" ],
        null);

```

If your keys are descriptive enough not having the complete text shouldn't be an issue.

Something like this could be useful as well:

```
Localization[ "<Location>.<NPC_name>.<Dialogue_text_key>" ];

```
> 6 votes

# Answer
You can take a look at the Dlgedit tool of the Open Source RPG engine Adonthell. It's very advanced and should contain everything you need (including sources ;))
> 5 votes

# Answer
Data drive your characters with LUA scripts or even XML files. When you interact with an NPC, grab the file that is attached to it, read it in, adjust for any game variables that may have been triggered, and product the valid response.

The biggest gain from doing it this way is you can easily go in and manipulate the dialog, add new characters, etc. You also avoid mucking up your code base with special logic in handling each and every case.
> 4 votes

# Answer
If you use XML, make sure you build a small tool to edit the XML file. You'll go crazy otherwise.
> 4 votes

# Answer
If you have a pretty deep set of dialog trees, use ChatMapper. They have a fully featured free version and the tool allows you to export your dialog trees into XML. I've been using it and it's an excellent way to visualize and organize complex dialog trees.
> 3 votes

# Answer
If your dialogs are of any complexity, the most important thing you'll need for dialog implementation is a way to understand the complexity of your interaction. I recommend a Node editor of some kind to visualize this, though I don't have any good open systems to recommend.
> 1 votes

# Answer
I think , that You use your own script language for directing these type of game(if not, You should).Then expand your script for dialogs handling too.
You can work with other game variables during creation of dialogs logic. Game engines are like Lego. You programmed only bricks and script uses them. It does not matter if You make some script interpreter or compiler. But script is always useful.
> 1 votes

# Answer
Simple automaton might do:

```
(dialogueline_id, condition) -> (next_id, response)

```

It might look something like this:

```
(1, troll is hungry?) -> (2, say "troll be hungry")
(2, player has bananas?) -> (3, say "hey, you have bananas!")
(3, ) -> (-1, (say "i like bananas, i take them and eat, you may pass, bye", remove bananas, feed the troll))
(2, player does not have bananas?) -> (-1, say "go away!!!")

```

In the game You find id and try to match id and the condition.

You need to model the conditions and actions. By objects, function pointers, XML ...

Good dialogue editor will be handy too.
> 1 votes

---
Tags: fsm, npc
---


# Question
Title: Must know legal issues when releasing a game?
Alright, some day in the far future I would love to independently release my own game.

My question is, what is the minimum amount of familiarity I need with copyright law, software patents, and other forms of intellectual property in order to protect myself and property while not accidentally infringing upon another company's property?

# Answer
> 20 votes
Well, let's talk about intellectual property, since that's really where it seems like your focus is right now. Before I continue, though, I just want to briefly mention that you also want to make sure that you understand where you stand with other aspects of the law as well, things like taxes (Do you have to charge some kind of sales taxes? What sort of taxes apply to your income from the game?).

It should also be mentioned that if you are unsure you should always find a good lawyer who specializes in the field. Lawyers can be expensive, but not as expensive as the world of hurt you can be put in if you mess up.

Now, for laws on intellectual property (which would include both copyright and patent), it's a good idea to give yourself a fairly strong familiarity with it. For one thing, you don't want to accidentally steal someone else's work. For another thing, you don't want to accidentally steal the work of someone who will then proceed to sue you :D.

Copyright laws are, I think, fairly straightforward. Basically, if you didn't create it, you don't have any rights to use it. The exception, of course, being when you are given permission to use something. There is something called fair use which, in certain circumstances, allows a copyrighted work to be used when it would otherwise be considered copyright infringement, but there isn't a clear law on this, just a set of guidelines that a court can use on deciding a case. If you are creating you entire game yourself (or with a team) and not attempting to use resources you (or your team) didn't create, you should be ok with copyright in general.

Software patents are tougher, especially with the way things are going now with all of these high technology companies trying to buy up as many patents as they can. It is important to note that some technologies used in making games either are or have been patented at some point. One example that's talked about frequently is the Marching Cubes algorithm. Basically, you want to make sure you understand software patent laws for sure, and make sure you do your research on what patents might be related to what you are doing. For example, the common music file format MP3 is patented, and you're not supposed to be doing anything with MP3s in your software without getting a license for it.

The flip side of worrying about if you are accidentally going to infringe upon the rights someone else has on their intellectual property is protecting yourself. The cool thing about copyrights is that they are automatic (at least in the US, not sure about elsewhere). As soon as you create something, you own the copyright on it. Being able to prove that you created something before someone can always help. One way to do this is to register the copyright. Again, registration is not necessary, but it can help you to prove when you created something. Another option I've heard about would be to do something like mailing yourself a letter about how you created something. Then, leave it sealed and that way if the time comes that you have to defend your copyright, you have a sealed envelope that has a postmark date on it and you can prove that you created it on or before the postmark date.

Other forms of intellectual property, like trademark and patents, all have to be registered. It's probably a good idea to try to get a trademark on your game's name, your brand name if you have one, things like that.

Again, I should mention, that the safest thing to do is to talk to a lawyer who specializes or has experience in this field. (Most lawyers are not going to be an expert on every aspect of all laws, so make sure you get one that does have the experience in these laws!)

---
Tags: legal, business, copyright, intellectual-property
---


title: Wave ripple effect?

text:
# Question
Title: Wave ripple effect?
I've been working on a tower-defense game for some time now, and so far I am really satisfied with the results. However, there's one thing I'd like to add.

I've seen a video of GeoDefense for Windows Phone 7 here: http://www.youtube.com/watch?v=YhPr4A4LRPQ

Notice how (when a unit gets killed or a projectile hits a unit), the background ripples in some kind of wave effect.

How can I make an equivalent? I'm thinking that I somehow need to do it in the vertex shader, with a quad made of many vertices.

What's your call?

**Edit** It is important to note that my XNA game is not made for Windows phone, but for Windows PCs.

# Answer
> 8 votes
The problem is that XNA on Windows Phone doesn't have custom shader support - so you *can't* write a vertex shader or pixel shader. However, you can use a trick described by Catalin Zima that deforms a vertex grid to achieve the same effect.

If you are not targetting Windows Phone 7, you can use a trick that I described on my blog. Copying the relevant bits in:

These distortions require 2 images. Firstly you need the entire scene as a render target (i.e. Texture2D) as well as the distortion render target. Typically you would use a particle system to fill the distortion render target; using special distortion sprites (example below).

Each color component in the distortion target (and distortion sprites) represents the following:

* **R**: dx: X offset – f(x)=2x-1 mapping (\[0.0f, 1.0f\] to \[-1.0f, 1.0f\]).
* **G**: dy: Y offset – f(x)=2x-1 mapping.
* **B**: m: Z strength – f(x)=x mapping.

A good example of a sprite that would be used for a ripple would be:

Determining the outcome of a ripple is as simple as adding the waves together (keeping in mind the mapping you need to perform first to \[-1.0f, 1.0f\]); because waves in reality are also additive this *just works* \- you will get very good approximations of real waves.

Once you have the two render targets you can use the following shader:

```
Texture InputTexture; // The distortion map.
Texture LastTexture; // The actual rendered scene.

sampler inputTexture = sampler_state
{
    texture = <InputTexture>;
    magFilter = POINT;
    minFilter = POINT;
    mipFilter = POINT;
};

sampler lastTexture = sampler_state
{
    texture = <LastTexture>;
    magFilter = LINEAR;
    minFilter = LINEAR;
    mipFilter = LINEAR;
    addressU = CLAMP;
    addressV = CLAMP;
};

struct VS_OUTPUT
{
    float4 Position : POSITION;
    float2 TexCoords : TEXCOORD0;
};

float4 Distort (VS_OUTPUT Input)
{
    float4 color1;
    float4 color2;
    float2 coords;
    float mul;

    coords = Input.TexCoords;
    color1 = tex2D(inputTexture, coords);

    // 0.1 seems to work nicely.
    mul = (color1.b * 0.1);

    coords.x += (color1.r * mul) - mul / 2;
    coords.y += (color1.g * mul) - mul / 2;

    color2 = tex2D(lastTexture, coords);

    return color2;
}

float4 RunEffects (VS_OUTPUT Input) : COLOR0
{
    float4 color;

    color = Distort(Input);

    return color;
}

technique Main
{
    pass P0
    {
        PixelShader = compile ps_2_0 RunEffects();
    }
}

```

This is the final effect:

This technique should also work for 3D games; although you might have to dedicate more thought to the particle shader and the distortion shader.

---
Tags: xna, c#, hlsl
---


# Question
Title: Is this the right architecture for our MMORPG mobile game?
These days I am trying to design architecture of a new MMORPG mobile game for my company. This game is similar to Mafia Wars, iMobsters, or RISK. Basic idea is to prepare an army to battle your opponents (online users).

Although I have previously worked on multiple mobile apps but this is something new to me. After a lot of struggle, I have come up with an architecture which is illustrated with the help of a high-level flow diagram:

We have decided to go with client-server model. There will be a centralized database on server. Each client will have its own local database which will remain in sync with server. This database acts as a cache for storing things that do not change frequently e.g. maps, products, inventory etc.

With this model in place, I am not sure how to tackle following issues:

* What would be the best way of synchronizing server and client databases?
* Should an event get saved to local DB before updating it to server? What if app terminates for some reason before saving changes to centralized DB?
* Will simple HTTP requests serve the purpose of synchronization?
* How to know which users are currently logged in? (One way could be to have client keep on sending a request to server after every x minutes to notify that it is active. Otherwise consider a client inactive).
* Are client side validations enough? If not, how to revert an action if server does not validate something?

I am not sure if this is an efficient solution and how it will scale. I would really appreciate if people who have already worked on such apps can share their experiences which might help me to come up with something better. Thanks in advance.

**Additional Info:**

Client-side is implemented in C++ game engine called marmalade. This is a cross platform game engine which means you can run your app on all major mobile OS. We certainly can achieve threading and which is also illustrated in my flow diagram. I am planning to use MySQL for server and SQLite for client.

This is not a turn based game so there is not much interaction with other players. Server will provide a list of online players and you can battle them by clicking battle button and after some animation, result will be announced.

For database synchronization I have two solutions in mind:

1. Store timestamp for each record. Also keep track of when local DB was last updated. When synchronizing, only select those rows that have a greater timestamp and send to local DB. Keep a isDeleted flag for deleted rows so every deletion simply behaves as an update. But I have serious doubts about performance as for every sync request we would have to scan the complete DB and look for updated rows.
2. Another technique might be to keep a log of each insertion or update that takes place against a user. When the client app asks for sync, go to this table and find out which rows of which table have been updated or inserted. Once these rows are successfully transferred to client remove this log. But then I think of what happens if a user uses another device. According to logs table all updates have been transferred for that user but actually that was done on another device. So we might have to keep track of device also. Implementing this technique is more time consuming but not sure if it out performs the first one.

# Answer
> 14 votes
If it's not a "real time" game in the sense that players don't need to see the immediate result of another player's actions on a game scene then you should be fine with HTTP requests. But Keep in mind the overhead of HTTP.

That said using HTTP will not save you from designing your communication protocol with care. But if you are in charge of both the server and the client side you are lucky as you can adjust the protocol when you need it.

To synchronize between the Master DB and the Client DB you can use whatever transport protocol you have access to, HTTP or others. The important part is the logics behind the sync. For a straightforward approach, simply pool from the server all the latest changes needed by the client since the last timestamp in the client DB. Apply It to the client DB and go with that. If you have more changes on client side upload it if it's still relevant, otherwise discard.

Some games don't even use a local DB, they simply keep track of the status by pooling the relevant info from the server when needed.

If loosing local events is not acceptable then yes, you should have local storage and save to that storage as often as possible. You can try doing that before each network send.

To check for active users we used to ping with HTTP every 20 seconds on a successful game... This value went up immediately as the servers have been overloaded :( The server team did not think about success. So I would tell you to add a message or some sort of special header in your communication protocol which will let you reconfigure your clients (for ping frequency load balancing and other communication related values).

Client side validations are enough if you don't mind cheaters, hackers and other automated scripts attacking your game. The server can simply refuse your action and send an error message with some details. You handle that error message by either rolling back the local changes or by not applying them to your local storage if you can wait until the server responds to actually save the changes.

We used the command pattern in our game to allow for simple and efficient rollback of failed or invalid user actions. Commands were played locally sent to the peers or translated to the server message and then applied on the peers or checked on the server, in case of a problem the commands were unplayed and the game scene went back to the initial state with a notification.

Using HTTP is not a bad idea as, later, it will allow you to integrate very easily with Flash or HTML5 clients, it's flexible, you can use any type of server scripting language and with basic load balancing techniques add more servers later without much effort to scale your backend.

You have a lot to do but it's a fun job... So enjoy!

# Answer
> 4 votes
> What would be the best way of synchronizing server and client databases?

The easiest way is to implement the database as a single file you can transfer. If you get into trying to compare differences between databases then that's a world of pain, and I speak from experience.

Note that your server must not trust decisions that the client makes based on that local database, because the client can change it. It must exist purely for presentational detail.

> Should an event get saved to local DB before updating it to server?

No. What if the server decides the event never happened? The client shouldn't be making decisions about events anyway, because the client can't be trusted.

I notice you are also talking about the local DB in two ways: one, for "things that do not change frequently" and two, for events. These should not really be in the same database, for the reasons above - you don't want to start trying to merge or diff individual data rows in databases. For example, referential integrity becomes a problem when a client has a reference to an item which you decide to remove from the server. Or if the client changes a row and the server changes a row, which change takes precedence, and why?

> Will simple HTTP requests serve the purpose of synchronization?

Yes, providing they're fairly infrequent or small. HTTP is not bandwidth-efficient so bear that in mind.

> How to know which users are currently logged in? (One way could be to have client keep on sending a request to server after every x minutes to notify that it is active. Otherwise consider a client inactive).

If you use a transient protocol like HTTP, then that is a reasonable idea. When the server receives a message from a client, you can update the 'last seen' time for that client.

> Are client side validations enough? If not, how to revert an action if server does not validate something?

No, not at all. The client is in the hands of the enemy. How to revert an action depends entirely on what you consider an action to be and what effects it might have. The easiest route is to not implement the action at all until the server responds to allow it. A slightly trickier route is to ensure every action has a rollback capability to undo the action, and cache all unacknowledged actions on the client. When the server acknowledges them, delete them from the cache. If an action is refused, rollback each action in reverse order up to and including the refused one.

---
Tags: architecture, mmo, mobile, client-server
---


# Question
Title: Export Blender 2.59 models with animations to XNA 4
Whats the best way to export from Blender 2.59 for XNA 4? I have heard you can use the DirectX to export to .x instead of .fbx which works better with animations?

Unfortunately all the tutorials out there are a bit dated and go on about the quirks with older versions..

# Answer
Since you're open to using .fbx, you may want to check out this sorta recent article on MSDN to skin your model, add bones to it, and export the animations to XNA 4. It actually summarizes this Codeproject article but it's still up-to-date with the newer Blender 2.5 interface. However there's a gotcha because of a difference of exporting in 2.59 as shown from a comment in the CodeProject article -

> The latest Blenders FBX export does not have the "XNA Export", as this is newly included in 2.59 (Simply export to FBX, and click "XNA Strict" in the list on the left when choosing file-name)

In other words, you want to use the XNA Strict Options setting on the options list.
> 4 votes

# Answer
I just found a way to export .x files in Blender 2.59 (It doesn't seem to show up):

Open the python console by right clicking on the bottom border of the 3D view and selecting split areas. Set the new area to the python console in the tool bar at the bottom.

Type

```
import io_export_directx_x

```

then

```
io_export_directx_x.register()

```

and then the option seems to appear in the export menu under file. I don't know if it works though (you can export the file but I don't know if its actually a valid x file), there's probably a reason why you have to manually load it.

Hope it helps!
> 2 votes

---
Tags: xna-4.0, blender
---


# Question
Title: Getting errors while compiling Irrlicht for Android
I was trying to compile the Irrlicht port for Android but I continue getting errors while following these instructions.

I created a jni folder inside my project folder and the contents looked like this,

```
PROJECT/jni/Application.mk
PROJECT/jni/l.sh
PROJECT/jni/MakeAndroid.py

```

Then I went into the console and navigated to the PROJECT/jni/project/jni folder. From there I typed "ndk-build" and I got the following errors,

```
Compile++ arm    : irrlicht <= importgl.cpp
Compile++ arm    : irrlicht <= app-android.cpp
Compile++ arm    : irrlicht <= android-activity.cpp
Compile++ arm    : irrlicht <= android-receiver.cpp
Compile++ arm    : irrlicht <= CIrrDeviceAndroid.cpp
Compile++ arm    : irrlicht <= CVideoModeList.cpp
Compile++ arm    : irrlicht <= CFPSCounter.cpp
Compile++ arm    : irrlicht <= CNullDriver.cpp
Compile++ arm    : irrlicht <= COGLESDriver.cpp
Compile++ arm    : irrlicht <= COGLESTexture.cpp
Compile++ arm    : irrlicht <= COGLESExtensionHandler.cpp
Compile++ arm    : irrlicht <= CColorConverter.cpp
Compile++ arm    : irrlicht <= CImage.cpp
Compile++ arm    : irrlicht <= CImageLoaderBMP.cpp
Compile++ arm    : irrlicht <= CImageLoaderJPG.cpp
Compile++ arm    : irrlicht <= CImageLoaderPCX.cpp
Compile++ arm    : irrlicht <= CImageLoaderPNG.cpp
Compile++ arm    : irrlicht <= CImageLoaderPSD.cpp
Compile++ arm    : irrlicht <= CImageLoaderTGA.cpp
Compile++ arm    : irrlicht <= CImageLoaderPPM.cpp
Compile++ arm    : irrlicht <= CImageLoaderWAL.cpp
Compile++ arm    : irrlicht <= CImageLoaderRGB.cpp
Compile++ arm    : irrlicht <= CImageWriterBMP.cpp
Compile++ arm    : irrlicht <= CImageWriterJPG.cpp
Compile++ arm    : irrlicht <= CImageWriterPCX.cpp
Compile++ arm    : irrlicht <= CImageWriterPNG.cpp
Compile++ arm    : irrlicht <= CImageWriterPPM.cpp
Compile++ arm    : irrlicht <= CImageWriterPSD.cpp
Compile++ arm    : irrlicht <= CImageWriterTGA.cpp
Compile++ arm    : irrlicht <= COGLES2Driver.cpp
In file included from /home/cmetrolis/NetBeansProjects/MyProject/jni/project/jni/COGLES2Driver.h:44,
         from /home/cmetrolis/NetBeansProjects/MyProject/jni/project/jni/COGLES2Driver.cpp:6:
/home/cmetrolis/NetBeansProjects/MyProject/jni/project/jni/COGLES2ExtensionHandler.h:18:23: error: GLES2/gl2.h: No such file or directory

```

I cut out a ton of the errors after this, but they mostly all say "No such file or directory". Any idea what I am doing wrong?

# Answer
The problem is the Application.mk, you need at least android platform 2.0 for OGLES 2.0. In your application.mk, add this line:

```
APP_PLATFORM := android-6

```

Look at the project/default.properties:

```
target=android-8

```
> 2 votes

---
Tags: android, irrlicht
---


# Question
Title: How to detect collision with non-rectangular objects in 2D games?
Detecting collision with rectangular objects is quite easy. I am able to write simple tile based games. Now I want to learn to write non-tile based games in which objects may not be rectangular, for example, a mountain.

Suppose I want an uneven terrain with hills and mountains how do I store the shape of the terrain? Also how do I detect the collisions for such uneven objects?

# Answer
You can do it several ways:

One of which is to use a rough collision test using bounding box collision (similar to what you've been doing) then if that passes, perform a fine collision test using pixel perfect detection.

Another can be to use bounding shapes but only have them surround the area that you want to be collide-able, i.e. a hitbox, and perform intersection detection.
> 3 votes

# Answer
Shape of terrain is usually stored as array, so called "heightmap":

```
height[X][Y]

```

You can smooth or create some fractal details on it (usually when dimensions of array are small).

Don't do collisions by hand, You might run into problems with speed, penetrations ...

Use Box2D convex polygons for sidescrollers (Scorched Earth). For topdown RPG like games ODE, Havok, Newton, Bullet ... seem to have support for heightmaps, sometimes even natively.
> 0 votes

---
Tags: collision-detection
---


title: Rendering fancy particles?

text:
# Question
Title: Rendering fancy particles?
I'm making a tower-defense game for Windows (not phone) in XNA.

I've seen this video of another tower-defense game for Windows Phone that uses particle effects, which I really like. They change color, glow and density as they move away from the explosion. Really cool stuff!

http://www.youtube.com/watch?v=YhPr4A4LRPQ&hd=1

I would like a similar result (particle-wise) to the stuff in the video, however, I don't know where to start. I suppose I need to do linelist hardware instancing to achieve the result, and then update every particle position on the CPU.

Or is there a better alternative? Post your suggestions. That'd be great, thanks.

**Edit** It's the explosion particle effect that I want to implement. Not the particle effects that the projectiles leave when they fire.

# Answer
> 5 votes
What you are looking for is a particle engine. take a look at the Mercury Particle Engine on GitHub. I really like it, and recommend it. The only down side is the latest version (in source, not the release) doesn't have a working editor as of now. The rest of the it is stable though. (The release is XNA 3.1, and the version is source is 4.0)

If this engine doesn't cut it for you there are many others. You could even build your own. It isn't that hard

In a nutshell, you have a collection of Texture2Ds. With each pass you update their velocity, alpha, rotation, and scale. So if you wanted a smoke effect, create some Texture2Ds (say 5) with the same texture. Give each one a slightly different rotation, scale, alpha, and position them in a cluster. With each pass of Update, modify those properties until the particle "dies".

Looking at the video, it *looks* like they might be doing some 3D rendering to get the warp effect of the board. I would start off simple. Try to get some simple particle effects going without jumping into the 3D stuff first.

---
Tags: xna, c#, hlsl
---


title: Integration of homogenous wave

text:
# Question
Title: Integration of homogenous wave
I have a 2D matrix; each of its elements describes a homogenous coordinate in 3D wave (the values of wave coordinates are changed in time). The wave rendering is done with texture. I need to make an integration for the wave.

Does anyone have a clue? And another question; will the texture have any impact on integral calculation? p.s maybe i can do this using opengl?

# Answer
Correct me if this is no the answer you want, as the question is a little vague.

Since this is in gamedev SE I assume you want some kind of real time wave simulation, and this matrix is basically a 'height map'. There are several numerical methods for solving the *2d* wave equation (I don't think you want the 3d) and you can find thorough descriptions of the finite difference methods easily on the net. For example. However, this is very computationally expensive. So I've made a quick search for 'real time wave simulation' and found this article, which basically show you how to make waves on the shore lines and the rest is just a noise-like texture.
> 1 votes

---
Tags: 3d, mathematics, textures, matrix, coordinates
---


# Question
Title: Making the AI take different paths to each other
I have a top down 2d game where the AI spawn at the edges of the map and run towards the center.

I'm using A\* and a node mesh to do the pathfinding.

Right now, the AI spawn at a point on the edge of the map and all take the same path which is the shortest route to the center.

Now I want them to be more surprising and interesting and take different paths to each other.

I can immediately think of two ideas for doing this but wanted to know if there are other ways or better ways that people often use?

1. When one enemy spawns and generates a path to the center, temporarily increase the cost of all the nodes on that path, then slowly decrease them back down over time. Then the enemy AI that spawn later will be forced to take a wider path.
2. The above approach will lead to AI just taking a wider and wider path though and still be very predictable. So I thought I'd also introduce a number of intermediate goal nodes around the map. When the AI spawn they randomly pick one of the intermediate goals and head there first before heading to the center of the map. Combining this with the above approach of increasing the costs might look pretty good?

What approaches have people found work best to getting the AI to vary the paths they take, look convincing and surprising?

# Answer
Your second option hints at a more fundamental approach: ensuring enemies approach your player from different directions. The question is, how far do they have to travel to in order to get "around" your player? The ideal to this would be a mix of

* dynamically generating points that closely surround (i.e. follow) the player's position;
* what Nevermind has suggested in terms of randomising paths to these surrounding points, to a greater or lesser degree.

In this way, you can ensure that AI's won't take unecessarily lengthy detours just to get realistic path variation when converging on the player.

Collaborative diffusion does what you want implicitly as part of the algorithm. But it's non-trivial to implement.
> 7 votes

# Answer
As a first idea, try adding a small **random** value to each node's weight when pathfinding. This way, every agent will look for a path in a slightly different environment. I'm not sure if this will work in your case, but it should be really easy to try.
> 13 votes

# Answer
I like Nevermind's answer, however, given the limitation described in the comments this is what I would try:

1. The algorithm for a single unit to the center, record the total distance travelled.
2. For each subsequent unit allocate it a distance that is a random and small amount longer than this.
3. While doing the A\* for each unit add extra weight based on how close you are and how far you 'want' to travel. This would probably be something like `(distanceToGoal) + Max(0, desiredDistance - distanceTravelled))`.

This would make the units attempt to go further, which is probably a different path, which would result in them possibly taking different paths.

You could also just add it to your starting huerestic for each unit, but the random range would probably have to be quite a bit larger.
> 4 votes

# Answer
As pointed by Nick Wiggill the simplest approach would be to get a circle surrounding the objective.

* randomly assign a point close to this circle as a waypoint.
* eliminate all paths in the circle from the initial path (or increase dramatically the value of these points)
* then from that waypoint get the path to the objective.

The important part is to eliminate all paths in the circle for the original waypoint as you would probably end-up with enemies crossing the circle to get to their initial waypoint.

From that you can get any variant by playing with multiple values adding secondary waypoints in the circle close to the initial one etc.
> 3 votes

# Answer
Your problem here is essentially that A\* is an algorithm for finding the quickest route to a target. If that is your primary criteria for a 'good' path, then it's unsurprising that all your actors make the same decisions.

What you need to do is modify your quality criteria for the path, so that 'shortest-is-best' isn't the only factor. The element of randomness is key in this, but not so much that it detracts from the path-finding intelligence (i.e. actors take stupidly roundabout paths to the target).

A\* pathfinding is innately naive, as it usually assumes that the actor has perfect knowledge of the entire route before it starts out. That's always going to look unrealistic. The solution suggested that picked intermediate goals is a step away from that - the AI is trying to get closer to the target, but only tries to navigate in small sections at a time (this is analogous to real life where you can only navigate as far as you can see, and as you traverse more of the path, you can see further ahead).

I'd perhaps recommend a simpler way of looking at it. When you're pathfinding, don't just maintain a single best-path-I've-found-so-far. Instead, collect a set of the best 5 or 10 paths. Use a threshold to discard obvious outliers. E.g. if the best path traverses 20u to get to the target, the next best traverses 21u, and the next one after that traverses 50u. Set a threshold of 20% larger than the best path, and so discard the 50u path because it's stupidly longer. Now you have several paths to choose from, and by randomly selecting from that set of paths, your actors will make different decisions.

However you won't get this sort of information with standard A\* searching, so I think you'd have to modify the algorithm or use something else to gather the set of possible paths.
> 2 votes

# Answer
If you have a small set of recurring enemies (or enemy types), you might try to give them personalities that affect their movements. They don't have to be big things, just things that come up every now and then. A good example of this are the ghosts from Pac-Man. Have your A\* broken into several intermediary goals. Maybe one enemy is really stupid and gets lost easily, heading in a random direction every third node (other than directly backward). Be creative.
> 2 votes

---
Tags: ai, path-finding, navmesh
---


# Question
Title: How can I detect collision between a circle and a rectangle?
I'm trying to make a clone of brick breaker, one problem that I am running in to is to do with collision. I know how to detect if a collision has happened but I do not know how to check what side of the brick is hit.

Some general background from the program. all the bricks are just 2 points (x,y) a top right point and a bottom left point. The ball is just 1 point with a radius. for my current collision detection I'm checking if the ball's coordinates are at or in between the two box coordinates.

# Answer
assuming you are at a place where the ball is just contacting the brick;

You will have to create a structure that holds a point located on each edge, and a vector for each edge that is the edge's normal.

Give that structure a method that iterates through each point, creates a vector that is the difference between the ball's center & the point, dot it to the corresponding normal, and only one of the 4 results will be a positive number, that's the edge that has intersected.

pseudo code:

```
struct brick

Vector min, max, L, R, T, B; //letters repre points on edges
Vector normalLeft, normalRight, normalTop, normalBottom;

//ctor
Brick(min, max)
{
   //generate values for all the fields above
}

vector normalOfEdgeHit(Vector ballCtr)
{
   foreach(point i =  L, R, T, B)
   {
     if(Dot(ballCtr - i, normal[i]) > 0)
     {
       return normal[i];
     }

   }

}

```

in the following diagram, it would return normalB. notice how all the other normals point away from the ball (thus would return values less than 0). The points can be located anywhere on the edge, they do not need to be in the center.

It is possible to have two normals return positive when close to the corner. In that case, you must determine distance from point to line (as if the brick's edge were an infinitely long line) for both edges. Whichever is a greater distance is the edge that has intersected.
> 5 votes

---
Tags: java, collision-detection
---


# Question
Title: How do I make a turn based game for two players who play with different devices on iOS?
I only have experience in physics-based games in cocos2d.

I want to develop a turn-based game in Cocoa Touch (iOS). Two players will play this game on different devices which connect via Bluetooth or Game Center.

I'd like to know how to synchronise two devices through a Bluetooth connection.

Please tell me of any blog tutorial, guide, or sample code which will help.

# Answer
Finally I done.. I have use this blog tutorial

And do some logic with turn base.. Only maintain in this game center needs Send and Receive.. Thanks all who be a part of that.. Thanks...
> 1 votes

# Answer
Whenever I have network architecture questions, I refer to this wonderful document about how the Unreal Engine does it:

http://udn.epicgames.com/Three/NetworkingOverview.html

It's likely more than you need, but it's a great read and you'll likely be able to use concepts from it.
> 2 votes

# Answer
How you synchronize the games is going to be very different from game to game.

You just need to figure out what both clients are going to need to send across, package that up, and send it. There are some turn-based game helpers in iOS 5 that you can use to send messages back and forth.
> 1 votes

---
Tags: networking, ios, game-center
---


# Question
Title: How can realistic 3D body-part movement be implemented?
Say you create a person, monster or robot, with arms, legs, head(s) ... in 3D in a game.

How do you coordinate the body-part movement to achieve the fluidity of real living beings? Is there some theoretical base, or do you just try until it looks good enough?

To put the question in a more precise context, I haven't got some kind of advanced physics engine the would create automatically something physically correct by default.

# Answer
A possible solution to animate 3D body models of human-like actors are the rigging and skeletal animation techniques. Usually, these techniques use an skeletal motion that was captures using a MoCap technique, which basically means that the final result will look super natural because the motion data comes from "real data".

You can have a look at CMU's MoCap database, to see the range of human motions that are available, and see if they suit you.
> 2 votes

---
Tags: movement
---


title: VS deployment problems

text:
# Question
Title: VS deployment problems
I created an installer for my XNA demo in the hopes that people could just download it and use it. It runs perfectly on my computer, however on others, it installs fine, but the demo doesn't run and has to close. The included dependencies are:

DotNetFX35 WindowsInstaller3\_1 and XnaFxRedist31

The Demo also makes use of a number of text files which contain path lookup tables. Could it be that these are not being included? It seems unlikely that this is the issue though as it runs on my machine. It must be a missing dependency I think but I don't know what...

# Answer
> 1 votes
Install a clean machine to test deploy on, you're really shooting in the dark if you aren't. If you don't have another machine, install a virtual machine. Not all virtual machine solutions have drivers that support the graphics device XNA needs - but some do. And with a virtual machine you can install a trial version of Windows and make use of snapshots to revert to a clean slate every time you do new tests.

Provide useful error reports, catch crashes and display them to the end-user with an option to send and/or copy information to you. If it does automatic updates, you might want them to opt-in for automatic error and crash reports so you get a database of common problems complete with stack traces that you might want to fix. The only case where this won't work as far as I know is if .NET isn't installed on the target machine.

There's a multitude of possible issues from content pipelines not handling decimal point differences in other cultures beside the one they were compiled with to installations missing a vital file or directx and c++ dependencies. It's hard or impossible to answer your question until you've figured out why it's crashing and what the demo thinks is missing (if anything).

# Answer
> 3 votes
XNA games have the following dependencies:

* .NET Framework 3.5 Redistributable
* XNA Framework Redistributable (version depends on which version of XNA you use)

To allow people to install your games on their computers without downloading these dependencies themselves, you need to bundle or allow downloading & installing those dependencies right in your installer. There are two ways that I know of to do so, each with its own set of advantages & drawbacks:

* **ClickOnce** is the default method included in XNA Game Studio. It packages a very straightforward and pretty nice installer that will take care of installing the dependencies and puts your app under the current user's application data folder (the path is not customisable). It also means your game will only be installed for this user.

ClickOnce **only bundles the files that are part of your XNA Content project**, so external text files won't be installed. You could add them in your Content project with the Copy build action (no pipeline processing).

You can specify an URL in the Publish settings to check for updates everytime your game is launched. You can then upload updated builds of your game at this URL. A very big limitation of this is the URL has to be publicly available. If your game isn't free, then there is no way of providing automatic updates without putting the game up for anyone to download. Worse, people will have to uninstall the game before installing a new version manually, there is no manual upgrade possible. And uninstalling the game will wipe all content stored through IsolatedStorage (basically, saved games are lost).

This makes ClickOnce mostly unusable for anything but free games.
* **WiX XNA** is a preconfigured project for building a WiX installer. You'll need to install SharpDevelop (the site says 3.2 but the latest 4.1 version as of October 2011 works just fine)

It bundles the redistributables you need and check for them and install them if needed.

The only drawback is that, in order to set up your game installer, you have to:

+ generate a set of GUIDs and put them in the files
    + create an XML tag soup for each directory and file you want to include. (upside of this is: **you can decide exactly what to include, for instance files not included in Content project**)
    + the project template is not setup for supporting upgrades, but you can do so yourself. I had to look it up on StackOverflow.

It's really a shame that there is no effortless way of creating a useful installer for XNA, when building games with it is such a breeze. For my own projects I use the WiX XNA template that I customized to allow for upgrades and it took me quite a while to figure it all out.

EDIT: My original answer didn't address the part of your question about your external data files, I updated it.

---
Tags: xna, software-engineering, distribution
---


# Question
Title: Handling different version clients in a multiplayer game
What are various ways of handling different version clients in multiplayer games? For example, when there's an update, some games allow you to play with people who have a different version of the client. How is this handled?

# Answer
The first thing is that you need some way of communicating a version number, so the first thing a client should do is probably send its current version so that the server can take action accordingly. You may be able to embed the version number within another message, depending on your protocol.

Most games probably just reject older clients, and force them to upgrade first. Even if the code is unchanged, the presence of older data may mean the game is essentially unplayable. And if the underlying network protocol changes, older clients may not be able to connect at all. It's therefore useful to have a robust version check that doesn't rely directly on this protocol, otherwise people can't even connect to find out that they need to patch up.

The problem is not in allowing different versions of clients to play with each other as such, since usually all communication goes via the server. Only the server needs to worry about versioning, not each client. The developer can have the server note the version of each client and handle them accordingly.

The issue is that a new version usually implies a new or changed feature in some sense, and an old client won't have the information to be able to use that feature. The server can take care to avoid sending messages about this feature to older clients. Or, if you have a protocol that can handle it, you can send the messages anyway and the client can ignore any it doesn't understand.
> 5 votes

---
Tags: multiplayer, mmo
---


title: DirectXCollision.h missing

text:
# Question
Title: DirectXCollision.h missing
I am using DirectX10, June release and I am trying to

```
#include <DirectXCollision.h>

```

so that I can use the bounding objects, however it does not seem to be there. Am I missing something basic?

# Answer
That header is not part of D3D10 itself, but rather part of the DirectXMath library in the Windows 8 Developer Preview.
> 1 votes

---
Tags: directx, directx10
---


# Question
Title: How should I structure my classes to allow for multithreaded simulation?
In my game, there are plots of land with buildings (houses, resource centers). Buildings like houses have tenants, rooms, add-ons, et cetera, and there are several values that have to be simulated based on all these variables.

Now, I'd like to use AndEngine for the front end stuff, and create another thread to do the simulation calculations (perhaps also later include AI in this thread). This is so that one whole thread doesn't do all the work and cause problems such as blocking. This introduces the problem of *concurrency* and *dependency*.

The *currency problem* is my main UI thread and the calculation thread would both need to access all the simulation objects. So I have to make them thread-safe, but I don't know how to store and structure the simulation objects to enable that.

The *dependency problem* is that in order to calculate values, my calculations depend on other objects' values.

What would be the best way to link up my tenant object in the building with my calculations? Hard-code it into the tenant class? What is a good way to do "store" algorithms so they are easily tweaked?

A simple lazy way would be to bung everything into a class which holds all the object, such as plots of lands (who in turn hold the buildings, et cetera). This class would also hold game state such as the technology available to the user, object pools for things such as sprites. But this is a lazy and dangerous way, correct?

**Edit:** I was looking at Dependency Injection, but how well does that cope with like a class that holds other objects? i.e, my plot of land, with a building, which has a tenant and a host of other values. DI looks like a pain in the bum with AndEngine as well.

# Answer
> 4 votes
Your problem is inherently serial -- you must complete an update of the simulation before you can render it. Offloading the simulation to a different thread simply means the main UI thread does *nothing* while the simulation thread ticks (which means it is blocked).

The commonly held "best practice" for concurrency is *not* to put your rendering on one thread and your simulation on another, as you are proposing. I strongly recommend against that approach, in fact. The two operations are naturally serially related, and while they can be brute forced, it's not optimal and it *does not scale*.

A better approach is to make parts of the update or rendering concurrent, but leave updating and rendering themselves always serial. So for example, if you have a natural boundary in your simulation (for example, if houses never affect each other in your simulation) you can shove all the houses into buckets of N houses, and spin up a bunch of threads that each process one bucket, and let those threads join before the update step is complete. This scales much better and is a much better fit for concurrent design.

You're over-thinking the rest of the issue:

Dependency injection is a red herring here: all dependency injection really means is that you pass ("inject") the dependencies of an interface to instances of that interface, typically during construction.

That means if you have a class that models a `House`, which needs to know things about the `City` that it is in, then the `House` constructor might look like:

```
public House( City containingCity ) {
  m_city = containingCity; // Store in a member variable for later access
  ...
}

```

Nothing special.

Using a singleton is unnecessary (you often see it done in some of the insanely complex, over-engineered "DI frameworks" like Caliburn that are designed for "enterprise" GUI applications -- this does not make it a good solution). In fact, introducing singletons is often the antithesis of good dependency management. They also can cause serious problems with multithreaded code because they cannot usually be made thread-safe without locks -- the more locks you must acquire, the worse your problem was suited for handling in a parallel nature.

# Answer
> 5 votes
Usual solution for concurrency problems is data **isolation**.

Isolation means that every thread has its own data, and does not touch data of other threads. This way there are no problems with concurrency... but then we have problem of communication. How can these threads work together if they don't share any data?

There are two approaches here.

First one is **immutability**. Immutable structures/variables are the ones that never change their state. At first, this may sound useless - how can one use a "variable" that never changes? However, we can *swap* these variables! Consider this example: suppose you have a `Tenant` class with a bunch of fields, that is required to be in some consistent state. If you change a `Tenant` object in thread A, and at the same time observe it from thread B, thread B may see the object in inconsistent state. However, if `Tenant` is immutable, thread A can't change it. Instead, it creates *new* `Tenant` object with fields set up as required, and swaps it with the old one. Swapping is just a change to one reference, which is probably atomic, and thus there's no way to observe the object in inconsistent state.

The second approach is **messaging**. The idea behind it is that when all data is "owned" by some thread, we can *tell* this thread what to do with data. Every thread in this architecture has a message queue - a list of `Message` objects, and a messaging pump - constantly running method that removes a message from the queue, interprets it and calls some handler method. For example, suppose you tapped on a plot of land, signaling that it needs to be bought. The UI thread can't change the `Plot` object directly, because it belongs to logic thread (and probably is immutable). So UI thread constructs a `BuyMessage` object instead, and adds it to logic thread's queue. Logic thread, when running, takes the message from the queue and calls `BuyPlot()`, extracting the parameters from the message object. It might send a message back, for example `BuySuccessfulMessage`, instructing UI thread to put up a "Now you have more land!" window on screen. Of course, access to message queue must be synchronized with lock, critical section or whatever it is called in AndEngine. But this is a *single* point of synchronization between threads, and threads are suspended for a very short time, so it's not a problem.

These two approaches are best used in combination. Your threads should communicate with messages, and have some immutable data "open" for other threads - for example, an immutable list of plots for UI to draw them.

Note also that "readonly" does **not** necessarily means immutable! Any complex data structure like a hashtable can change its internal state on read accesses, so check with documentation first.

# Answer
> 4 votes
Probably 99% of the computer programs written in history used just 1 thread and worked fine. I don't have any experience of the AndEngine but it's very rare to find systems that *require* threading, just several that could have benefited from it, given the right hardware.

Traditionally, to do simulation and GUI/rendering in one thread, you simply do a bit of the simulation, then you render, and you repeat, typically many times per second.

When someone has little experience of using multiple processes, or doesn't fully appreciate what thread 'safety' means (which is a vague term that can mean lots of different things), it's too easy to introduce many bugs into a system. So personally I would recommend taking the single-threaded approach, interleaving simulation and rendering, and saving any threading for operations that you know for sure are going to take a long time and absolutely require threads and not an event-based model.

---
Tags: android, multithreading, andengine
---


# Question
Title: What should I focus on learning to get a job doing high level programming instead of low level programming?
I am in last year of college. I want to get a job in games industry as programmer but I don't want to do low-level programming. I want to do something AI and machine learning related. Am I in the wrong industry? Should I change focus to other jobs other than games industry?

By low level programming I mean, for example, connecting XNA and windows Forms or whatever. I mean I don't care about those kind of things, I want to work on higher level like doing fuzzy logic, how does the AI decide what to build in RTS and so on...

# Answer
> 6 votes
> I am in last year of college. I want to get a job in games industry as programmer but I don't want to do low-level programming. ... By low level programming I mean, for example, connecting XNA and windows Forms or whatever. I mean I don't care about those kind of things, I want to work on higher level like doing fuzzy logic, how does the AI decide what to build in RTS and so on...

As an entry-level programmer, you're going to have very limited say in what you ultimately end up getting to do -- entry level programmers are often hired as generalists.

You will likely have to spend some time doing some level of grunt work (which is more akin to your apparent definition of "low level" than is traditional); it's the nature of the beast. You are only minimally competent, at best, after college anyhow.

You can help avoid this by paying careful attention in your job interviews to the kind of work other programmers describe doing. You want to find a place where tedious grunt work like connecting forms to the game engine for editors is handled via a resuable architecture platform, and doesn't involve much programmer intervention: where tedious grunt work has been engineered out as much as possible, because the programmers know that grunt work is not intellectually stimulating and they want their fellow programmers to be intellectually stimulated.

That is, assuming you even look for a job in games, because...

> I want to do something AI and machine learning related. Am I in the wrong industry? Should I change focus to other jobs other than games industry?

...you may be barking up the wrong tree, unfortunately. The vast majority of "AI" in games is clever disguised scripting and simple, heuristics-based logic models. The games industry is most decades behind the state of the art for artificial intelligence and there is rarely any real opportunity to advance it: even the scripts are usually mostly in the hands of the designers, for maximum gameplay control.

# Answer
> 4 votes
This was going to be a comment, but it's really long enough to be an answer.

The answer is (unfortunately) **you can't avoid or minimize low-level work.** It's just impossible.

Why? Because high-level is built on low-level. There are layers of abstractions upon abstractions; but at some point, somewhere, abstractions leak or are imperfect, and you need to dig down. How far down depends on the problem. You may find CLR bugs through some third-party's application on top of another third-party's library.

Let me give you an example. You might have a web app which uses ActiveRecord, which in turn uses NHibernate, which in turn uses C#. It's possible to find issues that depend on the way the CLR was implemented on a particular architecture (eg. x64).

Plus, most likely as a developer, **if there' s a low-level bug, you will need to trouble-shoot and fix it,** because it will impede your high-level work. You can't just say "here, ask X to fix this" because you're a "high-level" developer. YOu have to get the job done, whether it's your code or some other layer of the cake that has the problem.

If I were you, I would pick a fairly high-level platform to specialize in (like XNA, or even XNA specific to X platform) and *focus on improving your debugging skills.* That will carry you very, very far.

Sorry if this is not the answer you want to hear! This is just the (sometimes sad) reality of code. It's layers, and imperfect abstractions.

# Answer
> 3 votes
Although you may be able to find a job that only requires High Level programming, it's always a plus in your resume to at least know and understand how low-level works.

Besides, even if you are applying programming on AI and high level concept, you might need from time to time to handle low level (for example optimise your AI computing with GPGPU).

# Answer
> 3 votes
As others have mentioned, your question isn't about low-level versus high-level. Let me paraphrase the question.

> Can I get a job working on only the "fun" parts of developing a game?

The sobering answer is: probably not. 95% of the jobs on the market require doing the "un-fun" parts too.(Disclaimer: 95% of statistics are made up on the spot) And the 5% of the jobs that are only fun-related are often senior-level positions. They are senior-level positions often because in order to be good at them, you need a lot of industry experience in order to make good design decisions. Note that by "experience" I include "a thorough understanding of the low-level systems you develop on."

Here's the bright side though: you can find developers who have different opinions of "fun." For example, some people love writing game engines and frameworks, but not so much writing the scripts and interaction components that you'd want to work on. You can also find ways to minimize the low-level work by using pre-built frameworks such as Unity, doing mods on other games (like DOTA), or just making technological sacrafices (Solium Infernum comes to mind, the multiplayer is Play-by-Email, and the game is written in some kind of Flash compiler)

# Answer
> 2 votes
> I want to do something AI and machine learning related. Am I in the wrong industry? Should I change focus to other jobs other than games industry?

I think so, yeah.

A typical games company has between 0 and 1 AI programmers. And if they do have a dedicated AI programmer, or someone who spends a lot of time on AI, there's hardly any chance that they're using machine learning - it's just not a branch of AI that is commonly used in games, due to being too unreliable compared to more explicit methods.

> By low level programming I mean, for example, connecting XNA and windows Forms or whatever.

That's pretty high level by many standards in the games industry: they'd think of low level as writing shaders, optimising C code, writing directly to audio buffers, etc.

I don't think you'll find much work in the games industry that doesn't have you working with graphics and input/output stuff, at least to begin with.

---
Tags: game-industry
---


# Question
Title: What's the best way to track game phases?
I'm currently writing an IRC bot in Ruby to play some kind of strategy game (it doesn't matter which), but I'm hesitating between several solutions to implement a phases system the "best" way.

The system: The game has several days; the first day some phases occur to give the players their jobs and so on, but they never occur again, so phases are sometimes conditional.

What's more, when a certain condition is met, e.g. an important player dies, a phase may be started before the next one. Phases may be added by the job system; jobs are each defined in a single file and they can define their own phases and logic.

My ideas:

* The game is handled by a class in which I can store an instance variable to remember the actual phase and handle all of the logic in the code. I don't think this is the best idea.
* Use a phases hash to store the next phase and other parameters and methods to handle each change.

Is there a better way? I don't think those I came up with are very flexible.

# Answer
To expand on my comment, this is pretty much the perfect situation to use a Finite State Machine. You've got a set of different phases based on certain conditions, and each phase is handled in a different manner (at least, I'm assuming as much based on your description). The fact that some phases only occur once shouldn't make a huge difference. Switching between phases is easily handled, simply by changing the state. Each state handles one phase, and code is separated into nicely defined classes (or functions, if you implement it that way...)

The only possible downside is, for the most part, you can only have one state active at once. It's also tricky (but not impossible) to dynamically add newly defined states, though it's entirely possible to switch between defined states (heck, it's designed for it).

I'm not familiar enough with Ruby to know exactly how to implement a FSM, but it should be easy with any language that supports polymorphism.
> 7 votes

---
Tags: ruby
---


title: Manipulating a free camera

text:
# Question
Title: Manipulating a free camera
I have a camera class in my code which stores two 4x4 matrices. One for the view matrix and one for the projection matrix. Originally, I had two floats in the class for pitch and yaw and these were updated based on keyboard and mouse input. Then on update I would do something like this to set the view matrix:

```
Matrix33 xRot = Matrix33::CreateRotationX(m_pitch);
Matrix33 yRot = Matrix33::CreateRotationY(m_yaw);

Matrix33 rot = xRot * yRot;

const Vector3& rUp = rot.GetColumn1();
const Vector3& rForward = rot.GetColumn2();

m_viewMatrix = Matrix44::CreateLookAt(m_position, m_position + rForward, rUp);
```

However, I'm now wanting to add roll to the equation but I know that if I carry on using this method I'm going to run into gimbal lock. I do have a function in my maths library to rotate about an arbitrary axis. The function definition is:

```
static Matrix33 CreateRotation(const Vector3 &rAxis, const float rad);
```

But I'm not sure, based on pitch/yaw/roll how to create the arbitrary axis to rotate around. This got me thinking that perhaps pitch/yaw/roll isn't the best way to be doing it so I thought I'd ask on here about what might be the best way? I don't even have to use CreateLookAt(), it just seemed easier at the time :)

I don't have a quaternion class yet but I could add one if that would be the best way. I think ideally I'd rather do it with just matrices for now, though.

Any help would be much appreciated.

# Answer
> 3 votes
Your arbitrary axis for the static method of rotation around an arbitrary axis are as follows:

```
Vector3& pitchAxis = rot.GetColumn0();
Vector3& yawAxis = rot.GetColumn1();
Vector3& rollAxis = rot.GetColumn2();

```

Now, if on a partcular frame, you wanted to pitch 0.01 radians, yaw 0.25 radians, and roll 0.03 radians, you could do it like this:

```
Vector3& arbitraryAxis = (pitchAxis * 0.01f) + (yawAxis * 0.25) + (rollAxis * 0.03);
float& radiansToRotate = arbitraryAxis.Length();
arbitraryAxis /= radiansToRotate;

Matrix arbRotation& = CreateRotation(arbitraryAxis, radiansToRotate);
rot = arbRotation * rot;

```

Notice you no longer keep track of overall rotation angles of the camera any more (whew!), simply determine how much you want to YPR each frame and apply it.

# Answer
> 3 votes
One way around this problem to allow the view matrix to be kept from frame to frame instead of yaw, pitch and roll.

The idea behind doing this is that you can multiply the matrix by rotations around each of the three axes encoded in the 3x3 "rotation" part of the transform matrix to change yaw, pitch or roll incrementally. Because you continually apply small rotations using the ever changing local axes you will avoid gimbal lock - the camera won't suddenly flip upside down because the changes to the "up" vector part of the view matrix is always changing smoothly in small increments.

There are drawbacks however - you may need to orthonormalise the matrix to prevent distortion from the accumulation of rounding errors. At very low frame rates you might get unexpected results depending on the order in which you do the three rotations (e.g. if you get a single frame with such a big change in orientation that you still get gimbal lock).

---
Tags: mathematics, camera
---


title: programming light sources in java

text:
# Question
Title: programming light sources in java
I was making a game and I wanted to program light sources but I don't know how to. every where I search it comes up with lightweight java. Can any one offer any help. Its a birds eye view mmorpg. Can anyone help me?

# Answer
Ok, this may not be what exactly you are looking for. But, here you might find some guideline to sort it out.
> 1 votes

---
Tags: 3d, java, software-engineering, mmo, lighting
---