title: XNA editor content

text:
# Question
Title: XNA editor content
I have a little problem with designing editor in xna. I have Content types like `TilemapContent` and then runtime types like `TilemapData` (that are automaticly converted by content pipeline)

but in editor, i think i need to work with `TilemapContent` (so that i can save it as such later), but `TilemapContent` contains things like `ExternalReference<Texture2DContent>` instead of `Texture2D`, so there is no way i could render such thing.

One "solution" that i can think of is every time i make a change to `TilemapContent`, i need to rebuild it and then reload `TilemapData` (and i guess this would be really slow)

Another solution would be to write third class `TilemapEditorData` and inside it write method that would convert that class to `TilemapContent`. But this would be third class, with almost same data, and it would require me to write something that would convert things like Texture2DContent to Texture2D.

So question is, how is this thing done? Can i have different content type and runtime type and still make an editor?

**EDIT**: source

> ContentPipelineExtension project

```
[ContentSerializerRuntimeType("Data.TileMapData, Game")]
public class TilemapContent
{
     public int Width { get; set; }
     public int Height { get; set; }
     public ExternalReference<Texture2DContent> Texture { get; set; } // i need this in editor so i can change tileset texture
     public int[] Tiles { get; set; }
}

```

> Map.xml

```
<XnaContent>
  <Asset Type="Content.TilemapContent">
    <Width>3</Width>
    <Height>3</Height>
    <Texture>
      <Reference>#External1</Reference>
    </Texture>
    <Tiles>
      0 1 0
      0 0 1
      0 0 0
    </Tiles>
  </Asset>
  <ExternalReferences>
    <ExternalReference ID="#External1" TargetType="Microsoft.Xna.Framework.Content.Pipeline.Graphics.Texture2DContent">raytileset.jpg</ExternalReference>
  </ExternalReferences>
</XnaContent>

```

(i have custom ContentProcessor that will build all external references in xml file)

> Game project

```
   public class TilemapData
    {
        public int Width { get; set; }
        public int Height { get; set; }

        public Texture2D Texture; // and i need this in editor so i can render tilemap

        public int[] Tiles { get; set; }
   }

```

# Answer
To achieve this, separate your XNA solution into 4 projects:

1. Content Project

* This will contain all of your assets (like normal). Including your XML files that will be generated by your editor.

2. Engine Project

