# Question
Title: Programming Languages Recommendations:  A Space shooter game that allows two people to play
Do you remember an arcade game, that allowed two people to versus or play each other? It was a Galaga/Gradius type game.

Me and a couple of other people I know want to make a game like this. We want to get some other opinions on what programming languages to use. (C or C++ isn't an option).

We plan to use an engine to help us build the game and it's going to be a multiplayer game, so we would be handling the networking with this language as well.

We are thinking about C#, Java, or Actionscript 3.

Any advice on this? And if anyone knows the arcade game I am referring to please post up!

Edit

Let me add something here, this game will be played on computers and laptops only. We mainly want to know what's good for handling the networking and Dual screen play.

# Answer
> 5 votes
C# and XNA will allow you to develop for Windows, XBox, and Windows Phone. It supports multi-player two former platforms. One of the game samples that comes with the developer tools used to be a space shooter.

In my experience it has a very low barrier to entry, the tools are free for Windows, and only $99/year for XBox and Windows Phone.

# Answer
> 4 votes
Whichever language you know best, and suits your end product. If you're not wanting a web game, Actionscript is out the window. If you don't know Java, why bother with it?

On a more concrete note, I would probably go for C# or Java.

Then again, I'm pretty sure Unity might work too.

# Answer
> 3 votes
Looks like you're trying to make something 2d and relatively simple. I'd say go for PyGame (a game library for python); if you were going 3d I'd say Unity.

---
Tags: c#, software-engineering, java, actionscript-3
---


# Question
Title: Can I write plugin/extension to Unity editor?
Is there possiblity to write my own plugin/extension to Unity editor ? I want to write plugin to generate map for me from xml file.

# Answer
> 8 votes
"Plugins" in Unity nomenclature mean native code (read: written in C/C++/Objective-C) DLLs. For what you want to do you more than likely don't need (or want, really) to use plugins.

For extensions, the Unity editor is very scriptable.

Are you asking if you can

1. Populate a unity scene at editor time from an XML file
2. Replace unity's default scene format entirely with an xml file.

Either way, what you're asking is more than possible. Here's an example of somebody completely replacing Unity's binary scene file format with a text representation: https://github.com/terravision/UnityTextScene

What you probably want to do is more likely just take advantage of their editor scripting tools. For example, look at ScriptableWizard. You can take that base code and then do something like load an XML file and spawn a bunch of prefabs, or whatever.

Pretty much the vast majority of things you see in the editor is scriptable. You can attach components, move/rotate/scale things, spawn prefabs, edit materials, all sorts of things.

# Answer
> 0 votes
Yes - look on the Unity Manual:

http://unity3d.com/support/documentation/Manual/Plugins.html

The manual also points you to further reading by providing things like the simplest plugin project - you could use this as a starting framework

# Answer
> 0 votes
Chances are that you are using the free version of Unity. As such, you cannot write plugins unless you use the Pro version.

If you are using the Pro version, then check the manual.

---
Tags: unity, extension, editors
---


title: Setting effects variables in XNA

text:
# Question
Title: Setting effects variables in XNA
I am currently reading a book named "3D Graphics with XNA Game Studio 4.0" by Sean James and have some questions to ask :

If i create a effect parameter named lets say SpecularPower and have in my effect a variable named SpecularPower , if i do something like

> effect.Parameters\["SpecularPower"\].SetValue(3)

That wil change the SpecularPower variable in my effect ?

And a second question, not regarding the book : If i have a spaceship and i've created a "boost" functionality that speeds up my spaceship, what effects should i implement to create the impresion oh high speed ? I was thinking of making everything except my spaceship blurry but i think there would be something missing . Any ideas ?

Regards, Alex Badescu

# Answer
> 2 votes
`Parameters` is an EffectParameterCollection, which is indexable by string and integer. Indexing it by string returns an EffectParameter for the named parameter, which can be used to assign values to that parameter, as illustrated in the link documentation.

In short, the answer to your first question is "yes."

---
Tags: xna, effects
---


title: Texture artifacts on iPad

text:
# Question
Title: Texture artifacts on iPad
I'm porting an iPhone game to the iPad. When I move textures "quickly" (5.0 pixels every update at a rate of 60 Hz) I start to see little "artifacts" or remnants of where the texture used to be. I'm not sure if I know the correct terminology for this... imagine a texture at some location on the screen... then next to it is the same texture but faded a bit... then the same texture again just faded a bit more.

I'm using CADisplayLink to drive my update loop if that helps. Also I didn't see this issue on the 3G or the iPhone 4. Any ideas?

Cheers!

# Answer
> 1 votes
I don't know whether you mean this or not ..but i have this problem when i'm using render Texture in cocos2d.When the player sprite is moved,the sprites residue used to be ther for 3-5 frames.Clearing the alpha of the render texture fbo fixed the problem.Please mention the problem clearly if you have still problems.

\[Updated\]

Once have a look at the below link (please check the afterRender method)

http://code.google.com/p/cocos2d-iphone/issues/detail?id=631&q=glClear%28GL\_COLOR\_BUFFER\_BIT&colspec=ID%20Type%20Status%20Priority%20Milestone%20Component%20Owner%20Summary

Here the fix was to clear the RenderTextures's Alpha channel with 1.0 so that it will not have artifact when you draw other nodes on RenderTexture.That clearing should be done once you are done drawing on the renderTexture. Please let me know if you need further clarification.

# Answer
> 1 votes
Judging from a quick google search at least some (possibly defective, or at least less-than-perfect) iPads suffer from ghosting. Is this what you're seeing?

The youtube link above says the person has replaced his ipad with a functional one, and the other link suggests if you see clear ghosting, you should return your ipad.

---
Tags: iphone, graphics, opengl-es, ipad, cadisplaylink
---


# Question
Title: J2ME character animation with multiple sprite sheets
I'm working on a J2ME game and I want to have walking animations.

Each direction of walking has a separate sprite sheet (i.e. one for walking up, one for walking right etc), I also have a static idle image for each direction held together in a single file. I've tried to hold an array of sprites in my player class and then just drawing the sprite corresponding to the current direction, but this doesn't seem to work.

I'm aware that if I combine all the animations into one sprite sheet I could set up different animation sequences, but I want to be able to do it with separate images for each animation.

Is there a way that anyone knows of to achieve this? And ideally without too much extra code (as opposed to combining the sprites into one sheet)

# Answer
> 1 votes
As you said each direction of walking had a sprite sheet.Some thing like this structure will help.

Have the 0'th index as the static IDLE image.When you want to animate just update the animation Index to draw the rest of images in that sprite Sheet.

```
if(animate)//Just a rough code...you can optimize better ;)
{
     animIndex++;//animIndex is the current Frame of the animation
     draw(currentSpriteSheetImages[animIndex]);//currentSpriteSheetImages holds the set of images created from a sprite sheet
}
else
{
      draw(currentSpriteSheetImages[0]);//drawing the idle image
      animIndex = 0;
}

```

Btw, Just for some more info...As J2me devices have less memory,its better if you follow some thing which will create sprites with minimum memory footprint.I recommend you to check this useful tool.\[http://www.motionwelder.com/tutorial.php\]

---
Tags: 2d, java, animation, sprites
---


# Question
Title: How much is java used in 2d/3d indie games? (before/after Minecraft)
I wonder for my own use and curiosity, how popular is Java in indie game development , in 2d and 3d? Are there any good open/closed source games done in java?

# Answer
> 12 votes
Java is the language used for Android games. (I believe there may be some other methods like using C++ but its usually Java). If you have an Android phone, you can test the top-downloaded games to see good examples.

I think it's good for indie development - in fact I am doing an indie game for android. There are many tools that Google provides for you - such as debugger, emulator, memory allocation tracker. You can also use the Eclipse IDE with it.

There is also a lot of code online and the StackOverflow site if you get stuck on a bug. Also, Android supports openGL for 2D/3D games (though you can make a 2D game without it - as I am doing).

# Answer
> 14 votes
It's not terribly popular, in my experience. There's a few problems. First off, Java isn't the most efficient language around (though better than many think), but that lack of efficiency isn't really compensated for by ease of development. Second, running Java is kind of a pain - it's gotten better recently, but it's still tainted by Java's legendary growing pains. Third, Java hasn't had particularly good graphics support in-browser, and if you're outside the browser, you may as well use something else.

It's not really a matter of Java being bad. It's a matter of Java not being particularly good for any game-related niche, and other languages actually being good. The language that does everything in a mediocre fashion loses to the languages that do something well.

There's a list of famous Java games on this very site, but, well, you can see how popular it is.

# Answer
> 1 votes
Not quite answering the question, but javagaming.org has a non-exhaustive list of commercial Java games here.

---
Tags: java, 2d, 3d
---


title: Promoting independent iOS games

text:
# Question
Title: Promoting independent iOS games
> **Possible Duplicate:**
> What are effective marketing strategies for iPhone games?

I'm interested in promoting my latest iOS game. **What have you done that really helped spread the word**? Any smaller game review sites that were helpful? How about publishing?

# Answer
> 1 votes
Try making flash demo and post it on Newgrounds or other flash portals. Make sure you add information about your game. If the flash game is good, then people will buy the app. Otherwise, you can go with traditional promotion by contacting game review or game blog or youtube channels such as rock paper shotgun, wikigames, machinama, IGN etc.

---
Tags: publishing, ios, revenue, marketing
---


title: The practical cost of swapping effects

text:
# Question
Title: The practical cost of swapping effects
I use XNA for my projects and on those forums I sometimes see references to the fact that swapping an effect for a mesh has a relatively high cost, which surprises me as I thought to swap an effect was simply a case of copying the replacement shader program to the GPU along with appropriate parameters.

I wondered if someone could explain exactly what is costly about this process? And put, if possible, 'relatively' into context?

For example say I wanted to use a short shader to help with picking, I would:

1. Change the effect on every object, calculting a unique color to identify it and providing it to the shader.
2. Draw all the objects to a render target in memory.
3. Get the color from the target and use it to look up the selected object.

What portion of the total time taken to complete that process would be spent swapping the shaders? My instincts would say that rendering the scene again, no matter how simple the shader, would be an order of magnitude slower than any other part of the process so why all the concern over effects?

# Answer
The problem you are describing is not a "special" problem. There's nothing especially slow about changing effects on the GPU. The problem with changing effects, effect parameters (including transformations), textures, various render states, and simply sending multiple draw commands, is that it necessitates that **another batch must be sent to the GPU**.

Batches are **CPU**-bound and you only get **a few thousand per frame** to use.

It depends on the CPU and what other work you are doing, but let's say you get about 1000 batches per frame. If you are rendering one object per batch, you can draw about 1000 objects on screen before you hit problems.

If you suddenly add picking, and you have to render all your objects twice, then you are limited to drawing only 500 objects.

(So if you've only got a small number of objects, then don't worry about it!)

To reduce the number of batches you are using, you basically have to "be clever" about it. The prototypical method for doing this is to cleverly combine multiple objects into a single batch. In particular, look up "**instancing**". Perhaps you can use the instance number to assign a unique colour to each object within your shader.

Another technique, especially suitable for picking, is to **cull** the rendered objects in software so that you're not rendering anything you know is not touching your picked pixel.

Here's an entire presentation slide deck from NVidia titled "Batch, Batch, Batch: What Does It Really Mean?" (PDF) that has nice graphs and stuff explaining this. It also lists some techniques for reducing your batch count.
> 21 votes

---
Tags: xna, shaders
---


# Question
Title: Game actions that take multiple frames to complete
I've never really done much game programming before, pretty straightforward question.

Imagine I'm building a Tetris game, with the main loop looking something like this.

```
for every frame
    handle input
    if it's time to make the current block move down a row
        if we can move the block
            move the block
        else
            remove all complete rows
            move rows down so there are no gaps
            if we can spawn a new block
                spawn a new current block
            else
                game over

```

Everything in the game so far happens instantly - things are spawned instantly, rows are removed instantly etc. But what if I *don't* want things to happen instantly (i.e animate things)?

```
for every frame
    handle input
    if it's time to make the current block move down a row
        if we can move the block
            move the block
        else
            ?? animate complete rows disappearing (somehow, wait over multiple frames until the animation is done)
            ?? animate rows moving downwards (and again, wait over multiple frames)
            if we can spawn a new block
                spawn a new current block
            else
                game over

```

In my Pong clone this wasn't an issue, as every frame I was just moving the ball and checking for collisions.

How can I wrap my head around this issue? Surely most games involves some action that takes more than a frame, and other things halt until the action is done.

# Answer
The traditional solution to this is a finite state machine, which is being suggested in several comments.

I hate finite state machines.

Sure, they're simple, they're supported in every language, but they're such an amazing pain to work with. Every manipulation takes a ton of bugprone copy-and-paste code, and tweaking the effect in small ways can be a huge change to code.

If you can use a language that supports them, I recommend coroutines. They let you write code that looks like:

```
function TetrisPieceExplosion()
  for brightness = 0, 1, 0.2 do
    SetExplosionBrightness(brightness)
    coroutine.yield()
  end

  AllowNewBlockToFall()

  SpawnABunchOfParticles()

  RemoveBlockPhysics()

  for transparency = 0, 1, 0.5 do
    SetBlockTransparency(transparency)
    coroutine.yield()
  end

  RemoveBlockGraphics()
end

```

Obviously rather pseudocodey, but it should be clear that not only is this a simple linear description of the special effect, but it easily lets us drop a new block *while the animation is still finishing*. Accomplishing this with a state machine will generally be ghastly.

To the best of my knowledge, this functionality isn't easily available in C, C++, C#, Objective C, or Java. This is one of the main reasons I use Lua for all my game logic :)
> 11 votes

# Answer
I'm taking this from Game Coding Complete by Mike McShaffry.

He talks about a 'Process Manager', which boils down to a list of tasks that need to be done. For example, a process would control the animation for drawing a sword (AnimProcess), or opening a door, or in your case, make the row disappear.

The process would be added to the process manager's list, which would be iterated every frame and Update() called on each. So verymuchlike entities, but for actions. There would be a kill flag to remove from the list when it has finished.

The other neat thing about them is how they can link, by having a pointer to the next process. In this way, your animate row process may actually consist of:

* An AnimationProcess for the row disappearing
* A MovementProcess to remove the pieces
* A ScoreProcess to add points to the score

(Since processes can be one-use things, conditionally there, or there for X amount of time)

If you want any more details, ask away.
> 8 votes

# Answer
You can use a priority queue of actions. You push in an action, and a time. Each frame, you get the time, and you pop off all actions that have a time specified as before that time and execute them. Bonus: Approach parallelises nicely, and you can actually implement almost all game logic this way.
> 3 votes

# Answer
You always need to know the time difference between the previous and the current frame, then you've got to do two things.

-Decide when to update your model: eg. in tetris when a row removal begins, you don't want stuff collide with the row anymore, so you remove the row from the 'model' of your application.

-You then have to handle the object that is in a transitioning state to a separate class that resolves the animation/event over a period of time. In the tetris example you would have the row fade out slowly (change the opaqueness each frame a little bit). After the opaqueness is 0 you transfer all blocks on top of the row one down.

This might seem a bit complicated at first, but you will get the hang of this, just make sure to abstract a lot in different classes, this will make it easier. Also make sure that events that take time, like the removing of a row in tetris, are of the kind "Fire and Forget", just create a new object that handles everything that needs to be done automatically and that, when everything is done, removes itself from your scenegraph.
> 1 votes

# Answer
You need to think of the game as a "finite state machine". The game can be in one of several states: in your case, "expecting input", "piece moving down", "row exploding".

You do different things depending on the state. For example, during "piece moving down" you ignore player input, and instead animate the piece from its current row to the next row. Something like this:

```
if state == ACCEPTING_INPUT:
    if player presses any key:
        handle input
    row_timer = row_timer - time_since_last_frame
    if row_timer < 0:
        state = MOVING_PIECE_DOWN
elif state == MOVING_PIECE_DOWN:
    piece.y = piece.y + piece.speed*time_since_last_frame
    if piece.y >= target_piece_y:
        piece.y = target_piece_y
        state = ACCEPTING_INPUT

```
> 0 votes

---
Tags: architecture, animation, game-mechanics, game-loop
---


# Question
Title: Understanding the Microsoft Permissive License
I want to use certain parts of the Game State Management Example in a game I'm making, but I'm not sure how to do this legally. It says in the license that I'm supposed to include a copy of the license with it. So if I make a Visual Studio Solution, I just add the license.txt to the solution? Also, if I use a class and change it, do I have to keep the license info at the top or add that I changed it or what?

# Answer
> 3 votes
I am not a lawyer.

3.D says that a distribution of the source code must include the license; if you don't distribute the source code, you don't need to worry about that sentence. 3.C says that you may not remove any of the notices it mentions, if they are present. That would include a message printed on the screen or a credits dialog.

If you change one of the source classes, I would keep the license info at the top; you don't need to add that you changed it, but it might be a nice thing to add a note saying so.

In general, this is a pretty standard-looking open-ish source license that does a few things to cover the contributors' asses but doesn't require you to do much to comply with it.

---
Tags: xna, licensing
---


# Question
Title: What is the recommended library for using Lua from C++?
I am currently planning how to integrate Lua scripting in my 2D Game Engine, and i would like to go straight to the most adequate solution for having C++ classes and objects exposed.

I've read this (if it helps you help): http://lua-users.org/wiki/BindingCodeToLua

If you have a better scripting language to recomend, go for it ;D

All help is welcome, i need to pickup the best solution to start implementing Thanks

# Answer
> 4 votes
If the primary quality of your scripting language is easy binding, try AngelScript. It can call registered functions directly without the need to write proxy functions, and it supports calling conventions of wide variety of compilers. The language itself is similar to c/c++, which may be a good or a bad thing, depending.

# Answer
> 7 votes
I've heard good things about LuaPlus. It wraps the low level C API into a higher level C++ one.

# Answer
> 4 votes
As long as you're doing reasonably conventional binding, LuaBind will do everything you need. Binding classes and functions tends to be a one-line-per-function deal. If you'd like an example, here's the applicable file from the game engine I've been working on (look for module(L) for the start of the LuaBind interface, DontKillMeBro\<\> is a little system I rigged up to let me more precisely time object destruction for certain sensitive objects.)

If you want something more complex, you're probably going to need to use the actual Lua API. Luckily, the Lua API is reasonably simple.

# Answer
> 1 votes
We're using OOLua for Pioneer. It gives a pile of macros that you use to bind Lua "classes" to C++ classes. Its got a fair bit of power but is pretty straightforward. I haven't used any others so I can't comment on how it compares. Here's an example.

# Answer
> 1 votes
I'd go hands down with Nuclex's precompiled libs and include files for LuaBind. (that is if you're working with VS2008)

Since LuaBind requires you to build it with some Boost libs and tools, this package will save you valuable time (and maybe some headache, who knows). I'd say you'd be able to get Lua running in less than an hour if you know what you're doing.

You may also consider changing the default Lua dll to a LuaJIT dll if you're looking for a small performance gain. It's only a matter of compiling the library and replacing the lib/dll you're linking against in your main project, so it's quite easy.

With that, good luck!

---
Tags: c++, lua
---


# Question
Title: Strange javascript error when using Kongregates API
In the hopes of finding a fellow unity3d developer also aiming for the Kongregate contest..

I've implemented the Kongregate API and can see that the game receives a call with my username and presents it ingame. I'm using `Application.ExternalCall("kongregate.stats.submit",type,amount);`

where `type` is a string "Best Score" and `amount` is an int (1000 or something).

This is the error I'm getting:

> You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.
>
> ```
> callASFunction:function(a,b){if(FABrid...tion, can be used as a workaround.");
>
> ```

I'm wondering, has anyone else had this error or am I somehow doing something stupid?

Thanks!

# Answer
I don't know how, but I solved it by making sure the API was only initialized once. The problem with that is that if the person playing is a guest, it's impossible to get to know when the player logs in during play. I solved that with a work around, giving the player the possibility of manually saying when he/she has logged in. Not beautiful but works in war.
> 0 votes

---
Tags: unity, javascript
---


# Question
Title: Creating an alphabet with numbers in 3d using opengl-es
How should I create an alphabet with numbers in 3d in opengl-es? I'm trying to create them with the existing primitives, but it's not looking good. Do we have any alternate way to get these things done? If so, please let me know! Thanks in advance.

# Answer
I understood you are trying to create numbers and alphabets from primitives manually. You can create them in some modeling program (like Blender, which is freeware), it should be easier and you could get good results.
> 2 votes

---
Tags: iphone, opengl-es
---


# Question
Title: Game engine with good Lua entity creation/management
I'm looking for an engine that constructs it's entities using Lua or other scripting language. This is in order to find inspiration and do it in my own engine as well.

I know that CryEngine does use Lua to make their entities, but I wanted to know if there are some other alternatives that I can look up.

Thanks!

# Answer
> 7 votes
I'd recommend taking a look at LÖVE "an *awesome* framework you can use to make 2D games in Lua. It's free, open-source, and works on Windows, Mac OS X and Linux." It's **clearly** not an alternative to the Cryengine, but should certainly demonstrate how to effectively utilize the potential of Lua for entity creation and game logic. Combine that knowledge with how Cryengine/other AAA engines utilize script backends, and you should have all the inspiration you need to create your own engine with robust scripting capabilities. :)

# Answer
> 4 votes
To the best of my knowledge Relic's Essence Engine Series (as used in *Company of Heroes* and *Dawn of War II*) uses Lua or a dialect of it for unit stats and mission scripting. There are no real web sources for it, but you could always check out some of the mods at RelicNews.com to ask your way around if you are interested.

The Spark Engine by Unknown Worlds as used in their upcoming game *Natural Selection 2* allows most of the game code to be in Lua as far as I know. The SDK comes with the game pre-order and is currently in beta as is the game.

Another game that was once promoted heavily relying on Lua would be Eufloria (formerly Dyson). There is a Lua modding reference on their forums as well.

Valve's free co-op game Alien Swarm heavily uses a scripting language called "Squirrel" that has been influenced by Lua. The Alien Swarm SDK should be available for download on Steam. (Dev wiki)

EDIT: How could I have forgotten about World in Conflict! The game does a whole lot of stuff in Python as becomes obvious when looking at mods like the Modern Warfare Mod that implement completely new mechanics.

# Answer
> 2 votes
Here are some examples of (open source) games that use scripting to implement entity behaviour:

Frogato implements entities using a custom scripting language. Battle for Wesnoth implements entities using a custom description language in which Lua scripts can be embedded. KQ implements entity behaviour using Lua scripts.

Edit: Posted links now that I'm allowed to...

# Answer
> 2 votes
I do that in my engine (source available, but probably not worth deciphering).

In my case, an "entity" is a concept that exists wholly within Lua. There's no C++ backing for "entities". As such, an "entity" is whatever that specific game needs. Sometimes it's just a table with a little data attached to it, sometimes it's a 2d Frame element (note that Frames are entirely Lua constructions as well, I just have a standard UI library), sometimes it's something complicated with AI and rendering and then it's still just a thing created in Lua.

Many people use Lua to script object systems that have C++ backing, such that the entity "lives" in C++ and calls Lua for its scripting. I used to do that, but I found myself getting happier and happier as I moved code out of C++ and into Lua. At this point, I use C++ solely to handle the OS API calls, and all layout/rendering/AI/game logic is in 100% pure Lua.

Recommended.

Feel free to ask questions, I'm quite willing to answer :)

---
Tags: entity-system, scripting, lua
---


title: Pleasing isometric hexagons

text:
# Question
Title: Pleasing isometric hexagons
What angles and long-side/short-side ratios give the most aesthetically pleasing and graphically regular isometric (squashed and flat side up) hexes, that additionally resolve to whole pixel sizes for several sizes when rendered?

# Answer
> 14 votes
Since you presenting the hexmap through an isometric view that shifts things around.

Here is the traditional version with horizontal hexes that are effectively squished in the vertical axis to make a pseudo-isometric look.

This takes a different approach with the hexes that are rotated to present no vertical or horizontal lines.

Either style can work, just depends on what you want to do, the primary direction players will move through the world, and how much you want to avoid zig-zagging.

# Answer
> 5 votes
By "flat side up", I assume you mean "flat side horizontal" (as "up" could mean either the edge itself points up or it "faces" up, i.e. its normal points up).

I experimented with both orientations for a game I developed in college. Personally, I found "flat side vertical" hexagons more pleasing on the eyes. I could certainly be in the minority here, but I believe Civilization V uses the same orientation, so I'm definitely not alone. If you're not dead set on using one orientation over the other, then I suggest you experiment with both. Since most of the online resources I've found regarding hex grids use the "flat side horizontal" orientation, many equations you come across may require adjustments; this site should help.

I built my project with a resolution-independent UI framework that performed device pixel snapping automatically, so I didn't spend much time tweaking the angles and ratios. I believe each of my hexes had a bounding box of 96 device independent pixels squared (96 device pixels on a standard 96dpi display with scale = 1.0). You should be able to derive the rest from the screenshot :).

# Answer
> 3 votes
These are for flat side horizontal. The terminology I am using is from Amit's thoughts on grids page, with the additional language of "narrow side length" meaning the length of the squished non-horizontal sides.

http://www-cs-students.stanford.edu/~amitp/game-programming/grids/hex-grid-metrics-labeled.png

equilateral (0 degree projection):
"height" = L√3
"wide width" = L
"narrow width" = L√3
narrow side length = L
45 degree projection:
"height" = L
"wide width" = L
"narrow width" = 2 * √(3/8)L
narrow side length = √(2)L
60 degree projection:
"height" = (3/2)L
"wide width" = L
"narrow width" = 2 * √(3/4)L
narrow side length = √(13/16)L
I calculated these by hand, so please check my work.

---
Tags: game-design, graphics, tiles, isometric, hexagonal-grid
---


# Question
Title: Multiple Sprites using foreach Collison Detection in XNA (C#)
Back again from my last question. Now I was curious I use a foreach statement to use the same shot class. How would I go about doing collison detection.

I used the tutorial here on how to shoot a fireball
XNA Development: Game Development for the masses.

I tried to put in several places a foreach to look at all of them to see if they have reached the borders of my sprite hero but doesn't seem to do anything. If again some one might know of a good site that has tutorials to explain collision detection a little bit better that would be appriecated.

# Answer
> 0 votes
The fireball is a 'box' of width and height 200. And it's at a given position. Add a rectangle

```
Rectangle boundingRect = new Rectangle(position.X, position.Y, 200, 200);

```

to your fireball class.

Make sure to update the rectangle with the new position of the fireball every frame (so in the fireball's update or draw method)

Do the same thing for your player class.

Now you can check if the fireball has hit the player like this in your game's update method:

```
if(fireball.boundingRect.Intersects(player.boundingRect)) {
    //hit
}

```

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


# Question
Title: Keeping game model and graphics/animation separate but in sync
Suppose I'm building a chess game where I want to have animations. Pieces glide to their new squares when moved. Pieces perform attack animations when capturing other pieces.

I'm not sure how to effectively separate the data and logic needed for these animations and the actual game model (in the MVC sense). The pieces themselves should ideally not have to worry about their pixel coordinates or current animation frame. At the same time, many changes to the model are effectively driven by animations. A moved piece changes its position after (before?) its sprite is done gliding. A piece is removed from the board after the capturing piece is finished its attack animation.

How would you suggest I manage the game model, the graphics and animations, and their relationships? For example, where would the animations "live"? How would animations be created and managed in response to player moves? How would animations drive updates to the game model, or how would the game model drive animations?

# Answer
> 8 votes
Use a simple **observer pattern**:

1. The player input (mouse clicks/button presses) manipulates the model (abstract representation of chess board with pieces on it).
2. Your graphics component responsible for animating and rendering gets notified when the model's state changes and plays the according animation.

There are two ways to "sync" both modules:

1. Prevent any player input while an animation is running.
2. Maintain a queue in which you insert animations that are then being played one after another, thus giving your players the possibility to "play ahead" (for example choosing a piece that isn't involved in the current animation and moving it after realizing what the enemy just did)

Don't forget that your model contains all the game logic and follow this rule strictly. The graphics system just acts like an UI, while the model decides whether moves are actually allowed or not. This clear separation answers many questions (like: "What if someone commands a piece to do X, when it's currently doing Y?") and avoids logic problems along the course of the game implementation.

**Edit: Example Implementation**
Logic should be separated from the graphical representation.

```
class LogicalPiece {
    Type _type; //enum: "Pawn", "Knight", ...
    int _owner; //player index
}

class GraphicalPiece : LogicalPiece {
    SpriteBatch _sprite;
    Vector2 position;
}

```

The board can then store the logic aspects of all pieces while at the same time providing access to graphical information for the graphics system:

```
LogicalPiece[] _pieces = new GraphicalPiece[64];

```

Example move:

```
//graphics system asks:
if (game.board.isMoveVald(startPos, endPos, player)) {
    Move m = game.board.makeMove(startPos, endPos, player);
    //process m
} else {
    //output error msg
}

```

where the internal structure of *m* could look something like that:

```
m = {
    action: "move",
    piece: board[34], //the actual GraphicalPiece provided by the board
    startPos: {2, 5},
    endPos: {1, 7},
    effects : [
        { effect: "death",
          piece: board[57] //some GraphicalPiece },
        { effect: "promotion",
          callback: someFunc }
    ]
}

```

The graphics system updates itself with a fixed timestep (for example 60 times per second) and in the course of that includes animations of pieces. The game, when asked to do a move, not only updates itself(/the model), but collects all the changes that this move will cause and provides that information to the graphics system which parses and visualizes it. There are many implementation details to figure out, like:

* What kind of notification to use: Events, callbacks or return values?
* Should there be one central draw method or should every piece know how to draw (and animate) itself, so that the graphics system just dispatches animations?
* etc.

My advice is to start coding! Set yourself very easy goals at first and only add new goals after reaching the current one. The details will crystalize out over the course of programming. By trying to plan everything ahead all you'll accomplish is a headache.

Possible roadmap:

1. Be able to draw a game situation with the simplest imaginable implementation: Pieces' graphical representations are updated instantly just like the abstract model (they vanish at one place and pop out at another one)
2. With the system in (1) implement all rules of the game so that players can play it with the correct outcome.
3. Add moving animations: Pieces shall slide smoothly from origins to destinations.
4. Add fighting animations.

...

---
Tags: architecture, animation, models
---


# Question
Title: Game sites that provide good community support for that game
What are examples of games sites that provide good community support for that game? That is, sites for a specific game that provide ways for players of that game for to ask questions, exchange information, publish results.

A site supporting a game could provide ways for both beginners and experts to interact with games producers and players and to explore the set of notions evoked by the game.

# Answer
Is this for a new elevated Web 2.0 developer-player relationships, or a developer's site with really tight integration between the multiplayer/social media/community connectivity and the developer's newsreel?

The sites that come to mind for various reasons:

* Bungie.Net \- The original pioneer in getting down and dirty with its playerbase in the AAA space via the Weekly Update, having a designated community rep (Frankie), and beating everyone to the chase when it comes to displaying Xbox Live stats on a website.
* MuseGames \- For one of their first big Unity games, Guns of Icarus, they built a whole community site backend designed to have even more games plugged into it for connectivity.
* Battle.net \- All the new Facebook integration and combining all your product keys in one and even offering setup files for download was a big step.
* Steam \- Not for a specific game or developer, but still, a great model.
* Wolfire Games \- A good study of the importance of constant, reliable and interesting updates for indie games in development, as well as exerting leadership in the indie community via the Humble Bundle.
> 1 votes

---
Tags: community-management, support
---


# Question
Title: A good way to build a game loop in OpenGL
I'm currently beginning to learn OpenGL at school, and I've started making a simple game the other day (on my own, not for school). I'm using freeglut, and am building it in C, so for my game loop I had really just been using a function I made passed to `glutIdleFunc` to update all the drawing and physics in one pass. This was fine for simple animations that I didn't care too much about the frame rate, but since the game is mostly physics based, I really want to (need to) tie down how fast it's updating.

So my first attempt was to have my function I pass to `glutIdleFunc` (`myIdle()`) to keep track of how much time has passed since the previous call to it, and update the physics (and currently graphics) every so many milliseconds. I used `timeGetTime()` to do this (by using `<windows.h>`). And this got me to thinking, is using the idle function really a good way of going about the game loop?

My question is, what is a better way to implement the game loop in OpenGL? Should I avoid using the idle function?

# Answer
The simple answer is no, you do not want to use the glutIdleFunc callback in a game that has some sort of simulation. The reason for this is that this function divorces animation and draw code from window event handling but not asynchronously. In other words, receiving and handing window events stalls draw code (or whatever you put in this callback), this is perfectly fine for an interactive application (interact, then response), but not for a game where the physics or game state must progress independent of interaction or render time.

You want to completely decouple input handling, game state, and draw code. There is an easy and clean solution to this that does not involve the graphics library directly (i.e. it's portable and easy to visualize); you want the entire game loop to produce time and have the simulation consume the produced time (in chunks). The key however is to then integrate the amount of time your simulation consumed into your animation.

The best explanation and tutorial I have found on this is Glenn Fiedler's Fix Your Timestep

This tutorial has the full treatement, however if you do not have an *actual* physics simulation, you can skip the true integration but the basic loop still boils down to (in verbose pseudo-code):

```
// The amount of time we want to simulate each step, in milliseconds
// (written as implicit frame-rate)
timeDelta = 1000/30
timeAccumulator = 0
while ( game should run )
{
  timeSimulatedThisIteration = 0
  startTime = currentTime()

  while ( timeAccumulator >= timeDelta )
  {
    stepGameState( timeDelta )
    timeAccumulator -= timeDelta
    timeSimulatedThisIteration += timeDelta
  }

  stepAnimation( timeSimulatedThisIteration )

  renderFrame() // OpenGL frame drawing code goes here

  handleUserInput()

  timeAccumulator += currentTime() - startTime
}

```

By doing it this way, stalls in your render code, input handling, or operating system do not cause your game state to fall behind. This method is also portable and graphics library independent.

GLUT is a fine library however it is *strictly* event-driven. You register callbacks and fire off the main loop. You always hand over control of your main loop using GLUT. There are hacks to get around it, you can also fake an external loop using timers and such, but another library is probably a better (easier) way to go. There are many alternatives, here are a few (ones with good documentation and quick tutorials):

* GLFW which gives you the ability to get input events inline (in your own main loop).
* SDL, however its emphasis is not specifically OpenGL.
> 30 votes

# Answer
I think `glutIdleFunc` is just fine; it's essentially what you'd end up doing by hand anyway, if you didn't use it. No matter what you're going to have a tight loop which is not called in a fixed pattern, and you need to make the choice whether you want to convert it to a fixed-time loop or keep it a variable-time loop and make sure all your math accounts for interpolating time. Or even a mix of these, somehow.

You can certainly have a `myIdle` function which you pass to `glutIdleFunc`, and within that, measure the time that has passed, divide it by your fixed timestep, and call another function that many times.

Here is what **not** to do:

```
void myFunc() {
    // (calculate timeDifference here)
    int numOfTimes = timeDifference / 10;
    for(int i=0; i<numOfTimes; i++) {
        fixedTimestep();
    }
}

```

fixedTimestep would not be called every 10 milliseconds. In fact it would run slower than real time, and you might end up fudging numbers to compensate when really the root of the problem lies in the loss of the remainder when you divide `timeDifference` by 10.

Instead, do something like this:

```
long queuedMilliseconds; // static or whatever, this must persist outside of your loop

void myFunc() {
    // (calculate timeDifference here)
    queuedMilliseconds += timeDifference;
    while(queuedMilliseconds >= 10) {
        fixedTimestep();
        queuedMilliseconds -= 10;
    }
}

```

Now this loop structure ensures that your `fixedTimestep` function would get called once per 10 milliseconds, without losing any milliseconds as remainder or anything like that.

Due to the multitasking nature of operating systems you can't rely on a function being called exactly every 10 milliseconds; but the above loop would happen quick enough that it would hopefully be close enough, and you can assume that each call of `fixedTimestep` would increment your simulation 10 milliseconds worth.

Please also read this answer and especially the links provided in the answer.
> 4 votes

---
Tags: opengl, c, game-loop
---


# Question
Title: Best way to go for simple online multi-player games?
I want to create a trivia game for my website. The graphic design does not have to be too fancy, probably no more advanced than a typical flash game. It needs to be secure because I want users to be able to play for real money. It also needs to run fast so users don't spend their time frustrated with game freezing. Compatibility, as with almost all online products, is key because of the large target market.

I am most acquainted with Java programming, but I don't want to do it in Java if there is something much better. I am assuming I will have to utilize a variety of different languages in order for everything to come together.

If someone could point out the main structure of everything so I could get a good start that would be great!

1. Language choice for simple secure online multiplayer games?
2. Perhaps use a database like MySQL, stored on a secure server for the trivia questions?
3. Free educational resources and even simpler projects to practice?

Any ideas or suggestions would be helpful...

# Answer
I think most would agree with me that security is almost completely unrelated to the programming language you develop a project in. Security is mostly achieved by having a well thought security-centric architecture, proven crypto where needed and a good management of secret information (such as crypto keys).

Designing a secure system is not trivial, and there are no recipes for it. As I said before, security is not a programming language, a platform or a set of tools. You can say you make a program in C++, deploy it on OpenBSD, and have RSA all over the place, yet have holes big enough to drive trucks through.

In ultra-broad terms, designing secure client-server applications comes down to:

a. Anything that effects the data (such as scores, etc.) must be calculated on the server. Design your application so even a user with access to your source code cannot act improperly.

b. Use high grade symmetric encryption (such as AES, or Blowfish) for communication between the server and client, with key exchange with a good public key crypto algorithm, such as RSA. Encryption between trusted components is unnecessary.

c. Make sure your network is well designed. For example, the database server should be on a private network, only visible by the game server. Good firewall rules and router settings should complement everything.

d. Make sure all your keys and passwords are secure and well kept. What good is an ultra-secure system, whose admin password is qwertyuiop? Remember, the security of a system is that of its weakest link.

So basically, you should always assume the worst for every line of code you write. If this is your first time designing a secure system, I'd advice you either get some experience with other test systems, or get somebody to help you design it.
> 2 votes

# Answer
Your need for it to run fast and have high compatibility point to writing it in regular HTML and avoiding the likes of Flash and Java (applets) for this. If you haven't written any HTML before, you're in for a long road and yes you will need to utilize a variety of languages (HTML, JavaScript, CSS).

If you have the server hosting, I recently found Socket.IO which I think is really neat - it will facilitate true real-time communication between the browser and your server. Otherwise, if you want to only use your web server, then you'd need to write a system probably based on polling, and the backend would most likely be PHP pages. It wouldn't be true real time but it could be close enough.

It's interesting you mention real money upfront though. That seems to raise the stakes a lot. You will then need to deal with APIs of your virtual money systems (Google Checkout, etc.), make sure your system is airtight from hackers and scams and such, design your game in such a way that seems fair to the players, eliminate cheating in every way possible... It complicates the whole thing, honestly, and I think it's much too early to rush into something with no knowledge with a goal of making money. But if you're determined, I can only stand aside and wish you the best of luck in your adventure.
> 2 votes

---
Tags: multiplayer, online
---


# Question
Title: Effects to make a speeding spaceship look faster
I have a spaceship and I've created a "boost" functionality that speeds up my spaceship, what effects should I implement to create the impression of high speed?

I was thinking of making everything except my spaceship blurry but I think there would be something missing. Any ideas?

Btw. I am working in XNA C# but if you aren't familiar to XNA describing some effects is still useful.

The Game is 3d and i've attached some printscreens of the game

This is in normal mode ( none boosted )

and here is the boosted mode ( the craft speeds up forward while the camera speeds in its normal speed , the non boosted speed )

# Answer
Here are some suggestions:

* If your spaceship has a "propulsion-flame", change its size and color. Eg. if it normally burns with a yellow color, make it blue and double the size of it.
* Apply some jitter to your spaceship. The jitter occurs due to the heavy forces caused by the boost. Maybe you could apply random roll (rotation around the spaceship forward axis).
* Add some particle-effects to the wings of the spaceship.
* Add some wind-like effects to the tip of the rocket/spaceship.

**Update:** If the look of your game allows it, you could also consider adding some speed-lines. Either at the back of your ship or as an overlay (maybe white lines) to your background-scene.

**Follow-up:** When writing my initial answer I was thinking about a side-scrolling game, but most of the effects can still be applied to the "follower-perspective" you chose. As mentioned by others, motion-blur is a good idea. Use a radial motion-blur, as in this example image. Instead of keeping your camera at the "normal" speed and increasing the speed of your spaceship, you could increase the camera FOV which will result in a better speed-impression. Use a trail or radial speed lines to further enhance your effect.
> 36 votes

# Answer
I'll just add one thing which wasn't said here: motion blur
> 25 votes

# Answer
My 2 cents, some of it has already been said but I'd like to make my answer coherent as I believe many of these points together would create a nice effect but just alone they don't do much to create the immersion:

* Random camera shaking, I used Perlin noise to make this nice. There's a C# script available over at the unifywiki.
* Some blurryness spherically around the camera edges, like in the later need for speed games when travelling very fast.
* Make the exhaust flame bigger and more intensive
* Pull the camera back and widen the FOV, also make the colors around the edges of the camera more pale, as if the pilot is focusing really hard on what's ahead.
* have some distortion effects following the ship (if the game supports render to texture shaders)
* Of course, a sound to give feedback (more intensive engine sound, some kind of "moving fast through air sound" if your game allows it style wise.
* Something like what happens with space ships entering the atmosphere would be cool as well, some kind of fire at the bow of the ship.

Hope this helps.
> 14 votes

# Answer
I kind of assume that you're talking about a 3rd person view here of the spaceship because of how you described your idea.

Just in case you have a first person view: Try the "pilot pushed back in his seat due to accelleration" look. ie. pulling the camera a bit away from the cockpit when the boost is triggered.

**It might even be useful in a 3rd person setting too as you often need a bigger FOV when your speeds are higher (Like the camera in the top down GTA games).**
> 5 votes

# Answer
You could render the view distorted as given in *actual reality* by the theory of Special Relativity (you *are* moving fast then, right? Just remember you need to define an upper speed limit in your game then), see e.g. here.

I can't give you a good source reference atm however...
> 5 votes

# Answer
To add on to Phil's suggestion about sound, take multiple approaches to it. You would combine multiple visual effects to achieve the sensation of speed, so do the same with sound.

Have a slight increase in volume to your thrusting sound, or crossfade to one that is more intense and "whooshy". If your collision is split into broad and narrow phase, raise an event when another object gets checked in narrow phase but doesn't actually hit. When this happens, play back a "whipping by"/Doppler effect sort of sound. You can vary it by shifting the pitch variance range upward as the difference between the velocity of the player and the velocity of the object increases.

Also kick your music up a notch, fade in a supplemental rhythm track (layered on top of your main music track). This isn't directly related to perceived speed of the player, but will help increase the emotional intensity, which is what you're after at the end of the day.
> 3 votes

# Answer
Make everything else except your ship, act like it's in slow-motion. Even if everything moves at the same speed, but just animates slower. This will give the feeling that you have an increased rate, like adrenaline or something.
> 3 votes

# Answer
* If it normally leaves an exhaust trail, leave a longer exhaust trail.
* If it doesn't normally leave an exhaust trail, leave an exhaust trail.
* Have the ship shake slightly, for example by rendering it off its actual position by +/- 1 or 2 pixels randomly.
> 1 votes

# Answer
Some suggestions

* background sliding quickly in the opposite direction
* objects/asteroids around the ship quickly moving in the opposite direction
* after-images
> 0 votes

# Answer
Take a look at how Infinity Universe does it.

They have a big problem in that everything is to scale. That make any sense of speed to be almost non-existent right up to the moment when you arrive at the star/planet/moon/.

They have the best implementation of environmental speed lines I've seen.

They denote speed by making the ship look like its flying through a thin dust cloud. As the particles stream by the leave slight speed lines. When the ship is at rest the cloud is completely transparent.

Here is a video link demonstrating ship movement.
> 0 votes

---
Tags: xna, graphic-effects
---


# Question
Title: Interacting with scene from controller/app delegate cocos2d
I'm attempting to make my first cocos2d (for iphone) multiplayer game and having difficulty understanding how to interact with a scene once it is running.

The game is a simple turn-based one and so I have a GameController class which co-ordinates the rounds. I also have a GameScene class which is the actual scene that is displayed during a round of the game. The basic interaction I need is for the GameController to be able to pass messages to the GameScene class.. such as StartRound/StopRound etc.

The thing that complicates this is that I am loading the GameScene with a LoadingScene class which simply initialises the scene and replaces the current scene with this one, so there is no reference from GameController to GameScene, so passing messages is quite tricky.

Does anyone have any ways to get around this, ideally I would still like to use a Loading class as it smooths out the memory hit when replacing scenes.

# Answer
Solution on my first try was... Have a getInstance() static method in GameScene class

```
     +(GameScene*) getInstance()
     {
        return s_currentInstace;//This is the static variable that holds the current GameScene
     }

```

you should update 's\_currentInstace' variable as and when you create and destroy GameScene accordingly.(i mean set s\_currentInstace to 'nil' when GameScene is getting destroyed)

When you want to send a message to GameScene, you just need to call getInstance() on GameScene and based on the return value you act ;).

Will update this when i have some more solutions.
> 0 votes

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


title: Indie devs working with publishers

text:
# Question
Title: Indie devs working with publishers
I'm an independent game developer considering working with a publisher. This question is very informative however I have more questions. Please give feedback on the following issues... I think this can be helpful to many indie devs in the same situation.

* **Source code**: is it common for developers to give the publisher the source code?
* **Code quality**: does this matter when working with a publisher any more so than when just working on your own (or in a small team)? Just wondering if developers working for the publisher might scoff at the code quality and perhaps influence the relationship between developer and publisher.
* **Unique game concepts**: are publishers generally biased towards new/novel game concepts?
* **Intellectual property**: if I send a playable demo to a publisher what's to stop them from just reproducing the new/novel game mechanic? I think the answer is basically nothing... but I'm wondering if this is a realistic concern.
* **Revenue sharing**: how does it work? what's a common ratio? 70/30? 30/70?
* **Flaky publishers**: how common is it for a publisher to "string along" developers for a while then just drop them? Can this be reconciled with a contract of some kind?

And any **other issues** you've encountered or heard of.

# Answer
> 4 votes
Source code: Usually you don't give away the source code unless you have e.g. a porting contract with the publisher.

Code quality: Most publishers do QA. And if you're aiming for a console you have to go through first-party QA, too. But in the end your code should also be good if you self-publish your games.

Unique game concepts: Publishers are rather biased towards established concepts because they try to reduce their risk. Just look at the viable self-published indie scene on Steam, iPhone and XBLIG and compare it to a shelf of AAA productions. Notice the difference?

Revenue sharing: That depends on the deal. If you want a development deal with upfront payments and an IP by the publisher you might have to settle at 30/70 (30% for you, 70% for the publisher) after the first party took its share (e.g. 30% with Apple). If you do a "normal" development deal you most likely end up somewhere between 50/50 and 70/30. If you strike a marketing deal the publisher's share might go down to 15%.

Flaky publishers: It is not uncommon and there've been a lot of cases. It's best if you try to find out as much as possible about your publisher before you sign a deal. That's no reason to shy away from working with publishers, but you best be careful.

Other issues: Be sure to have a lawyer read your contract!

---
Tags: publishing
---


# Question
Title: Pack of resources in one big file with XNA
Is it possible to pack all the little .xnb files into one big file? Given the level of abstraction of the XNA Framework I though this would come out of the box but I can't find any well integrated solution.

So far the best candidate is XnaZip but in addition to having to compile the resources in a post-build event, and a little trouble porting the game to XBOX I have to rename all the references to resources I have already implemented.

# Answer
It's possible, but you either have to:

* Find a library that does it for you, or
* implement it yourself.

XNA lets you do the latter by deriving from the `ContentManager` class and replacing the `OpenStream` method; in fact, the documentation explicitly says:

> ```
> protected virtual Stream OpenStream (string assetName)
>
> ```
>
> Opens a stream for reading the specified asset. Derived classes can replace this to implement pack files or asset compression.

In the override version of `OpenStream`, one would simply return a compatible `Stream` that read the requested asset data from a pack file, rather than opening a `FileStream` from disk.

The tricky part is that you have to actually build the pack file yourself, incorporating the `xnb` files output via the content build pipeline. You could build a Content Pipeline Extension to do this, or find some other method, depending on what your goals are.
> 4 votes

---
Tags: xna
---


title: OpenGL ES 2.0: Using VBOs?

text:
# Question
Title: OpenGL ES 2.0: Using VBOs?
OpenGL VBOs (vertex buffer objects) have been developed to improve performance of OpenGL (*OpenGL ES 2.0* in my case). The logic is that with the help of VBOs, the data does not need to be copied from client memory to graphics card on per frame basis.

However, as I see it, the game scene changes continuously: position of objects change, their scaling and rotating change, they get animated, they explode, they get spawn or disappear.

**In such highly dynamic environment, such as computer game scene is, what is the point of using VBOs**, if the VBOs would need to be constructed on per-frame basis anyway?

Can you please help me to understand how to practically take beneif of VBOs in computer games? Can there be more vertex based VBOs (say one per one object) or there must be always exactly only one VBO present for each draw cycle?

# Answer
> 13 votes
> In such highly dynamic environment, such as computer game scene is, what is the point of using VBOs, if the VBOs would need to be constructed on per-frame basis anyway?

If you are reconstructing the vertex data for every object every frame, you're doing it wrong. Or at least, you're probably doing it inefficiently.

Moving objects in a scene can and should usually be done by changing the world transformation matrix used to render that object, *not* changing the vertex data directly. Skeletal animation has entirely on-GPU solutions, as well. Decomposable objects can be rendered with distinct transformation matrices, such that they appear together until they need to be decomposed, and then the matrices are adjusted to make them split apart as desired. Objects that are not visible or not spawned need not be rendered, even if their vertex data is on the card from a prior frame -- they don't need their buffers destroyed/recreated every time their visibility toggles.

> Can you please help me to understand how to practically take beneif of VBOs in computer games? Can there be more vertex based VBOs (say one per one object) or there must be always exactly only one VBO present for each draw cycle?

You can have multiple vertex buffers. In generally you have one per each mesh/model, and you refer to that single mesh/model data structure with a collection of possibly-many renderable objects which contain their own unique world transformation matrix. This way if you have 50 enemies who all use the same mesh, you only need that mesh in-memory once. Then you have 50 smaller, lightweight instance structures that refer to that mesh and hold a unique world transform used when rendering each instance.

# Answer
> 3 votes
You can have as many VBOs as you want. You can also have each animation frame in one VBO or whole animation in one VBO. You can also use Per vertex animation, which is done with the same data, but transformed in vertex shader (program).

If you change position, rotation or scale of object, it won't change VBO, it will only change transformation matrix.

So if you have enough memory, you can just transfer all your data to graphics memory in initialization phase.

---
Tags: game-design, opengl, opengl-es, graphics-programming
---


# Question
Title: OpenGL-ES: clearing the alpha of the FrameBufferObject
This question is a follow-up to Texture artifacts on iPad

How does one "clear the alpha of the render texture frameBufferObject"? I've searched around here, StackOverflow and various search engines but no luck. I've tried a few things... for example calling GlClear(GL\_COLOR\_BUFFER\_BIT) at the beginning of my render loop... but it doesn't seem to make a difference. Any help is appreciated since I'm still new to OpenGL.

Cheers!

p.s. I read on SO and in Apple's documentation that GlClear should always be called at the beginning of the renderLoop. Agree? Disagree? Here's where I read this: https://stackoverflow.com/questions/2538662/how-does-glclear-improve-performance

# Answer
> 6 votes
Try

```
glColorMask(FALSE, FALSE, FALSE, TRUE);//This ensures that only alpha will be effected
glClearColor(0, 0, 0, alphaValue);//alphaValue - Value to which you need to clear
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

```

to clear both the color buffer (with transparent black) and the depth buffer, in case you are using depth testing.

glClear must be called unless you are really sure you are redrawing all the pixels every frame, so parts of previous frames don't show over your new render.

# Answer
> 1 votes
Once have a look at the below link (please check the afterRender method)

http://code.google.com/p/cocos2d-iphone/issues/detail?id=631&q=glClear%28GL\_COLOR\_BUFFER\_BIT&colspec=ID%20Type%20Status%20Priority%20Milestone%20Component%20Owner%20Summary

Here the fix was to clear the RenderTextures's Alpha channel with 1.0 so that it will not have artifact when you draw other nodes on RenderTexture.That clearing should be done once you are done drawing on the renderTexture. Please let me know if you need further clarification.

Btw, for glClear call.... If you are drawing a full screen background, there is no need of calling glClear.The game i worked on recently had a bit of performance gain when i removed glClear call.The link you posted seems interesting.Thanks for the link.

---
Tags: graphics, textures, opengl-es, ipad
---


# Question
Title: What's the recommended bitrate for Background Music in iPhone Games?
What is the recommended bitrate for Background Music in iPhone Games?

# Answer
In all honesty, it's probably down to what sounds best at the lowest bitrate.

So if you had music at 192kbps but you could still get it sounding decent without a whole lot of quality loss at, say, 64kbps, then you've got no reason not to use the 64kbps version.

It might be worth having a bunch of different bitrates of the same song and see which "sounds" the best, whilst reducing the bitrate. If you've got some 8-bit retro sounds in the music you could get away with fairly low bitrates, but probably less so with a piece of music with a wide variety of sounds and textures (e.g. a classical composition, with full percussion, and synths and basses on top).

Just as an extra, if you're not certain about what sounds correct at a low bitrate, I'd suggest talking to an audio producer or if that's not possible then just ask the guys at Audio-Video Production SE those guys definitely know their audio :)
> 5 votes

# Answer
Like Ray Dey said, you need to make the call on quality vs size. Remember the project triangle?

The same applies to audio. You can have good quality audio that doesn't take up a lot of space, but you'll have to manage streaming it and you're often limited to a set number of streaming channels on non-PC hardware. You can have good quality without streaming, but it will take up a lot of memory, etc.

Something to check out, if you are working with composers who would be comfortable writing the music in trackers, you can use FMOD (iPod/Pad/Phone and PSP license is listed under "Casual" on their Sales Page and is $500 flat) and load .MOD, .XM, and .IT. You can have high quality samples and fine-grain control over the flow of music.
> 0 votes

---
Tags: iphone, cocos2d-iphone, music, ios
---


title: Mandelbrot set not displaying properly

text:
# Question
Title: Mandelbrot set not displaying properly
I am trying to render mandelbrot set using glsl. I'm not sure why its not rendering the correct shape. Does the mandelbrot calculation require values to be within a range for the (x,y) \[ or (real, imag) \] ? Here is a screenshot:

---

I render a quad as follows:

```
float w2 = 6;
float h2 = 5;
glBegin(GL_QUADS);

glVertex3f(-w2, h2, 0.0);
glVertex3f(-w2, -h2, 0.0);

glVertex3f(w2, -h2, 0.0);
glVertex3f(w2, h2, 0.0);

glEnd();

```

My vertex shader:

```
varying vec3 Position;

void main(void)
{
    Position = gl_Vertex.xyz;

    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}

```

My fragment shader (where all the meat is):

```
uniform float MAXITERATIONS;

varying vec3 Position;

void main (void)
{
   float zoom = 1.0;
   float centerX = 0.0;
   float centerY = 0.0;

   float real = Position.x * zoom + centerX;
   float imag = Position.y * zoom + centerY;

   float r2 = 0.0;
   float iter;

   for(iter = 0.0; iter < MAXITERATIONS && r2 < 4.0; ++iter)
   {
    float tempreal = real;

    real = (tempreal * tempreal) + (imag * imag);
    imag = 2.0 * real * imag;

    r2 = (real * real) + (imag * imag);
   }

   vec3 color;

   if(r2 < 4.0)
    color = vec3(1.0);
   else
    color = vec3( iter / MAXITERATIONS );

gl_FragColor = vec4(color, 1.0);
}

```

# Answer
> 1 votes
It was my fragment shader. Here is the correct version:

```
uniform float MAXITERATIONS;

varying vec3 Position;

void main (void)
{
   float zoom = 1.0;
   float centerX = 0.0;
   float centerY = 0.0;

   float real = Position.x * zoom + centerX;
   float imag = Position.y * zoom + centerY;
   float Creal = real;
   float Cimag = imag;

   float r2 = 0.0;
   float iter;

   for(iter = 0.0; iter < MAXITERATIONS && r2 < 4.0; ++iter)
   {
    float tempreal = real;

    real = (tempreal * tempreal) - (imag * imag) + Creal;
    imag = (2.0 * tempreal * imag) + Cimag;

    r2 = (real * real) + (imag * imag);
   }

   vec3 color;

   if(r2 < 4.0)
    color = vec3(1.0);
    else
    color = vec3( iter / MAXITERATIONS );

    gl_FragColor = vec4(color, 1.0);
}

```

---
Tags: opengl, mathematics, rendering, shaders, glsl
---


# Question
Title: Separate shaders from HTML file in WebGL
I'm ramping up on WebGL and was wondering what is the best way to specify my vertex and fragment shaders.

Looking at some tutorials, the shaders are embedded directly in the HTML. (And referenced via an ID.) For example:

```
<script id="shader_1-fs" type="x-shader/x-fragment">
  precision highp float;
  void main(void) {
    // ...
  }
</script>

<script id="shader_1-vs" type="x-shader/x-vertex">
  attribute vec3 aVertexPosition;

  uniform mat4 uMVMatrix;
  // ...

```

My question is, is it possible to have my shaders referenced in a separate file? (Ideally as plain text.) I presume this is straight forward in JavaScript. Is there essentially a way to do this:

```
var shaderText = LoadRemoteFileOnSever('/shaders/shader_1.txt');

```

# Answer
> 4 votes
Yes, it's simple. You can just make an AJAX request to the file, and pass the code to WebGL's shaderSource function.

---
Tags: javascript, webgl
---


# Question
Title: How do they keep track of the NPCs in Left 4 Dead?
How do they keep track of the NPC zombies in Left 4 Dead?

I am talking about the NPCs that just walk into walls or wander around aimlessly. Even though the players cannot see them, they are there (say inside rooms or behind doors). Let's say there's about 10 or so zombies in a hallway and inside rooms. Does the game keep all of those zombies in a list and iterate through giving them commands? Do they just spawn when the user is within a certain radius or reached a special location?

Say you placed the 4 units (controlled by players) on completely different places throughout the map. Let's assume you aren't being swarmed and then you have not killed any of these aimless NPCs. Would the game be keeping track of 10 x 4 = 40 zombies in total?

Or is my understanding completely off?

The reason I ask is if I were to implement something similar on a mobile device, keeping track of 40 or more NPCs might not be such a great idea.

# Answer
> 24 votes
You are interested in the paper found here:

AI Systems of Left 4 Dead

# Answer
> 4 votes
I haven't read the paper that ChrisE wrote a link to, but from either a conversation I had with a Valve employee or somewhere on their Development Wiki (can't remember which) I remember being informed that they essentially have only a couple of *real* entities (the AI director); the avatars you see portraying the infected NPC's are just "finger-puppets" to those entities. They did this to keep the number of edict (entity dictionary) entries to a minimum since there are obviously a ton of infected NPC's to keep track of.

The engine's entity dictionary has a fixed size and cannot grow. This means that any game built on this engine which requires a large amount of NPC's--or any entity for that matter--has to make use of such system in order for the engine to function properly and not choke (and ultimately crash) because the entity count is too high.

# Answer
> 1 votes
I can't speak to how the Left 4 Dead implementation works, but I can say how I'd probably do it.

I'd go for something like your second option, track each player and only load NPCs when players move past trigger points. The key in a system like this, is to make the trigger points far enough away from the player that they are unable to associate that `walking past this fence post` triggers `that car to blow up, and shoot a zombie at them.`

I would probably have an active NPC collection, which the trigger points either add or remove NPCs from the collection. This allows you to spend CPU/GPU resources on NPCs that players are actually interacting with, but it gives you the flexibility to load NPCs at any time.

Think about a boss who can hear sounds, maybe the boss is loaded at the start of the map and if the player going through the map makes lots of noise (grenades, pipe bombs, etc), the boss will seek out the player and attack out of the blue, instead of waiting till the player reaches the boss arena.

---
Tags: game-design, ai
---


title: Multiple volumetric lights

text:
# Question
Title: Multiple volumetric lights
I recently read this GPU GEMS 3 article Volumetric Light Scattering as a Post-Process. I like the idea to add volumetric light property to realtime render i'm working on. Question is will it work for multiple lights? Our renderer uses one render pass per light and uses additive blending to sum incoming light.

I'm mostly convinced that it have to work nice. Do you agree? Maybe there can be problem where light rays crosses each other.

# Answer
The question is a bit ambiguous. Will it work? Sure it will. You can probably squeeze it down to one pass that traces against all lights, even though you use one pass per light. Can you add your lights to a list and do a post process batch where your lights are in a list?

Will it look good? That's the problem. It's not really easy to answer and depend a lot on your art direction and how intense you want the effect from each light to be.
> 1 votes

---
Tags: lighting, post-processing, volumetric-light
---


title: Tetris Movement - Implementation

text:
# Question
Title: Tetris Movement - Implementation
I'm developing a Tetris clone and working on the input at the moment.

When I was prototyping, movement was triggered by releasing a directional key. However, in most Tetris games I've played the movement is a bit more complex.

> When a directional key is pressed, the shape moves one space in that direction. After a short interval, if the key is still held down, the shape starts moving in the direction continuously until the key is released.
>
> In the case of the down key being pressed, there is no pause between the initial movement and the subsequent continuous movement.

I've come up with a solution, and it works well, but it's totally over-engineered. Hey, at least I can recognize when things are getting silly, right? :)

```

    public class TetrisMover
    {
        List registeredKeys;
        Dictionary continuousPressedTime;
        Dictionary totalPressedTime;
        Dictionary initialIntervals;
        Dictionary continousIntervals;
        Dictionary keyActions;
        Dictionary initialActionDone;
        KeyboardState currentKeyboardState;

        public TetrisMover()
        {
            *snip*
        }

        public void Update(GameTime gameTime)
        {
            currentKeyboardState = Keyboard.GetState();

            foreach (Keys currentKey in registeredKeys)
            {
                if (currentKeyboardState.IsKeyUp(currentKey))
                {
                    continuousPressedTime[currentKey] = TimeSpan.Zero;
                    totalPressedTime[currentKey] = TimeSpan.Zero;
                    initialActionDone[currentKey] = false;
                }
                else
                {
                    if (initialActionDone[currentKey] == false)
                    {
                        keyActions[currentKey]();
                        initialActionDone[currentKey] = true;
                    }

                    totalPressedTime[currentKey] += gameTime.ElapsedGameTime;

                    if (totalPressedTime[currentKey] >= initialIntervals[currentKey])
                    {
                        continuousPressedTime[currentKey] += gameTime.ElapsedGameTime;
                        if (continuousPressedTime[currentKey] >= continousIntervals[currentKey])
                        {
                            keyActions[currentKey]();
                            continuousPressedTime[currentKey] = TimeSpan.Zero;
                        }
                    }
                }
            }
        }

        public void RegisterKey(Keys key, TimeSpan initialInterval, TimeSpan continuousInterval, Action keyAction)
        {
            if (registeredKeys.Contains(key))
                throw new InvalidOperationException(
                    string.Format("The key %s is already registered.", key));

            registeredKeys.Add(key);
            continuousPressedTime.Add(key, TimeSpan.Zero);
            totalPressedTime.Add(key, TimeSpan.Zero);
            initialIntervals.Add(key, initialInterval);
            continousIntervals.Add(key, continuousInterval);
            keyActions.Add(key, keyAction);
            initialActionDone.Add(key, false);
        }

        public void UnregisterKey(Keys key)
        {
            *snip*
        }
    }

```

I'm updating it every frame, and this is how I'm registering keys for movement:

```

            tetrisMover.RegisterKey(
                Keys.Left, keyHoldStartSpecialInterval, keyHoldMovementInterval,
                () => { Move(Direction.Left); });

            tetrisMover.RegisterKey(
                Keys.Right, keyHoldStartSpecialInterval, keyHoldMovementInterval,
                () => { Move(Direction.Right); });

            tetrisMover.RegisterKey(
                Keys.Down, TimeSpan.Zero, keyHoldMovementInterval,
                () => { PerformGravity(); });

```

Issues that this doesn't address:

* If both left and right are held down, the shape moves back and forth really quick.
* If a directional key is held down and the turn finishes and the shape is replaced by a new one, the new one will move quickly in that direction instead of the little pause it is supposed to have.

I could fix the issues, but I think it will make the solution even worse. How would you implement this?

# Answer
What you need is a simple key repeating algorithm. This is how I usually do it.

```
FRAMES_FOR_FIRST_PRESS = 4;
FRAMES_FOR_OTHER_PRESS = 1;

key_pending_frames = -1;

```

now, for every frame:

```
function OnFrame()
{
    if (IsKeyPressed())
    {
        if (key_pending_frames < 0) // not pressed
        {
            key_pending_frames = FRAMES_FOR_FIRST_PRESS;
        }
        key_pending_frames--;
        if (key_pending_frames == 0)
        {
            DoYourAction();
            key_pending_frames = FRAMES_FOR_OTHER_PRESS;
        }
    }
    else
    {
        key_pending_frames = -1;
    }
}

```

You'd need a key\_pending\_frames for each key you want, and you can reset any key's counter just by setting its variable to -1.

Note that for non-fixed frame lengths, you can use clock ticks, or another time interval structure you have. You just have to make sure your non-pressed value is unreachable by simply decrementing the counter. To be on the safe side, you can simply add a `bool key_pressed` for each key.
> 2 votes

---
Tags: xna, game-mechanics, input, game-loop
---


title: Need help drawings planets in Java

text:
# Question
Title: Need help drawings planets in Java
I am looking for help/links/notes/agorithms/URLs/examples on drawing/rendering spheres in pure Java (so that I can hopefully, one day, generate/render planets with various surfaces & atmospheres)

So for the moment, i'd be pretty happy to be able to start off with just drawing a wireframed sphere(s).

ps: I don't want to use external libraries like Java3D, JOGL or aftermarket engines like JMonkeyEngine, Would rather keep it as straight Java.

# Answer
This is not possible in java as i know.

If you still want to do this in plain java, you will have to implement some kind of simple 3D library by yourself. That is very useful for learning graphics programming, but not easy way how to get things working (and it will be slow, because you will not be able to use gpu). If there is not some special reason to not using libraries i think that you will be good with JOGL.
> 3 votes

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


# Question
Title: How to calculate vertex normals for a mesh in Java in OpenGL ES?
Can some one point me to Java code ( in Java not C or C++) that calculates all the normals for all the vertices of a mesh for OpenGL ES application. I need this for lighting. Lets say I have a cube with following vertices and indices:

```
float vertices[] = { -width, -height, -depth, // 0
                      width, -height, -depth, // 1
                      width,  height, -depth, // 2
                     -width,  height, -depth, // 3
                     -width, -height,  depth, // 4
                      width, -height,  depth, // 5
                      width,  height,  depth, // 6
                     -width,  height,  depth  // 7
        };
short indices[] = { 0, 2, 1,
                    0, 3, 2,
                    1,2,6,
                    6,5,1,
                    4,5,6,
                    6,7,4,
                    2,3,6,
                    6,3,7,
                    0,7,3,
                    0,4,7,
                    0,1,5,
                    0,5,4
                  };

```

In above specific example how many normals we need?

# Answer
> 1 votes
You can calculate normals by taking two edges, and cross product for each vertex. A cube actually has 24 vertices not 8, the reason is that each corner vertex is shared with different faces, because openGL takes per vertex attributes, you need to duplicate a vertex if you find that it has 2 different normals, assuming you want hard edges.

http://www.devmaster.net/forums/showthread.php?t=1783

this is a C++ code but its self explanatory.

---
Tags: opengl-es
---


# Question
Title: How do I employ an arcball to allow the user to look around the screen?
How do I apply an arcball (using quaternions) along with mouse events, to allow the user to look around the screen using the o3d WebGL framework?

This sample uses the arcball for rotating the transform of an "object," but rather than apply this to a transform, I would like to apply the rotation to the camera's target, to create a first person style ability to look around the scene, as if the camera is inside the centre of the arcball instead of rotating from the outside.

The code that is used in this sample is

```
var rotationQuat = g_aball.drag([e.x, e.y]);
var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);

```

The code that I am using which doesn't work

```
var rotationQuat = g_aball.drag([e.x, e.y]);
var rot_mat = g_quaternions.quaternionToRotation(rotationQuat);
g_thisRot = g_math.matrix4.mul(g_lastRot, rot_mat);

var cameraRotationMatrix4 = g_math.matrix4.lookAt(
  g_eye, g_target, [g_up[0], g_up[1] * -1, g_up[2]]
);
var cameraRotation = g_math.matrix4.setUpper3x3(
  cameraRotationMatrix4, g_thisRot
);
g_target = g_math.addVector(cameraRotation, g_target);

```

where am I going wrong?

# Answer
Without knowing exactly how it "doesn't work," it's a bit hard to say. I will say that the canonical arcball approach involves projection the 2D screen position onto the surface of an imaginary sphere that surrounds the object, and might be overcomplex for the kind of rotation you want for your camera.

It sounds like you would be able to get away with building a shortest-arc quaternion between the previous mouse position and the new one (in screen space, during a drag) and using that quaternion to modify your view matrix.
> 1 votes

# Answer
I agree with Josh Petrie's answer, use ray cast to find intersection with an imaginary sphere now find the vector from intersection point to the center of the sphere for the first mouse position, now repeat the step for the next mouse position, you will have two vectors, make a cross product to the find the axis that you should rotate your camera around.
> 1 votes

---
Tags: 3d, javascript, html5, webgl
---


title: How to find the window size in XNA

text:
# Question
Title: How to find the window size in XNA
I just wanted to know if there was a way to find out the size of the window in XNA. I don't want to set it to a specific size; I would like to know what dimensions it currently displays as automatically. Is there a way to find this information out?

I realize I probably should have found this information out (or set it myself manually) before working on the game, but I'm a novice and am now hoping to work within the dimensions I have already become invested in. Thanks!

# Answer
Here are your options:

To get the back-buffer size use:

`GraphicsDevice.PresentationParameters.Bounds` (for a rectangle) or `BackBufferWidth` and `BackBufferHeight`.

You want the back-buffer size if you're doing stuff like setting viewports, taking screenshots, etc.

**To get the *Viewport*, use:**

`GraphicsDevice.Viewport.Bounds` (for a rectangle) or `Width` and `Height`.

**The size of the viewport is what you want to use when you're actually rendering stuff**. Any coordinates you pass to `SpriteBatch` are in pixel-aligned client space in terms of the viewport: (0,0) for the top left pixel to (width-1,height-1) for the bottom right. If you're doing 3D stuff, *projection space* goes from (-1,-1) in the bottom left of the viewport to (1,1) in the top right.

You can adjust the size and position of the viewport on screen (for doing effects like split-screen). So, while it is initialised to the size of the back-buffer, it is not necessarily always the same.

If you're doing interface layout stuff, particularly if you will run on the Xbox 360, be aware of `Viewport.TitleSafeArea`. This tells you what region is definitely visible on screens that may cut off some of the border.

If, for some reason, you're actually working with the game window itself, use `Game.GameWindow.ClientBounds`.
> 17 votes

# Answer
GraphicsDevice.Viewport.Bounds - this returns Rectangle2D and it has parameters Width and Height.
> 2 votes

---
Tags: xna
---


title: Building an instance system

text:
# Question
Title: Building an instance system
I am looking into how to design an instance system for the game I am working on. I have always wondered how these are created in games like World of Warcraft, with its instances (dungeons/raids/etc). Areas that are separated from players other than those in your group, but have specific logic to them.

Specifically how can you reuse your existing code base and not have a bunch of checks like the following

`if (isInstance) do x; else do y;`

I don't know if this will make too much of a difference on any answers, but we're using a pretty classic "Object as pure aggregation" component system for our entities.

# Answer
> 3 votes
As you probably guessed, having a bunch of `if` statements in your code is just about the worst thing you could do. What you actually need, is to abstract different functionality in different "units" - be they classes, functions, scripts or whatever - and make them as self-contained as possible.

Here's how we do that. In our current game, characters can be either in an instance, or in town. We have so-called *services*, that run in their own threads and process players' requests and game logic. We have one town service and many instance services - one for each instance active on the server.

Thus, town service has logic to deal with town tasks, such as visiting a shop; instance service has logic to deal with instance tasks, such as casting spells. These are not the only services - for example, quests and achievements can happen both in town and in instance, and they're handled in a special quest service, that towns and instances communicate with.

But instance service doesn't contain all game logic pertaining to instances (for one thing, it would be enormous if it did). For example, there's `MoveController` that handles, you guessed it, movement in instance. This allows us to (theoretically) add some new logic to movement - like, for example, add flying - by just creating another `MoveController`-derived class. Not that we actually tried (-8

An example that is closer to your question: at start of development, we only had PvE instances, that closed whenever all mobs *or* all characters died. However, at some time we had to add PvP, which had a bunch of different rules about who won and who lost and when. That is, the game logic in PvP was the same as in PvE, *except* the finishing part. This is what we did: we created an object called `ExitStrategy`, whose responsibility was to decide whether instance was to end, and what characters received rewards afterwards. Than we made several different strategies: `PvEExitStrategy`, `DuelExitStrategy`, `TeamBattleExitStrategy`, etc. The instance service has an object of type `ExitStrategy`, that is created during set-up, based on what type of instance it is. Thus, there's only one place with a bunch of `if`'s (`switch` actually), neatly tucked in a short method in the startup sequence.

I want to emphasize that we *didn't* subclass `InstanceService` instead. While this might seem like a logical thing to do, subclassing is actually bad decision in this case. Suppose we'd later want to add another type of instance - say, with some "mission objectives" to reach. If we used subclassing, we wouldn't be able to add this to both PvE and PvP instances without some code duplication. However, with aggregation we can easily add some `ObjectiveManager` or something.

To reiterate: you want to have different logic in different places, as independent as possible?, and combine it with aggregation. If you do, you can use whatever "common" game logic you need in the instance, and add or override parts you don't need.

Now, if you're anything like me, this approach would actually leave you with a lot of components that are just not independent enough, and tend to break if you push them too far, especially on first try. But that's still way better than huge inheritance hierarchy, code duplication or, heaven forbid, bunches of `if`'s everywhere.

# Answer
> 0 votes
You wouldn't need a bunch of checks everywhere if you had lots of rooms, right? You just load the room, and do thing that belong to that room, while you're in the room. Leave the room, and these checks are never made again.

Instance logic is decoupled from game logic. Usually they're just the same, but the regular game just "plays" and the instances are scripted (or whatever.) Specially in WoW, where LUA dominates.

# Answer
> 0 votes
Design elements are generally data-driven, not done in code (at least not in the same code as the engine, some places use Lua or Python code for the gameplay bits).

---
Tags: mmo, game-mechanics
---


title: Creating Cut Scenes For iPad

text:
# Question
Title: Creating Cut Scenes For iPad
I am working on an iPad game, and would like to have a few, pre-rendered cut scenes that are shown at key moments throughout the game.

How do low-budget software developers create pre-rendered cut scenes, especially when the target device is an iPad?

# Answer
> 2 votes
A common method is to record a movie, encode it to a file such as Mpeg-4, and use the iPhone's selection of video controls to play that movie back.

The movie itself can be produced in a variety of ways:

e.g.

* Live action;
* Computer generated images using a CGI package such as Autodesk's 3ds Max or Maya;
* Play out your scene using your own game and record it using something like FRAPS.

# Answer
> 1 votes
I would suggest paintings with subtle animations in a comic like presentation. If you are lucky you might find a talented young artist that will spend his/her free time to get their art exposed in a game.

A good example of awesome "2D" cutscenes are the mini-cutscenes before missions in Warhammer40k: Chaos Rising. It's basically paintings overlain on an animated 2D mesh. Very clerver, good looking and affordable! I can't find a video example online though. Most of the ones online are full 3D.

---
Tags: ipad, cutscene
---


title: GLSL: How do I cast a float to an int?

text:
# Question
Title: GLSL: How do I cast a float to an int?
In a GLSL fragment shader I am trying to cast a `float` into an `int`. The compiler raises an error:

```
ERROR: 0:60: '=' :  cannot convert from 'mediump float' to 'highp int'

```

I tried raising the precision of the `int`:

```
mediump float indexf = floor(2.0 * mixer);
highp int index = indexf;

```

but to no avail.

How do I cast the `int` properly?

# Answer
Try this:

```
highp int index = int(indexf);

```

I found it here.
> 53 votes

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


# Question
Title: OpenGL ES 2.0: Picking Individual Polygon Sprites from within VBO
Say, I send 10 polygon pairs *(one polygon pair == one 2d sprite == one rectangle == two triangles)* into **OpenGL ES 2.0 VBO**. The 10 polygon pairs represent **one animated 2D object** consisting of 10 frames.

The 10 frames, of course, can not be rendered all at the same time, but will be rendered in particular order to make up smooth animation.

Would you have an advice, **how to pick up proper polygon pair for rendering** (4 vertices) inside Vertex Shader from the VBO? Creating separate VBO for each frame would end up with thousands of VBOs, which is not the right way of doing it.

I use OpenGL ES 2.0, and VBOs for both Vertices and Indices.

# Answer
> 4 votes
If you use glDrawElements, you should be able to define offset. If you have bound indeces with glBindBuffer(GL\_ELEMENT\_ARRAY\_BUFFER, indices), last parameter in glDrawElements is just offset. So you can start from anywhere and stop after few indeces (second parameter - count).

# Answer
> 3 votes
One approach is to use a shader to interpolate frames, so you get smooth animation and possibly less data.

Look at this question and its answers: interpolating frames in a vertex shader

---
Tags: opengl, opengl-es, graphics-programming
---