* This will contain common classes like `TilemapContent` and `WhateverOtherContent` that you want to load in-game as well as edit in the editor, as well as any utility classes common between the game and editor (or your whole engine if you want essentially a "game-with-editor-mode" project).
* Any classes you wish to instantiate, edit, and reload should have appropriated attribute flags like `[ContentSerializer]` (or something, look at Shawn Hargreaves' blog.

3. Game Project

* This will contain the game logic. If you want to run the game, you run this project.
* It will reference the Engine project to get access to `TilemapContent`, etc. for deserializing TilemapContent objects from the XML that's been compiled into the XNB files.

4. Editor Project

* This will contain your editor code. Mainly, the GUI code, and even if you'd like you can reference all the same files as the game engine project so running this project is the equivalent of running the game in editor mode.
* Use conditional compilation to allow or disallow compilation & execution of editor functionality. You can set conditional compilation symbols on a per-project basis, and you can setup separate exes for editor and game.
* This will also reference the engine project of course, but it will also reference the ContentPipeline assemblies.

A 2d XNA game framework I'm creating on and off for fun does this, so I can verify it works.

Note of course that making a level editor using the `Content.Load<YourObjectType>("foo");` that's intended to run on Xbox won't work at all, and you'll have to go through the pain and misery of writing your own data format and intermediary classes. The serialization supported in XNA is designed to be part of the Content Pipeline since it uses reflection.
> 2 votes

# Answer
From my experience, usually the content (xnb files) are compiled from some other intermediate format. (for images its bitmaps or .pngs, or what have you) I'm guessing you have some kind of xml format.

To get to that xml format, usually you write some kind of serializing code or use a serializer class (like XmlSerializer or IntermediateSerializer or some kind of serializing/persistence framework)

So you could use your TileData class in your editor, save the map as an xml file and you could run your visual studio build or set up some MSBuild stuff in your editor.

All in all, I think your looking at this the wrong way and that you shouldn't compile to xnb directly. I'm not an expert, but I think your a tad confused with the workflow, at least from my understanding.

My Understanding in Digest Format : Runtime Type (in editor) -\> Save to intermediate format (xml or whatever) -\> build later at design time (this is where that Content class comes in)

This is also a bit easier to debug because xnb files are binary while xml is filled with strings, far easier to look at and understand. Maybe I just didn't understand your question/situation.

Just in case I'm completely off: You could use the runtime type and when you save it you could instantiate a bunch of the content types to save with?

Edit: You need the texture name to edit the texture or something? I see your dilemma now. Probably creating a new class would be the easiest solution instead of trying to do a bunch of funky pairing of the two classes.

If you used interfaces, you could have a class that implements both the ITextureContent and ITextureData (that might make it easier if you had functions that took an TextureContent or something of that nature). If you didn't use interfaces (understandable for a data type), than maybe creating a new class that just holds both a texture content and texture data (these fields would be protected and there would be public properties that would access shared data between the two members or just one member, in the case of the texture name). You could then define a public property to get one of those members (the TextureContent or TextureData) for code that needs a specific member like a drawing function or something of that nature.

That could probably work.
> 1 votes

---
Tags: xna
---


# Question
Title: Spritesheets From Individual Images in Content Pipeline?
My main goal is avoid using an external program like SpriteSheetPacker.

I would like to just use sequenced PNGs and have the sprite sheets be made, updated, and saved automatically when I build my game.

**Edit: The old answers I upvoted, but I updated the question and specifically asked how to do this automatically with the Content Pipeline. Please do not give an answer that involves using an external program.**

# Answer
> 4 votes
Breaking down what you want to do into solutions:

1. You need some way to watch the file system to trigger this process. Polling it or using `FileSystemWatcher` come to mind as appropriate solutions. (If this is for some kind of editor, I personally find assigning a hotkey is preferable.)
2. You need a way to actually create sprite sheets. Googling around will probably find something. Nick Gravelyn's Spritesheet Packer that bearcdp mentioned is probably more fully-featured, but I'm not sure that it is integrated into the content pipeline - the one in the XNA Sprite Sheet sample is.
3. To create XNA's native XNB files you need to use the Content Pipeline. This requires you have XNA Game Studio installed on the end-user machine. You can invoke the content pipeline at runtime, and a good example of this to get you started is the Winforms 2 XNA sample.
4. You can then load those XNB files with `ContentManager` as normal (and unload the old ones that you aren't using). I think the Winforms 2 sample has some discussion of your various options for caching and so on.

# Answer
> 2 votes
Are you talking about runtime as in while running on the Xbox? If so, no. But if you are talking about as part of your development process, then you could add a special content pipeline class, or at the most basic, a simple custom build step that runs a tool that updates image files needed.

Custom build steps allow you to specify the output files that should be checked to see if they need to be updated or not. You'll probably need a directory with standard naming schemes for the individual frames of an animated sprite, and a text file with the properties of the spritesheet to be parsed by your tool and also double checked for being up-to-date by MSBuild.

Check out the Spritesheet Packer by Nick Gravelyn for the example of modifying image data and outputting it. It's not what you're looking for, but it covers similar ground.

---
Tags: 2d, xna-4.0, spritesheet, pipeline
---


title: How can I implement Offline Skilling

text:
# Question
Title: How can I implement Offline Skilling
An example of offline skilling would be EvE Online. Your character (pilot) does not gain skills by getting experience. Instead, your character gains skillpoints towards a skill you are training whether you are in or out of game. Also, I am fairly certain that skills continue to build even when the game servers are down.

Anyone have any broad ideas of how they go about this, or better yet how I could go about implementing something like this in a game I am developing. I'm not looking for a detailed explanation here (don't let me hold you back though), but I am looking for a signpost that points me in the correct direction.

Thanks!

# Answer
Assuming the skill development is deterministic and fairly linear, all you need to do is to hook into some kind of real time clock (such as the system clock, or server clock), and calculate how long the skill has been in development.

In other words, when the skill development starts, take timestamp and store it, and whenever you want to check if the skill has improved, compare the timestamp with the current one, check if the delta is big enough, and bing, the player has a new skill.
> 17 votes

# Answer
If the skill won't be used until the player is back online you can simply store the log-off time and remaining time on any skills in the queue, and then when the player logs in do something like this:

```
timeRemaining = currentTime - logoutTime
while ( timeRemaining > 0 and hasQueuedSkill() ) {
     skillTime -= timeRemaining
     if ( skillTime <= 0 ) {
           popSkill()
           timeRemaining = -skillTime
     }
}

```
> 2 votes

---
Tags: mmo, character
---


# Question
Title: Why does glGetUniformLocation report some of my uniform locations as -1?
I have been writing GLSL shaders for over a year but this is the first time I have run into this problem. I am on the iOS platform - if that matters.

In a vertex shader I have this:

```
uniform mediump mat4 projectionViewModelMatrix;

```

In a fragment shader I have been using for months I have the following uniforms:

```
uniform int channels;
uniform sampler2D hero;

```

Nothing to write home about. I added three additional uniforms to the fragment shader:

```
uniform int heroChannels;
uniform int heroWidth;
uniform int heroHeight;

```

Using

```
glGetUniformLocation

```

I tried to grab the location of all my uniforms. This is when my own personal hell began. This is the result:

```
uniform heroChannels location -1
uniform channels location 4
uniform hero location 5
uniform heroHeight location -1
uniform projectionViewModelMatrix location 0
uniform heroWidth location -1

```

Huh? Why are the recently added uniforms not given a valid location by the GL Gods?

# Answer
Couple things come to mind.

First, it's possible each of your int uniforms actually takes a whole vector in uniform space, and thus you may be running out of space - you can try to combine them into vectors to see if it helps.

Second, it's possible that the shader compiler happily discards the uniforms in case they're not actually in use. If this is the case, then they naturally won't get a location.
> 5 votes

---
Tags: opengl, opengl-es, glsl
---


# Question
Title: Translate object in world space usings it's local rotation
I'm using Three.JS to render some objects. I'm struggling with some very simple object rendering and translation.

The scenario is that I spawn an object at 0,0,0 in world space with 0,0,0 rotation.

```
var scene, camera, cube;

...

function change() {
  var degrees = 90
  var zTranslation = 5;

  cube.rotation.y = degrees * Math.PI / 180;
  cube.rotation.z = zTranslation;

  var newCubeMatrix = cube.matrix;
  newCubeMatrix.identity();
  newCubeMatrix.multiplySelf(THREE.Matrix4.rotationYMatrix(cube.rotation.y));
  newCubeMatrix.multiplySelf(THREE.Matrix4.translationMatrix(cube.position.x, cube.position.y, cube.position.z));

  cube.updateMatrix();
}

function loop() {
  renderer.render( scene, camera );
}

...

```

What now happens is that the cube is rotation 90 degrees and translated 5 points on the Z axis in world space, not 5 points on the Z axis in the cube's local space.

How do I make the cube translate 5 points in it's local space?

# Answer
The order of the transforms is important.

Rotating around Y and then translating along Z rotates the object around its Y and then translates along world Z.

Translating along Z and then rotating around Y rotates *the scene* around Y, that is, the cube is already 5 units from the origin, and the whole scene rotates.

First of all you need to determine which you're trying to achieve. It may be useful to forget about different coordinate spaces, just assume the cube starts at the scene's origin and you then apply several transforms to its vertices, all in scene space.

Once you've figured out the correct order of operations, figure out (either by trial and error or reading the documentation (!)) whether the API premultiplies or postmultiplies the vertices and the matrices. Then make sure you concatenate the transforms in the correct order, because P\*T\*R will yield a different P' (transformed P) than T\*R\*P, even if the composite transform T\*R is the same.
> 6 votes

---
Tags: 3d, javascript, three.js
---


# Question
Title: How can I convert a paid iOS game to a free game with in game purchases?
I have developed a game for iOS that has had a decent amount of downloads, but I think I would get significantly more revenue if I were to convert the game to free to play, with in app purchases (especially since some competitors products are now free to download with in app purchases).

My question is what is the best way to go about converting to a free game with in app purchases without annoying the existing users?

On upgrading I'd like the people who previously paid for the app to have access to all the in-app purchases because I don't want to make them have to pay for content they previously had, and I don't want to make all the content (that is currently in the game) free.

# Answer
> 8 votes
Have you considered just making a different SKU? Keep your paid version up there, and add a new one that's free with IAP. It will be a bit more of a maintenance issue with future updates, but it seems like the fairest way to make sure that people who paid don't have to be in a situation where they have to do anything to keep their content.

# Answer
> 0 votes
By including all content into the game but locking it off unless the user can authenticate against a server of yours, then pull down account information and unlock correct content. There is no easier way because of the method in which you have sub

---
Tags: ios
---


# Question
Title: Techniques for creating sound effects in a browser based game?
The `<audio>` tag and the `<object>` tag are (somewhat hard to use) ways to embed audio on a page... ...but what about creating sound effects in a browser-based game? E.g. if the game becomes aware you died, I plan to have some music play on the "you're dead" page. But what about some kind of fighting sound when people click an "attack" link, or the sound of flowing water when they click to "heal".

Do I essentially have to look into embedding an invisible flash widget like facebook does for some of it's sounds in order to make this work, or are there other approaches?

# Answer
> 4 votes
You can trigger audio that is loaded in `<audio>` or `<object>` tags in a couple of ways.

In HTML5-compatible browsers like Firefox, Chrome, IE9, and Safari this is accomplished like so:

```
<audio id="attack">
  <source src="attack.wav">
</audio>
<audio id="heal">
  <source src="heal.wav">
</audio>

<a href = "#" onclick="document.getElementById('attack').play()">Click to Attack</a>
<a href = "#" onclick="document.getElementById('heal').play()">Click to Heal</a>

```

The "#" link is just to make sure that you don't go to a new page. I recommend using WAV files for short sounds -- WAV is compatible with basically every browser, and as long as your total sound effects end up less than maybe 1MB you should be okay. Otherwise you'll have to include both an .OGG and .MP3 files for each sound effect inside the tag, like so:

```
<audio id='attack'>
  <source src='attack.ogg'>
  <source src='attack.mp3'>
</audio>
<audio id='heal'>
  <source src='heal.ogg'>
  <source src='heal.mp3'>
</audio>

<a href = "#" onclick="document.getElementById('attack').play()">Click to Attack</a>
<a href = "#" onclick="document.getElementById('heal').play()">Click to Heal</a>

```

If you want to get this to work on IE7 and IE8 then you'll need to fall back on the `<object>` tag. There's a good example of that available in this article.

---
Tags: audio, browser-based-games, sound-effects
---


# Question
Title: Receiving user commands in a text based console game
I'm working on a little text based console game for a bit of fun and am starting work on the user commands entered into the console.

Are there some good design patterns for deciding what to do with the commands the user enters into the console window?

My thoughts so far:

I've createed a basic query structure for obtaining the command and it's arguments. It works kinda as follows (the code is C#):

```
var userCommand = _getUserInputQuery.Invoke(new GetUserInputRequest
                                                {
                                                  FullCommandText = Console.ReadLine()
                                                });

```

I now have two items available to me in the userCommand. Firstly I have the name of the command as a string `userCommand.UserCommand` and secondly I have a string array of arguments `userCommand.UserCommandArgs`.

I figure there's a couple of ways I can now proceed with the information I have.

The most basic form could be a simple `switch/if` on the command name and invoke the relevant class/method required (seems a bit icky though).

I also figured given a generic interface for all commands `IUserInputCommand` I could create the class required using reflection and fire off a generic `Invoke` method from the interface. (Although I'm not sure how useful this will be given that some command invokations will require different data than others).

What are some design patterns already available for solving this kind of problem? What would you do personally?

# Answer
Old MUDs and Talkers (mostly the talker code bases) would use an array of arrays of structs for keeping lookups only to possible alphabetic matches. This would be done with

```
input[0].ToLowerInvarriant() - 'a'

```

== the index of all the commands starting with the same letter... In C# however I would say just use a Dictionary. Their hashing routines for strings is nice and zippy so just

```
Dictionary<string, Delegate> dCommandHash;

```

or so would work. Then just

```
if ( dCommandHash.ContainsKey(userCommand.UserCommand))
    Whatever.You.Call.Invoke.On.Invoke(dCommandHash[userCommand.UserCommand],userCommand.UserCommandArgs);

```

would likely be the most straight forward way to accomplish this.
> 4 votes

# Answer
If you'd like to see what one approach to this looks like far down the evolutionary path, take a look at the MudOS parser. This is a complex, powerful mechanism for defining pattern-based parsing, meant to be able to intelligently route command handling for targets with multiple nouns and adjectives, and handle cases like `put ITEM in CONTAINER` vs. `put on CLOTHING` (i.e. very different actions that happen to start with the same verb). It may help illuminate where you're going.
> 4 votes

---
Tags: c#, design-patterns, console, text-based
---


title: opengl memory issue - quite strange

text:
# Question
Title: opengl memory issue - quite strange
I have heard that textures consumes lot of memory but I am surprised how much.... I have 7 textures 1024 16 bit each. And while I will run my app it consumes 57MB of memory. I think that this is "a bit" too much.

I am writing 2D application (no cocos or other framework)

Strange is that while I will compile my app with disabled rendering methods: glDrawArrays than It uses only 27MB.... which is about 30MB less...

Do you have any Idea why?

I am creating textures before rendering of course: rendering looks like this:

```
 [EAGLContext setCurrentContext:context];
 glBindFramebufferOES(GL_FRAMEBUFFER_OES, defaultFramebuffer);

 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

 glPushMatrix();
 glEnableClientState(GL_VERTEX_ARRAY);
 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
 glEnable(GL_TEXTURE_2D);

 glEnable(GL_BLEND);
 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

 TeksturaObrazek *obrazek_klaw =[[AppDirector sharedAppDirector] obrazek_klaw];
 glBindTexture(GL_TEXTURE_2D, [[obrazek_klaw image_texture] name] );

  glVertexPointer(2, GL_FLOAT, 0,vertex1);
  glTexCoordPointer(2, GL_FLOAT, 0, vertex2);
  glColor4f(1,1,1,alpha);
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

 glDisable(GL_BLEND);
 glDisable(GL_TEXTURE_2D);
 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
 glPopMatrix();
    [context presentRenderbuffer:GL_RENDERBUFFER_OES];

```

It looks like standard routine... I have spent about 2 days looking for for answer and I still have no clue.

# Answer
7 described textures could take as much as 14mb in 16bit, 28mb in 32bit (uncompressed). My ideas:

* when you disable rendering compiler disables texture creation (pretty weird);
* you create GL\_RGBA textures and they use 32bit per pixel = total of 28mb;
* you load your textures from "HDD" and pass them to OpenGL, but you forgot to clean up after that, hence you have additional 14mb+ wasting your RAM;
* you use uncompressed (raw) textures by mistake;
* creating/using mipmaps may add additional ~30% RAM usage.
> 1 votes

# Answer
> * Why it allocates 4 Mb per texture during rendering and how to release this memory if is not used.

4MB sounds like 1024\*1024\*4, or 1kx1k 32bit per pixel texture. The reason why such memory would be allocated during rendering is that the GL implementation converts the texture into a more hardware-friendly format. It should get freed when you free the texture. You can try to change the internalFormat of the glTexImage2D call to something more suitable - can't remember which ones are supported in ES, but GL\_RGB16 might be it?

> * Why after loading more the 4 textures 1024 App break?

This one I don't know. Maybe you're running out of memory. Why do you need so many of such massive textures anyway for a mobile application?
> 0 votes

---
Tags: 2d, opengl, iphone, software-engineering, memory-efficiency
---


# Question
Title: What sort of things can cause a whole system to appear to hang for 100s-1000s of milliseconds?
I am working on a Windows game and while rendering, some computers will experience intermittent pauses ("hitches" for lack of a better term). When profiled they appear in seemingly random places in the code. Eventually I noticed that it wasn't just my process that was affected, but (seemingly) every process on the system. All of the threads in my application hitch at once. The CPU utilization drops during these hitches and it appears as if most processes make no progress.

This leads me to believe this may be an Operating System or Driver issue, but it only occurs while playing the game (and only on some systems). What sort of operations might the operating system be doing that would require the kernel to pause all user threads and block. Some kind of I/O? At first I thought of paging but my impression is that would only affect a single process, no?

Some systems in use: Windows, DirectX (3d), nVidia cards (unknown if replicates on ATI), using overlapped io for streaming

# Answer
In my experience, these types of issues typically boil down to some type of resource exhaustion.

It's easy to speculate to the n-th degree about what it "could" be, but without data, these remain speculations.

## Counters

To gather data that can solve the puzzle, on windows you need to collect perfmon data. Some counters you should grab for all processes (if applicable) are:

```
**Processor** /All Counters/All instances
**Logical Disk**/All Counters/All instances
**Memory**/All Counters/All instances
**Network Interface**/All Counters/All instances
**Paging File**/All Counters/All instances
**Process**/All Counters/All instances
**Processor**/All Counters/All instances
**Server**/All Counters/All instances
**Server Work Queues**/All Counters/All instances
**System**/All Counters/All instances

```

In my opinion, this is an exhaustive list of all possible counters that you might find relevant data in. There is a penalty for capturing all of this data, it is a lot of data to log, so you may want to try a subset of the counters that you feel are most relevant for your situation.

## Logging

When you run perfmon you want to select to create a new manually defined Data Collector Set for Performance Counters. There will be a screen that asks for the sample interval. You need to make sure that the sample interval is small enough to capture the problem but not so small that you overwhelm the system with data logging.

I would recommend setting the capture to manually start/stop. So that you can start the capture, repro the problem, then stop and analyze the logs.

## Analyzing Data

The perfmon utility allows you to look at every counter individually. If you know what you're looking for, this works. If you're not familiar with this process or which counters to look at, you might benefit from using an automated analysis tool such as PAL. PAL is free and awesome. Essentially it has a set of thresholds defined for each counter, it parses through your log collection and spits out an HTML report that shows you:
**Warnings** \- Any counter that is close to a threshold
**Critical** \- Any counter that has exceeded a threshold

This can be a simple way to start your analysis and narrow in on any items marked Critical.

## Best Guess/Speculation on Problem Statement

To add to the speculation about what it might be. It sounds like you may be under memory pressure. This means that physical free memory has been exhausted and the os needs to read or write memory contents to or from disk.

The perfmon data that would validate the above scenario would show a steady rise in memory utilization followed by a sharp fall. Simultaneously there would be a sharp rise in pagefile usage as well as local disk I/o. Again, just speculating without any hard data (which you need).
> 3 votes

# Answer
If you managed to hang the entire computer, not just your own process or any processes you were actively messing with, then this means a bug in Windows or a driver, as it should be impossible for user-mode code to cause this kind of system-wide hang. That doesn't mean that the bug isn't triggered by a bug in your own code- but your code might also be perfectly bug-free.

What you need to do is narrow down the issues- record the state of all threads at the time of a hitch. Also, you should verify that no external code is messing with your process. There's a specific Logitech Webcam, whose drivers will inject a DLL into all processes and it would damage several games that I know of, just for example. This kind of thing can damage your system from the outside in unknowable ways.
> 1 votes

# Answer
This sounds like you are crashing/stalling the GFX-Driver.

The best tools to narrow this down are a PIX and the directx-debug runtime.

You can change the DirectX Runtime into debug mode in the "DirectX Control Panel". This should give you a lot of log-output about any issues there could be in your driver-calls or the data you are providing. You should try to fix every error/warning the runtime is logging, as it is totally driver-dependent how these problems are handled on specific graphcs-cards.

If this does not show anything suspicious you can try to get more info about what is happening with PIX. But I am pretty sure that the first step should give you the informations you need.
> 1 votes

---
Tags: directx
---


# Question
Title: What are some Game Development Publications that accept outside articles
What Are some Game Development publications (electronic or otherwise) that aren't so large that there is no chance to potentially get included in the publication after a few well-written articles sent their way.

Looking for publications geared towards developers, not gamers, and can be any aspect of the game process, design, development, business, etc.

# Answer
> 4 votes
Game Developer magazine?

# Answer
> 4 votes
In addition to Game Developer and Gamasutra there is Develop which has a more EU tilt and the more recently launched Gamesauce which is a small growing publication and probably the most interested in unsolicited articles.

# Answer
> 4 votes
We're always interested in contributions from industry professionals. Feel free to contact me!

Best regards,

Vlad Micu
European Editor for Gamesauce Magazine

---

# Answer
> 3 votes
Gamasutra might be an option.

I don't know if they are too big and they do not explictly request articles but their site covers some of the topics you list.

Their email address is at the bottom of their page.

# Answer
> 2 votes
Not exactly a publication, but you can always share articles you've written on gamedev.net

# Answer
> 1 votes
Most publications accept submissions. Look for a "submissions" or "contact us" link on their websites and make sure to follow their guidelines.

# Answer
> 0 votes
Specific to software engineering and production, Communications of the ACM and ACM Queue both seemed to cover game software and related content (AI, graphics, real-time systems) regularly when I was a subscriber.

---
Tags: marketing, business, publishing, articles
---


# Question
Title: 2D game - Missile shooting problem on Android
I have to make a tank that sits still but moves his turret and shoots missiles.

As this is my first Android application ever and I haven't done any game development either, I've come across a few problems...

Now, I did the tank and the moving turret once I read the Android tutorial for the LunarLander sample code. So this code is based on the LunarLander code.

But I'm having trouble doing the missile firing then SPACE button is being pressed.

```
private void doDraw(Canvas canvas) {

canvas.drawBitmap(backgroundImage, 0, 0, null);
// draws the tank
canvas.drawBitmap(tank, x_tank, y_tank, new Paint());
// draws and rotates the tank turret
canvas.rotate((float) mHeading, (float) x_turret + mTurretWidth, y_turret);
canvas.drawBitmap(turret, x_turret, y_turret, new Paint());

// draws the grenade that is a regular circle  from ShapeDrawable class
bullet.setBounds(x_bullet, y_bullet, x_bullet + width, y_bullet + height);
bullet.draw(canvas);

}

```

UPDATE GAME method

```
private void updateGame() throws
 InterruptedException {

 long now = System.currentTimeMillis();

 if (mLastTime > now)  return; double
 elapsed = (now - mLastTime) / 1000.0;
 mLastTime = now;

 // dUP and dDown, rotates the turret
 from 0 to 75 degrees. if (dUp)
 mHeading += 1 * (PHYS_SLEW_SEC *
 elapsed);

 if (mHeading >= 75) mHeading = 75;

 if (dDown) mHeading += (-1) *
 (PHYS_SLEW_SEC * elapsed); if
 (mHeading < 0) mHeading = 0;

 if (dSpace){

```

// missile Logic, a straight trajectorie for now x\_bullet -= 1; y\_bullet -= 1;

//doesn't work, has to be updated every pixel or what?

```
 }

boolean doKeyDown(int keyCode, KeyEvent msg) {
            boolean handled = false;
            synchronized (mSurfaceHolder) {
                if (keyCode == KeyEvent.KEYCODE_SPACE){
                    dSpace = true;
                    handled = true;
                }
                if (keyCode == KeyEvent.KEYCODE_DPAD_UP){
                    dUp = true;
                    handled = true;
                }
                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
                    dDown = true;
                    handled = true;
                }
                return handled;
            }
        }

```

} a method run that runs the game...

```
public void run() {
            while (mRun) {
                Canvas c = null;
                try {
                    c = mSurfaceHolder.lockCanvas(null);
                    synchronized (mSurfaceHolder) {
                        if (mMode == STATE_RUNNING)
                         updateGame();
                        doDraw(c);
                    }
                } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        mSurfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }

```

**So the question would be, how do I make that the bullet is fired on a single SPACE key press from the turret to the end of the screen?**

Could you help me out here, I seem to be in the dark here...

Thanks,

Niksa

# Answer
> 4 votes
All the movements in the lunar lander game are multiplied by the elapsed time since the last frame. This comes from the formula velocity * time = distance. Because of this the motion will be constant no matter what the frame rate is.

Instead of

```
x_bullet -= 1; y_bullet -= 1;

```

You should have something like:

```
x_bullet -= BULLET_SPEED * elapsed;
y_bullet -= BULLET_SPEED * elapsed;

```

---
Tags: 2d, physics, java, android
---


# Question
Title: What are some programming design patterns that are useful in game development?
I have a few books on Design Patterns, and have read some articles, but cannot intuitively figure out which programming design patterns would be useful in game development.

For example, I have a book called ActionScript 3 with Design Patterns that details several design patterns such as Model View Controller, Singleton, Factory, Command, etc.

As someone new to this, I cannot figure out which of these would be useful, or in fact if any of these are the design patterns I should be learning and trying to use. Perhaps there are other, more game-programming-specific design patterns that I am not even aware of?

If you have experience using a certain design pattern in game development, I'd love to hear it. Reasoning as to why it was used, code samples, or online resources would all be very helpful as well if you have them. I am at the moment most interested in ActionScript 3 and C++ implementations, but could definitely benefit from experience and examples from any language.

Thanks!

# Answer
Now for a less flippant response, with some suggestions. Don't take these as implementation recommendations, more as examples of possible use.

* Builder: set up component-based entity one component at a time, based on data
* Factory Method: create NPCs or GUI widgets based on a string read from a file
* Prototype: store one generic 'Elf' character with initial properties and create Elf instances by cloning it.
* Singleton: *this space deliberately left blank.*
* Adapter: incorporate an optional 3rd party library by wrapping it in a layer that looks like your existing code. Very useful with DLLs.
* Composite: make a scene graph of renderable objects, or make a GUI out of a tree of Widgets
* Facade: simplify complex 3rd party libraries by providing a simpler interface to make your life easier later.
* Flyweight: store the shared aspects of an NPC (eg. models, textures, animations) separately from the individual aspects (eg. position, health) in a mostly transparent way
* Proxy: Create small classes on a client that represent larger, more complex classes on a server, and forward requests via the network.
* Chain of responsibility: handle input as a chain of handlers, eg. global keys (eg. for screen shots), then the GUI (eg. in case a text box is focused or a menu is up), then the game (eg. for moving a character)
* Command: encapsulate game functionality as commands which can be typed into a console, stored and replayed, or even scripted to help test the game
* Mediator: implement game entities as a small mediator class that operates on different components (eg. reading from the health component in order to pass the data to the AI component)
* Observer: have the renderable representation of a character listen to events from the logical representation, in order to change the visual presentation when necessary without the game logic needing to know anything about rendering code
* State: store NPC AI as one of several states, eg. Attacking, Wandering, Fleeing. Each can have its own update() method and whatever other data it needs (eg. storing which character it is attacking or fleeing from, the area in which it is wandering, etc.)
* Strategy: switch between different heuristics for your A\* search, depending on what sort of terrain you're in, or perhaps even to use the same A\* framework to do both pathfinding and more generic planning
* Template method: set up a generic 'combat' routine, with various hook functions to handle each step, eg. decrement ammo, calculate hit chance, resolve hit or miss, calculate damage, and each type of attack skill will implement the methods in their own specific way

Some patterns left out due to lack of inspiration.
> 171 votes

# Answer
I wrote a book on exactly that topic: Game Programming Patterns. The chapters that are there might be helpful for you.
> 64 votes

# Answer
One thing Brandon Eich had the good sense to bring up in *Coders at Work* is that patterns are hacks and workarounds: *\[Patterns\] show some kind of defect in the language. These patterns are not free. There's no free lunch. So we should be looking for evolution in the language that adds the right bits.*

As game programmers rather than compiler designers we rarely get the option to evolve the languages we use, but we can learn to evolve our own style to better fit our language and requirements. Patterns are some of this, but *not using patterns* is another part, especially since as Brandon says, patterns rarely go without a notable performance or memory or code agility cost. MVC just is not a great pattern for many things in games. Singleton is a workaround for lame C++ static initialization rules, and you probably shouldn't be doing those anyway. Factory simplifies complicated object creation - maybe your objects should just be simpler to start with. The popular patterns are tools to resort to *when we need them* to manage something complex, not tools we should be longing to use to build something complex at the start.

Good (game) code might use patterns, or it might not. If it does use patterns, fine - they're a great communication tool to explain code structure to other programmers at a high, language-independent level. If you think the code is better without using a pattern, don't beat yourself up over it - it probably is.
> 22 votes

# Answer
Of course, as others have said, all patterns are useful in the right circumstances, and part of learning how to use them is learning when to use them. However, the excellent book *Core Techniques and Algorithms in Game Programming* by Daniel Sanchez-Crespo Dalmau, lists six programming patterns and six usability patterns as especially useful in game programming.

Programming:

* Singleton: I don't hate this one like many people do; it can be used for things like the single-player player or the keyboard reader.
* Factory: Lets you create and destroy objects efficiently.
* Strategy: Lets you change out AI strategies elegantly.
* Spatial Index: Helps perform queries on spatial data sets.
* Composite: Sets up a useful object heirarchy.
* Flyweight: Frees memory by genericizing things like identical enemies.

Usability:

* Shield: Protects from accidental activation of dramatic actions.
* State: Visual cues of the world/UI status.
* Automatic Mode Cancellation: Makes the game work more intutitively.
* Magnetism: Autoaiming and easy unit selection.
* Focus: Eliminating distracting UI elements.
* Progress: Universally useful.

The book, of course, goes into more detail on each of these.
> 8 votes

# Answer
*Entity systems* are a nice kind of pattern. It's not exactly a design pattern since it's not strickly OOP. However you can mix it with OOP.

Some good links (start from top for intro):
> 8 votes

# Answer
All of them. Except Singleton. \[/flippancy\]
> 7 votes

# Answer
The curiously recurring template pattern can be really useful for avoiding virtual methods and the performance penalty that can come from the virtual function calls.

This can be the appropriate pattern when you don't actually need to have a container of the base class type which has the interface you're after, but you'd like to have similarly named behaviors and interfaces.

For example you can use this when compiling classes for multiple platforms or engines (dx vs. opengl) where the variance of type is known at compile time.
> 7 votes

# Answer
Not really about patterns, but about basic principles behind them. In "Design Patterns: Elements of Reusable Object-Oriented Software" (1995), the gang of four (Gamma, Erich; Richard Helm, Ralph Johnson, and John Vlissides) recommends only two principles for object oriented design: **(1)** program to an interface and not to an implementation and **(2)** favor object composition over class inheritance.

These 2 principles are very helpful in many tasks of game development. For example, many game programmers have used a deep **class hierarchy** to represent game entities. There is another approach based on **composition** \- component-based game objects. Article about this approach. Even more links. It is a Decorator pattern example.
> 6 votes

# Answer
A design pattern that I evolved over the course of many years, and which has been spectacularly useful to me, is something I refer to as "brokered definition sets"; how to summarize it in GOF terms appears to be controversial, but this question I wrote about it on StackOverflow goes into some detail about it.

The core concept is that some property of a model, like the species of a creature, is set up so that each possible value for the property has a corresponding definition object -- a single, shared object per value -- that specifies its behavior, and these are accessed through a central broker (which, GOF-wise, may be a Registry, a Factory, or both). In my usage, they're also generally accessed via scalar keys, to facilitate weak binding for runtime morphism purposes.
> 4 votes

---
Tags: c++, software-engineering, actionscript-3, design-patterns
---


# Question
Title: Need 3D RPG development library/framework recommendations
I’m currently planning to develop an RPG. It will be a project I do in my free time. No pres-sure behind it. I’ll probably be doing it together with a friend and it’s just supposed to be a fun project, something we just work on, if we like to. Although it is a private fun project, I will make arrangements for this project, like project management and detailed documentation etc. I will also have a look at this thread and gather more information before starting.

An important choice I have to make is what libraries or framework I want to develop the game with. I know that there isn’t a BEST library, but maybe someone with some experience can recommend a fitting library. Maybe I just write down what my “requirements” are.

* C++
* Offline RPG
* Running on Windows will suffice
* Therefore I tend do Direct3D, contradictions? Proposals? OpenGL?
* Well documented API

If you need some more specific information, just tell me.

If you can recommend libraries, how is multithreading done in those? Are new threads created implicitly? I’d just like to know as much as possible about what is coming to me, before starting.

Thanks in advance!

# Answer
> 11 votes
A good framework - or actually a toolset - is Unity3D. It's somewhat less flexible than "engines" that are focused only on rendering, but then it can save you *enormous* amounts of time by taking care of a lot of common tasks. You don't have to worry about render, physics, sound, resource importing, terrain engine (if you need one), it has passable GUI system.

In my experience, it's the only game engine out there that enables a single person to create a big game.

It requires C#, though (or its own Unityscript, but C# is way better).

# Answer
> 4 votes
To give proper advice we need to take a step back.

1) What are your goals.

2) What is your experience level.

If your answer to #1 is "I just want to make an RPG/tell a story/bring my characters to life" and #2 is "little to none", then I recommend you read this thread: Recommended RPG game that can be used to learn game Modding?

There's no reason to write rendering code if all you want to do is lay the framework for your story to take place in an existing engine, for example.

Also, I personally don't think C++ is a good requirement to have. Learning a new language, especially something that's higher level, can be an enlightening experience and also help you get stuff done faster, even if it's not theoretically as efficient.

# Answer
> 4 votes
One thing I would like to clear you up on - don't expect to find one library that does all that. Or even some of it. Robust, sturdy libraries exist for large things (SDL for 2D graphics, OGRE3D and Irrlicht for 3D, FMOD for sound, etc), but don't expect to find a well documented RPG engine.

Also, there is going to be little difference if you choose DX over GL. The only thing I can possibly see is that OpenGL drivers (Windows) tend to be slightly worse than directX ones. Since both OGRE and Irrlicht are abstractions, you can switch between either. So cross platform-ity is not completely out the window.

However, if you take each of your requirements separately: ogre3D and Irrlicht are good solid 3D graphics engines.

And as for your threading concern, here is an article about threading OGRE. Natively, neither of the engines support it. But there's no reason why you cannot support it yourself.

I do not know of any RPG engines, but you can always try searching here, Gamedev.net and forums, and generally googling for RPG designs. I know for a fact there are a lot of great threads on the gamedev.net forums (though you may have to search a bit harder since they just updated the forums).

Of course, there's always Unity to look at. You can script in C# or Javascript (both being easy enough to learn) and it is very powerful. This would probably be the easiest route, but it depends on how you want to do your project :)

# Answer
> 2 votes
If you really do want to write a 3D RPG (a goal I highly support, by the way) I think Ogre3D is going to be your best bet for a starting framework. It's OpenGL-based and C++-based and can just get a lot of the "busywork" of making a basic renderer out of the way. Plus, it's released under the LGPL, which means that, should you decide to make this a commercial project in the future, you won't have to change engines.

Second, I would recommend reading a blog called the CRPG Addict. (I don't have enough rep to embed a link, just google it). Not only is it interesting watching him play through older RPGs, but he's got some excellent articles on RPG design that you really should check out.

# Answer
> 1 votes
I could suggest Leadwerks, a really easy but flexible and powerful game engine which does dynamic real-time lighting, physics, sounds, and basic controllers for you.

http://www.leadwerks.com/

# Answer
> 1 votes
You might want to look at Sauerbraten (Cube 2), a project focused on being a working open source 3D game with a well-designed, extendable engine. The game they implemented is an FPS rather than an RPG, so the RPG elements would be up to you to design in, but that level of design is probably one that'd wind up being completely custom in any event.

One notable aspect of Sauerbraten is that it, like Cube, is heavily focused on the world model being runtime morphic, which can be extremely useful both for developers working on the setting from within it, and if you want to go the ambitious dynamic persistent world route.

# Answer
> 1 votes
There have been several excellent recommendations, I would add panda3d to the list of items to check out. It has quite good documentation and is fairly easy to use.

---
Tags: c++, rpg
---


# Question
Title: How do you make Direct3D work in a browser?
I've come across games that are 3D that are playable in a browser. They require a plugin to be installed to work. I guess the plugin creates a D3D window inside the browser.

How would I go about implementing something similar?

# Answer
Unity web player (for windows) can use both DirectX and OpenGL in a window (however it abstracts your access to these APIs).

Another approach would be to implement a DirectX plugin using ActiveX (for Internet Explorer), or NPAPI (for other browsers).

If you use NPAPI, when your plugin starts up you'll receive a window handle where you can draw whatever you want (including a D3D window). If you go this route you're essentially running native code on the clients machines.
> 8 votes

# Answer
The game you are playing might use WebGL http://en.wikipedia.org/wiki/WebGL, or something more exotic like a firefox plugin, but I don't think you can embed machine code in a firefox plugin (I'm not sure, that would be a little security flaw).

Unity implements a web plugin version of their engine, and it seems they do so with ActiveX. I don't know if it implements on Mac..., I wonder though.

The best way to find out how this game you are playing use a 3D API or any other kind of plugin stuff, is to look at the HTML source of the page, and look for object or activex or else.
> 5 votes

# Answer
Check out Firebreath for Cross-broswer support.

http://code.google.com/p/firebreath/
> 2 votes

---
Tags: 3d, directx, browser-based-games, web
---


# Question
Title: iPhone point-and-click adventure game port structure
I am porting an AGS game to iPhone, and was wondering what the best approach to the port would be?

How best would you structure your code and assets?

More specifically, how would you deal with say 100+ scenes. My initial approach is to create a scene superclass with things common between all scenes, like backgrounds, music, doors, windows, characters. Then for each scene an inherited version of that superclass with more particular things like checks, dependencies etc. Upon entering the scene, you'd check for dependencies and go from there. This is all off the top of my head mind you, so probably forgetting quite a bit.

# Answer
> 6 votes
Chances are, there are no (maybe one or two hobby ones) 'mature engines' for iPhone point-and-click.

However, Cocos2D iPhone has a high level of abstraction, so it should be easy enough to use that.

As for code structuring, that's really up to you. I personally would have a system where:

* The background is just a static image.
* Items are graphically static on the background, but in code they exist with a position and general rules for combining. So a lamp at (x,y) would receive the touch there and do whatever it has to.
* If an object is on the screen, it could have checks for 'am I being used with object X?' and 'has event Y happened?'. This indicates you would need a set of event flags, muchlike an RPG. Something like 'has player opened secret door', 'has player killed bad guy', 'has player unlocked safe', etc.

EDIT: Following your edit, Cocos2D has its own Scene class. This can quite easily be derived from, and would save significant time from having to develop a whole scene object.

As for doors, I would treat them as a separate object. If you give each object the player as a parameter when you press them, you could simply have pressing a rock call player.add\_item(this), and a door player.setzone(scene.leftexit).

I wish you luck with your project.

---
Tags: iphone, adventure-game-studio
---


title: XNA - Weird bug with 2D Sprite Rotation

text:
# Question
Title: XNA - Weird bug with 2D Sprite Rotation
I have a problem with my XNA Game, I have a function where I need my sprite to face towards an enemy, using this code:

```
        Vector2 currentPosition = Position;
        Vector2 nearestEnemy = gameObjectManager.GetNearestEnemy(Position, GameObjectTypes.Zombie);

        Orientation = (float)Math.Atan2(nearestEnemy.Y - currentPosition.Y, nearestEnemy.X - currentPosition.X)

```

As found on an XNA forum results in my character looking 90 degrees away from the enemy.

Adding "MathHelper.ToRadians(90);" to the end of my Orientation assignment fixes this bug, why is this happening?

Thanks!

# Answer
It seems to me that your sprite may be incorrectly oriented in the source file. Atan2, I believe, returns the angle of the given vector, where zero indicates a vector pointing "to the right" (+X, Y=0). If your sprite file does not point "to the right", you will have to make angle corrections.
> 7 votes

---
Tags: xna, 2d, mathematics
---


# Question
Title: Smallest MQ/HQ Video Format for Game Software (VB.net/WPF based)
I am making a first-person computer game in the style of Carmen Sandiego or The Cluefinders. My game company is just starting up, so we have no spare money.

My animator and I decided that the best way to get movement throughout the game would be to create 640x480 videos that would serve as backdrops, and would hold everything from entering/exiting the scene to talking with other characters (especially since Flash and WPF don't play well with each other). Everything the user interacts with directly (by clicking or dragging) would be put over this video, and in cases of clicking "something in the video," we'll use empty image boxes as "hotspots".

Thus, bringing me to the question. What is the best video format to use so that we have good quality video at 640x480 res, yet does not take up too much space, as this will be running from disk. Whatever it is, it must be able to be integrated in WPF without WinHost, because I have to have WPF objects over it. And again, it must be a format I can use commercially without royalties, but also does not require me to pay for it (therefore, BINK Video is not an option).

# Answer
Given your listed requirements I'm pretty sure there is no answer. Theora or WebM are probably the only that will be free, and I'm sure by now there are Windows codecs for WebM that you could bundle. This seems like a horrible idea though, you should really just do animation the way everyone else does it.
> 2 votes

---
Tags: video
---


# Question
Title: Building 2D Assets for a Game Targeting Multiple Framerates
To make a real-world example, lets assume I want to build an animated sprite for an explosion. The duration of the animation should last ~1 second, and we'll say exactly one second to make the math a bit more simple. And lets assume I'm using XNA and my goal is to target both XBox (60fps), PC (60fps), and Windows Phone 7 (30fps).

My question is this, how should I build the sprite animations so that my programming is as simple as possible without simply using a timer to calculate which frame I should be on (which I feel would make the animation "choppy")?

# Answer
> 6 votes
You have two basic options, animate by frame or animate by time. If you animate by frame it will run twice as long. If you animate by time it will skip half the frames. Choppiness in this case is largely the result of bad animation (no blur, no squash+stretch, no ease-in/out); 30fps is more than smooth enough for sprites in motion.

As for how I'd do it with a timer,

```
# Figure out how long the animation's been going
elapsed = (now - start)
# Figure out how far we are into it.
percentage = elapsed / animation.duration
# Figure out what frame we are given that state.
frame = animation.frames[percentage * animation.frames.size()]

```

---
Tags: xna, algorithm, assets, animation
---


# Question
Title: Enemy movement in straight line to player in chase game
I'm creating a game where the enemies spawn randomly on a map then move towards the player every frame at a random speed. The map has no obstacles so the enemies should always move in a straight line. I wrote the movement function a few times but no matter what the enemies always hit 0, 45, 90, 135, 180, 225, 270, 315 angles but never a straight line. Here is an example of the code:

```
    base_speed = random();

    diff_x = abs(enemy_y_pos - player_x_pos);
    diff_y = abs(enemy_x_pos - player_y_pos);
     if (diff_x > diff_y) {
      y_speed = base_speed;
     } else if (diff_y > diff_x) {
      x_speed = base_speed;
     }

     if (enemy_x_pos < player_x_pos) {
      velocity.x = x_speed;
     } else if (enemy_x_pos > player_x_pos) {
      velocity.x = -x_speed;
     } else {
      velocity.x = 0;
     }

     if (enemy_y_pos < player_y_pos) {
      velocity.y = y_speed;
     } else if (enemy_y_pos > player_y_pos) {
      velocity.y = -y_speed;
     } else {
            velocity.y = 0;
    }

    enemy_x_pos = enemy_x_pos + velocity.x;
    enemy_y_pos = enemy_y_pos + velocity.y;

```

This is my first attempt at game programming. I guessing it's should use algorithm like Bresenham’s Line( http://en.wikipedia.org/wiki/Bresenham%27s\_line\_algorithm) but my attempts to implement have the same issue. How do I make enemies move in a straight line?

# Answer
> 17 votes
Bresenham's line algorithm was developed for fast drawing lines without using floating point operations (integer operations are faster). It is very interesting historicaly but not very good solution for a game (especialy because you cannot specify speed).

When doing a 2D movement use always vectors. This will do all the stuff for you. Sometimes is algebra just wonderful.

```
Vec2d playerPos;
Vec2d direction; // always normalized
float velocity;

update()
{
   direction = normalize(playerPos - enemyPos);
   playerPos = playerPos + direction * velocity;
}

```

There will be some vector2D class for your target language for sure.

# Answer
> 9 votes
Are you calculating every frame? Your code sets either x\_speed or y\_speed to a random number and the other to zero (or the default). Let's say the enemy is at 0, 0 and player is at 20, 10. This looks like it will set x\_speed to some random number each frame and move the enemy to the right until he is at 10, 0. Then the enemy will move either x or y each frame so it will seem he moves in a 45 degree angle up to 10, 10.

Notabene's vector explanation is right but here's how it works. The Vec2d will have an x and y component. In the example above, playerPos - enemyPos will give you a vector of (20, 10). normalize() changes the vector so that the length is 1. Currently the length is sqrt(20 * 20 + 10 * 10). That is about 22.36068. normalize divides both X and Y by this number, giving you about (0.89443, 0.44721) for the direction, which is a vector pointing from the enemy to the player with a length of 1. Multiplying this by your random speed does what you want.

However I would not calculate a new random speed each frame. You probably just want to set the random speed once, or have an initial speed and a target speed that you get closer to each frame. It doesn't make sense for your enemy to go 100 mph initially, then 50 mph for one frame and 200 mph for the next.

```
float targetSpeed = random(); // do this only rarely, or each frame if you don't mind slowing down and speeding up constantly

float acceleration = max(abs(targetSpeed - speed), 0.5) * sgn(targetSpeed - speed); // cap accel/decel at 0.5 per frame
speed = speed + acceleration;

```

---
Tags: ai, movement
---


# Question
Title: What are the advantages of a sprite sheet over an image sequence/flash timeline?
I've noticed sprite sheets are used more and more in Flash games and I don't fully understand what are the advantages over an image sequence/flash timeline - MovieClip.

I've read this related question: 2D graphics - why use spritesheets? and that makes sense for hardware accelerated games, but that's not the case for flash yet.

Any Flash Player specific insights ?

# Answer
> 5 votes
Some popular flash game engines (eg. flixel) use sprite-sheets for sprite-animations. This is mainly because they also implemented a bitmap-based rendering engine which doesn't use the native flash display-classes like "Sprite", "MovieClip" for each object but rather a big bitmap-image where stuff is drawn onto using pixel-operations. Using a bitmap-based approach (i.e. Spritesheet) for a bitmap-based rendering engine is the most efficient thing to do.

This question covers some of the different rendering-methods.

# Answer
> 5 votes
Don't think there is a huge advantage to using one or the other, but it makes porting your game/graphics a lot easier, as any platform can use spritesheets. If you are doing a strict flash game, probably comes down to preference/quickness.

---
Tags: 2d, graphics, flash, spritesheet
---


# Question
Title: State Machines: State Object versus sequential check: what are the pro/cons?
I dont know much about finite state machine in AI or other game behaviors in game, except this quick tutorial with a Miner: http://www.ai-junkie.com/architecture/state\_driven/tut\_state1.html which is object oriented.

I don't really know if this tutorial describes the State pattern or not, what do you think ?

I'm not speaking about other more arithmetic-oriented stuff like steering or physics or path-finding or collisions, but rather about game logics, state-driven AI, and things that involves a lot of simultaneous states and `if`s and/or `switch`es

What are the pro/cons of using either a State Pattern or a sequential check of a plain state structure like this:

```
struct States
{
bool is_walking, is_running, holds_a_weapon, is_crouch;
int weapon_id, int id_team;
};

void HandleStates (States state)
{
//etc
}

```

# Answer
> 11 votes
I will try to answer this as best as I can, but there are certain "best practices" which I am unsure on, but I'll try to break it down as cleanly as possible.

**FSMs**

Firstly, the Miner tutorial is from Programming Game AI by Example by Mat Buckland (which I do recommend you get as an introduction to AI). He uses an enum for each state, NOT a struct. With the struct in your example you have booleans as the states, so you could have any number of these on at the same time. This might lead to behaviour you want, but more often than not with FSMs (Finite State Machines) it leads to undesirable behaviour.

For example:

```
enum
{
WANDER_AROUND,
ATTACK,
RUN_AWAY,
};

```

Secondly, that's not the only way he describes states. The way I personally prefer (depending on the situation) is to create an abstract class called State that has an Enter(), Exit() and Update() functions. Then create my states as subclasses of the State class.

Like this picture (found on page 2 of that link actually):

**State Pattern**

In my personal opinion, the state pattern is just a part of software design where the software has a number of states. The *implementation* is down to the developer. I don't feel there's a proper difference between using a big switch statement or creating a complete state machine to run all your states like I've outlined above. They're essentially doing the same thing. So in that respect, the answer to one of your questions is yes, I do believe that page describes the state pattern.

**Pros/Cons**

There are pros and cons to any method you use to implement a state-driven design.

*Using an If/Else or Switch Statement*

Pros:

* Very easy to add and check conditions of states
* Can be prototyped very quickly

Cons:

* When you've got a load of states, it can turn very ugly, very quickly.
* Keeping track of transitions, effects when the state is entered/exited or anything specific to the state is difficult

*Using an object-oriented state machine*

Pros:

* Highly extensible - the only thing you need to do is create a new state that inherits the abstract State class
* Easily maintainable - You don't have to worry about spaghetti looking code as each state resides in its own class. You can easily see the conditions associated with that state without worrying about the other states.
* Intuitive - If you're working on a team project with this sort of state machine, it will be so much easier for the person reading your code. They won't have to read through lines upon lines of code just to get to a certain state ("Always program as if the programmer maintaining your code is a psychopath who knows where you live!" :))

Cons:

* Slight learning curve - This design may take a while to get your head completely round when implementing it
* I honestly can't think of any more, since I do prefer this way, but if anyone wishes to add to it, just comment and I'll add them.

I hope that answers all your questions. In fact, I've just opened up my copy of Programming Game AI by Example and Mat does mention that the state machine is known as the "state design pattern". Personally, I disagree, but to each his own.

Hope it helps :)

---
Tags: c++, ai, c, state
---


title: Online leaderboards for iPhone games

text:
# Question
Title: Online leaderboards for iPhone games
I'd like to add an online leaderboard to my iPhone game. Upon discovering the time and effort required to create a Game Center account I started considering other options.

What do you use for online leaderboards? Why?

I'm open to a variety of options including App Engine, using EC2, Open Feint, PlusPlus etc.

-- I'd like to make this a community wiki but I don't see the option.

# Answer
Go for OpenFeint, it is easy to use. Why I say that? Well, because even *I* managed to do it XD!

OpenFeint accepts achievements, leaderboards and other stuff I didn't pay much attention to. Also, if you make a decent game, the site seems to focus a lot on helping you advertise your game, making it a "free app download" for one day in the site and in another iPhone games site. It *really* drags a lot of people's attention to your game.

A lot of games use OpenFeint, so the community is decently big, and remember: players are hungry for the achievement points they get in games.

Of course, with Game Center out, a lot of people is implementing it into their games, so you still might want to give it a go.
> 3 votes

---
Tags: iphone, leaderboards
---


# Question
Title: having problems while rendering in Maya 2008
I am having problems while rendering in Maya 2008.

1 frame is taking 1 hr.

My 5 computers have config of : core i3 , 1 gb ATI radeon graphics card, 8 GB Ram.

OS: win Xp pro 32 bit.

I am giving render from command prompt.

What should be my page file size ?

How to diagnose if any problem ?

suggest tips to improve rendering time and quality ?

Also heard there are scripts and tools for rendering ?!!

I am a total newbie to maya, 3d etc and i have team of 3d artists who have inability to google and solve problems independently( due to lack of english knowledge and exposure to net) !

# Answer
> 1 votes
1 frame could take several days or a few milliseconds to render depending on the renderer, the configuration of the renderer, the complexity of the scene, the lighting and so on. Mostly it's about configuring the render though, trading off quality for speed.

This doesn't sound entirely on-topic for Game Development though. Where I come from we use progressive renderers that constantly improves on the rendered frame(s) until the time/deadline is up - that way there's much less guesswork. We're just telling the renderer that we have x amount of time so please go ahead and render this scene/animation as pretty as possible until the time is up ^^

# Answer
> 1 votes
Ok this is great example of offtopic. But i will recommend you to use some of the gpu or gpgpu renderers. If you dont own renderfarm it is great way how to render 10-300 times faster in same quality. There are some renderers to consider.

**CPU rendering is dead**

* iray Is gpgpu raytracer from Mental Images, authors of Mental Ray
* V-Ray Most famous and really good gpgpu renderer.
* FurryBall is the fastest renderer for Maya, works like game engine and that means best speed, but bad support for indirect lighting.

---
Tags: 3d, rendering
---


# Question
Title: Any ad network for XNA games on the PC platform?
There's a lot of press about the ad controls included on the new 7 phone, but I'm looking for candidates for the PC platform.

# Answer
While I am not aware of any XNA specific ad controls (heck, I do now even know a single Windows based ad platform at all and Google fails me; the only one I saw is/was used in FeedDemon seems to be HTML based The Deck and targeted at “creative, web and design professionals”, which might not intersect your audience…) I would assume that any Windows supporting platform could be used within an XNA game. However, it might involve quite a bit of work to get the ad rendered onto a D3D surface if the ad framework does not support it itself (and it might even be next to impossible). I would search for something that gives you raw text/image and a link to open as this would be the easiest way to integrate into your game.

As a side note: I have no idea how well-received an ad-supported game would be or how much revenue it could collect. The pessimist might assume that a donate PayPal button will perform better for a mid-popular game than any form of advertisement ever will…
> 2 votes

# Answer
http:// advertising.microsoft.com/mobile-apps

> Download the free Microsoft Advertising SDK for Windows Phone 7 for mobile applications using the XNA Framework or Silverlight.

http:// www.microsoft.com/downloads/en/details.aspx?FamilyID=b0f00afc-9709-4cc2-ba2c-57728db6cbd6
> -4 votes

---
Tags: xna
---


# Question
Title: What are the differences between XNA 3.1 and 4.0?
I have been away from XNA for a couple months and want to get back into it. I had a game I was currently working on, but it was done in XNA 3.1. What are the differences between the two, and is it worth updating?

# Answer
> 21 votes
I would say its very beneficial to update your XNA to 4.0 (especially if you want to work on windows phone 7)

There are a few changes (not a ridiculous amount though) between 3.1 and 4.0. Here is an excellent site that I have had bookmarked that will help you out! (its a cheatsheet) XNA 3.1 to 4.0 CheatSheet

# Answer
> 8 votes
XNA 4 restructured a lot of the graphics section of XNA, it also added support for more built in effects (as opposed to just BasicEffect.) XNA 4 also dropped Zune support and now supports Windows Phone 7 development in its Reach mode. Shawn Hargreaves posted a lot of comparison posts on his blog last year, for example here.

# Answer
> 4 votes
XNA4 introduced DynamicSoundEffectInstance which opens up **HUGE** doors for dynamic audio.

**EDIT:**

Also note that you only have until February 7th to submit XNA 3.1 games for XBLIG. See this post.

# Answer
> 1 votes
There are a few breaking changes, as Shawn Hargreaves outlines here, as well as new features, et cetera. A discussion of "what's new" in XNA 4.0 can be found in the XNA documentation on the MSDN site. You'll have to evaluate the new features and changes in the context of your current game and see if its worth upgrading -- certainly I'd think you should do it for new games.

---
Tags: xna, c#, xna-4.0
---


# Question
Title: What is the ballpark GL framerate for iPad and iPhone 4?
Does anyone the GL frame rate for iPad and iPhone 4 under the follow conditions:

* Unlit
* Non supersampled
* GLSL texture mapped with two textures.
* Single quad, 4 vertices

Thanks,
Doug

# Answer
> 3 votes
60fps, if nicely vsynced?

If you're looking for (un-vsynced) big numbers like '1000fps', stop thinking in framerates and start thinking in milliseconds-per-frame. The numbers are a lot more meaningful that way around (You won't panic when your first draw call halves your framerate...)

# Answer
> 3 votes
According to Apple, iOS devices max out at 60FPS.

---
Tags: iphone, opengl-es, ipad, frame-rate
---


title: How to create a mini-game?

text:
# Question
Title: How to create a mini-game?
I am wondering how to creat a mini-game like "Diner Dash" or like "Big Fish Games". I want my game to be 2d, but it looks like 3d: see this image. http://www.topxgames.com/bigfish/diner-dash-flo-through-time/screen1.jpg Also, if you know some good game-engine to create games like those then thanks a lot in advance.

# Answer
> 7 votes
I'm assuming that you are confusing the term "mini-game" with "casual game." I'm going to attempt to answer you with the assumption that you are talking about creating a casual game, which is still a very broad question, but I'll try to give it a stab from a high-level; however, if you really do have a full game and are just looking to add mini-games to it, I don't know what I can offer to guide you there.

Some key concepts for casual games, are (all my opinion):

* **Quick to play**, that is to say your game should have gameplay that is very simple to pick up and just play. You shouldn't have a "tutorial mode" or any of that, it should be so simple anyone can figure it out.
* By extension of quick to play, most popular casual games have gameplay that is on the shorter end of the spectrum, 30-90 seconds is common.
* Progress after a gameplay period should be saved.

I can only speak for myself, but XNA has a very low cost of entry, the learning curve is small if you already are familiar with C++ and/or Java. It also lets you deploy your game to Xbox, Windows Phone, and PC.

As @Spooks said, 2D games that appear to be 3D are frequently called 2.5D or pseudo-3D. And is typically done with 2D sprites that appear to be 3D.

# Answer
> 5 votes
The 2D game but looks 3D is sometimes referred to as 2.5D. As for creating a mini game, that is a very broad question. You need to first pick a language you want to work in, then maybe we can provide you with a game-engine, but even with a game engine, you still need to know how to program, and edit the game engine.

---
Tags: xna, directx, unity, unreal
---


# Question
Title: How to manage dependencies between tile map and units
I have a 2D tile-based strategy in the works. I'm wandering how to handle the relationship between the map and the units on the map.

Given a tile coordinate I'll need to be able to get the unit standing on it, if any. At the same time, if given a unit I'll want to be able to get the unit's coordinate.

I've seen two solutions to this. The first solution would be to have units store a coordinate and the map store unit references in its tiles. This creates a cyclic dependency between the map and units. I'd need to make sure that the map an any unit are kept in sync if the unit moves.

The second solution would be to only have the units keep track of their coordinates. To tell if a tile contains a unit and to get that unit, I'd loop through the whole set of units unit I find one with matching coordinates. That get rids of the cyclic dependency, but it looses the O(1) property the first solution had for looking up units from the map. This may add up as I want to be able to scan the map regularly for things such as path finding, determining movement range, and finding valid targets for a given unit.

I also can't just store the units in the map (or can I?). Units are associated with "armies", either player or AI. An army should be able to easily access and iterate over all of its units.

Since this appears to be a common issue in strategy games, are there any other patterns besides the two I described for managing unit/map relationships?

# Answer
> 3 votes
It's not a popular pattern but the relational database world offers a third way: use a data structure that has multiple keys. In tabular form, it might look like this:

```
Unit id    Location
-------------------
  1309     13,15
  2357      7,93
  8552      7,93

```

You want to be able to ask, “where is unit 2357?” and get back 7,93. You also want to be able to ask, “what's in location 7,93?” and get back 2357 and 8552. There are data structures that allow multiple keys for looking things up. You can store this outside the units and outside the map if you want to remove dependencies.

However, in practice it's more common to store location in each unit, and then on the side use a spatial partitioning data structure that tells you what units are in a given region. Since it's a separate structure, the regions don't have to be grid spaces; they can be larger areas.

I recommend doing whatever's easiest (your second solution) and then later if it's a performance problem you can add a spatial partition to make lookups faster.

# Answer
> 5 votes
Well, you unless you several thousand units per player, I wouldn't worry about memory usage, and use the first solution. Memory is cheaper than CPU it seems.

In fact even if you had 4000 units per player, using two integers to store there location, and 8 players, that only takes 2MB, but with the first solution, you get to use a O(1) co-ord getter, rather than O(n) (assuming unsorted), which with a lot of units could be slow.

Most games seem to be pixel based, rather than tile, now a days so they only need to get the unit to store the co-ords.

---
Tags: tiles, maps, character
---


title: D3D9 Effects- variable parameters

text:
# Question
Title: D3D9 Effects- variable parameters
I've created some simple Phong shading code from a sample. The issue is that the sample only handles one light. If I wanted a variable number of lights set at the start of each frame, how could I specify in the effect file that I need to pass a variable number of e.g. light positions and etc to render from?

# Answer
> 5 votes
For each light do one render pass and use Additive blending. It is called *forward rendering*.

Question is: Why to do it this way and not just send all of the light positions and params in few arrays? Answer is that this is much easier to handle once you start making some more complex effects. And there is one plus more. You can use your current shader.

**Edit:** To prove my point, i added two renders, because this technique sometimes sounds weird. One is rendered with gpu renderer which using described technique. And second is same scene rendered with Maya. Scene is lighted with 3 lights. One emits red, one blue and one green color. Common shadow mapping is used.

Realtime renderer:

Rendered with maya

---
Tags: c++, directx9
---


title: How to implement zombie AI?

text:
# Question
Title: How to implement zombie AI?
We need to make a zombie videogame for a semester project and I was wondering about what are considered nice algorithms/techniques for implementing zombie AI that don't take too long to implement.

The project is a videogame **product**, involving other stuff as physics and multiplayer, so we have limited time, so what I'm specifically looking for is:

* A **quick & dirty** way to implement zombie AI (I'm thinking on **neural networks** or perhaps even **fuzzy logic**)
* Common ways of implementing and optimizing zombie AI
* The ideal way of implementing zombie AI (I imagine it would involve **pathfinding**, or even **swarm intelligence**?)
* General advice on zombie AI

Considering that the quick & dirty implementation would perhaps be a place-holder for another and better algorithm/technique.

Thanks in advance.

# Answer
First of all, DON'T use neural nets. They're simply not applicable to this (unless you have some real life zombies where you can get some training data :) )

Just to clarify neural nets and fuzzy logic are not quick and dirty ways of implementing AI. They're fairly in depth (neural nets, more so than fuzzy logic).

Secondly, unless your zombies are clever, they might not need pathfinding at all. Sure it's useful to avoid obstacles, but there are simpler ways of achieving that.

If your semester is around 10 weeks long (approx) you're going to be getting stuck on more important things than the AI (that's not a criticism on your coding skills, it's just usually how it happens unless your design stage is almost perfect). Therefore *simplicity is key* here.

The simplest thing to do is to combine a number of steering behaviours. Simple behaviours merged together can create intelligent looking behaviour (this is called emergent behaviour if you're interested, and is what swarm intelligence and flocking is based on).

The behaviours I'd suggest you use are:

* Seek
* Wander
* ObstacleAvoidance
* WallAvoidance
* Cohesion
* Alignment
* Separation

These behaviours are collectively known as *steering behaviours* and this link will show you exactly how they work (albeit without source code): Steering Behaviours

Read Programming Game AI by Example, as those behaviours are very well documented (or you could just find the source code somewhere).

Cohesion, Alignment and Separation are behaviours that work together to create the "flocking" effect. Cohesion makes sure that each zombie moves towards the average position of the flock. Alignment makes sure the zombie aligns with the average orientation of the flock. And finally Separation just maintains a distance from the zombie's neighbours.

You can optimize this by having each zombie have a "neighbourhood" region, so the zombie will only check it's neighbours for the appropriate values.

If you have a fairly small game world, you can use a grid based partitioning system to optimize further as it's relatively simple to code and won't take up much memory since the world is small. If it's larger, consider using a quad-(oct-)tree. If it's an indoor level, consider using BSP.

But to sum up, keep it as simple as you can. Simple behaviours are easier to debug and when combined they look very impressive. And don't use neural nets, whatever you do.

P.S. If you're allowed to use external libraries, try and use OpenSteer :)

Hope that helps.

Ray
> 19 votes

# Answer
You may be over-engineering it, a basic implementation is just a state machine with a state "Shamble" which will cause the zombie to move around a bit (checking it won't hit walls and such perhaps, or stay out of the light etc, it can be expanded upon) and a "Follow" which will cause the zombie to move toward a player (maybe using path finding like A\*) and attack him/her if the zombie gets to close.

This will be fairly "realistic" (as far as zombies go) because players usually don't look at enemies for a long time (they usually run from them/attack them).
> 9 votes

# Answer
I'm taking all my zombie-related facts from the Zombie Survival Handbook. Which, on a tangent, is a very entertaining read.

A stereotypical zombie would be very stupid - so it wouldn't need AI for things like:

* Opening doors, though it could probably break them (if you choose to go for a destructible route)
* Any kind of tactics
* Climbing, or the Z-axis at all.
* Swarming.

Instead, you would want zombies to do things like:

* Walk around aimlessly until they get a target
* Chase the target until it disappears
* Follow the trail of the lost target for a short time
* Repeat

I'm pretty sure a simple state machine would be useful - either WANDER, FOLLOW, OR LOST.

As for the target searching, each zombie could have a field-of-vision check. If target can be seen, change state and set the direction to go.
Something interesting may be to have different target checks. Not just if a zombie sees you, but perhaps if you wandered an area you could leave a 'scent trail', putting a zombie into the LOST state? Or if you fired a large weapon, the zombie would be attracted to your position in the LOST state? This second one could have an area-of-effect radius, giving a swarm-type pattern since all the zombies will end up in one area, and then move as one.

As for implementing, it wouldn't be much more than having a check to see if the player has been seen, then some very dirty pathfinding - quick and dirty rather than something like A\* - a zombie isn't going to go the optimal route - and a state machine. Just make sure that your random walk does have some form of obstacle avoiding - I really hate it when enemies just run into buildings for ages. ;-)
> 4 votes

# Answer
I think whats complicating your project is the fact you are trying to make Artificially Intelligent Zombies.

As another poster stated, I think you over engineering your project. Think about a couple "states" you want your zombies to have.

1) Searching/moving aimlessly

2) Pursuit/Chase

These come to mind, you might consider more for uniqueness.

The nice thing is zombies don't really act intelligently, use this to your advantage!
> 3 votes

# Answer
You're going about it all wrong! Zombies are stupid!

```
if CanSeeCharacter()
    IterateLegalMoves()
    Pick the move that ends up as close to the character as possible (by crow only)
else if Dice < 5%
    PickRandomBearing()
else if Position + Speed * CurrentBearing is legal
    Move()
else
    PickRandomBearing()

```

No pathfinding, let them get stuck. That's how zombies should behave. If there's enough of them the crowd will fill in any dead ends and force the additional zombies to go around so they can actually get to the character.
> 1 votes

---
Tags: software-engineering, ai, game-mechanics
---