# Question
Title: How to determine what triangle in a mesh the cursor is pointing to?
I have a game I'm working on in which items are "placed" and "selected".

In order to do this, I need to determine what triangle in a mesh the cursor is pointing to. I have no trouble with getting the cursor position or the orientation/position of the camera - the problem is figuring out how they relate.

I'm guessing that this involves ray-picking, but I have no idea on how to convert a cursor position to a ray that I can test for intersection with a triangle.

**A little bit of background:**
Game engine: *Irrlicht*
Language: *C++*

# Answer
> 3 votes
I found a solution, though not an in-depth explanation - seems like Irrlicht has a built in function for this:

irr::scene::ISceneCollisionManager::getRayFromScreenCoordinates

This will calculate a ray given a screen coordinate.

# Answer
> 1 votes
To convert a cursor position to a ray, you can back-project the 2D co-ordinates onto two planes parallel to the view plane. Typically you might use the near and far planes. Two points define a ray.

This is simply a matter of doing the maths used to project a 3D point onto the screen, in reverse.

Typically from world space you would multiply by a view and projection matrix to get into clip-space, divide by Z to do the actual projection, and then scale the resulting values into pixel-values.

So in reverse you would scale the screen-coordinates into clip space, multiply by Z (taken from the plane you're interested in), and transform by the inverse of the view-projection matrix to get back into world space.

However as you've noticed, most engines and libraries can do this for you...

# Answer
> 0 votes
Irrlicht Tutorials This link explains the triangle selection and ray casting, just need to convert screen to the world coords.

```
scene::ITriangleSelector* selector = 0;
scene::IAnimatedMeshSceneNode* node = 0;

    // Add an MD2 node, which uses vertex-based animation.
    node = smgr->addAnimatedMeshSceneNode(smgr->getMesh("../../media/faerie.md2"),
                                            0, IDFlag_IsPickable | IDFlag_IsHighlightable);
    node->setPosition(core::vector3df(-70,-15,-120)); // Put its feet on the floor.
    node->setScale(core::vector3df(2, 2, 2)); // Make it appear realistically scaled
    node->setMD2Animation(scene::EMAT_POINT);
    node->setAnimationSpeed(20.f);
    video::SMaterial material;
    material.setTexture(0, driver->getTexture("../../media/faerie2.bmp"));
    material.Lighting = true;
    material.NormalizeNormals = true;
    node->getMaterial(0) = material;

    // Now create a triangle selector for it.  The selector will know that it
    // is associated with an animated node, and will update itself as necessary.
    selector = smgr->createTriangleSelector(node);
    node->setTriangleSelector(selector);
    selector->drop();
    scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();

```

In the main loop

```
while(device->run())
    if (device->isWindowActive())
    {
            driver->beginScene(true, true, 0);
            smgr->drawAll();
            scene::ISceneNode * selectedSceneNode =
                    collMan->getSceneNodeAndCollisionPointFromRay(
                                    ray,
                                    intersection, // This will be the position of the collision
                                    hitTriangle, // This will be the triangle hit in the collision
                                    IDFlag_IsPickable, // This ensures that only nodes that we have
                                                    // set up to be pickable are considered
                                    0); // Check the entire scene (this is actually the implicit default)

            // If the ray hit anything draw the triangle that was hit.
            if(selectedSceneNode)
            {
                    driver->setTransform(video::ETS_WORLD, core::matrix4());
                    driver->setMaterial(material);
                    driver->draw3DTriangle(hitTriangle, video::SColor(0,255,0,0));

            }

            // We're all done drawing, so end the scene.
            driver->endScene();
     }

```

---
Tags: camera, raycasting, irrlicht
---


# Question
Title: how disable texture after drawing an object?
i try to make a textured object then draw other without (only colored).

i had tried to play with glEnable/Disable(GL10.GL\_TEXTURE\_2D) , gl.glEnable/DisableClientState(GL10.GL\_COLOR\_ARRAY/GL10.GL\_TEXTURE\_COORD\_ARRAY);

But i never get the result i expect.

(first colored + textured then others textured and colored too) (first colored and not textured then other colored and not textured)

i don't know if this is because i don't disable some things at the good place or if i missing something.

# Answer
> 3 votes
glBindTexture(GL\_TEXTURE\_2D, 0) switches to the default texture; unless you've changed the default, that should do what you want.

# Answer
> 3 votes
glDisable(GL\_TEXTURE\_2D) should do it, unless you have other texture targets enabled (eg. GL\_TEXTURE\_1D, GL\_TEXTURE\_3D or GL\_TEXTURE\_CUBE\_MAP)

As a debugging mechanism, try use glPushAttrib(GL\_ALL\_ATTRIB\_BITS) before setting up any state for your textured rendering, then use glPopAttrib() afterwards. Move the push and pop down/up until you find out what state is causing your subsequent objects to be textured incorrectly, and then fix it and remove the push/pops.

Failing that, use gDEBugger, an OpenGL debugger to try narrow down your problem. This debugger was recently made free! (see: http://www.gremedy.com/purchase.php)

---
Tags: android, java, textures, opengl-es
---


# Question
Title: Are there existing forums/QA sites specific to PS3 or Xbox360 development?
I'm wondering if there are existing forums, or sites similar to this one, that are targeted specifically to PS3 developers, or possibly, targeted specifically towards Xbox 360 developers? Is all of this information proprietary, and therefore "secret," or do communities of developers for these platforms exist?

Thanks as always!

# Answer
All 3 platform holders provide forums / newsgroups which are strictly for registered (licensed) developers only. In general they provide a second tier of support for developers, allowing folks to share problems and solutions in a shared forum with the developer support teams also read. It is a specific part of the licence agreement that the development SDKs and any information about them is not shared outwith the developer or those secure shared forums/newsgroups.

XNA on X360 development and PS3 Linux are allowed by Microsoft and Sony. Anything else (Wii, PSP, etc.) is home-brew only and not sanctioned (since it involves hacking the hardware); although that's not to say there aren't plenty of forums out there for that.
> 2 votes

# Answer
PS3 DevNet has forums I think, but I've never used them. MS provides developer support via email, but no list/forum that I've seen. In both cases you need to have a contract with them and be under NDA yada yada. If you are doing XNA/CC for the Xbox there are plenty of forums for that at least. There are some forums out there that have more than their fair share of professional devs, but thats all unofficial.
> 0 votes

---
Tags: xbox360, playstation3
---


# Question
Title: Microsoft and media - using the new stuff
Over the past 5 or so years, Microsoft has released APIs / that is intended to replace older APIs:

* (2006) Direct3D10
* (2009) Direct3D11
* (2008) XAudio2 / *deprecates DirectSound*
* (2006) Windows Media Foundation / *replaces DirectShow*

But 66% of Windows users are still on Windows XP as of Oct 2010.

Win XP doesn't and won't have:

* Windows Media Foundation
* Direct2D
* DirectWrite
* D3D10
* D3D11

There's a lot of cool stuff in these API's! My question is **is there any point, as a game dev, in migrating to the newer technology while you still have to support the old technology and provide a similar gaming experience?**

Microsofts refusal to support D3D 11 on XP means there are some cool shader FX that are only supported on Windows 7 machines, such as geometry shaders

http://knol.google.com/k/-/-/2lijysgth48w1/8oyyfu/image2.png

But its generally not that acceptable to say something like "Hey those cool geometry shader FX only show up **if you're running Windows 7!**" Suddenly you as a game developer are part of the angry microsoft upgrade push.

> UPGRADE YOUR SYSTEM SO YOU CAN PLAY THE GAME!
> love,
> Microsoft

My point is, if I write code for D3D11, and then I'm going to have to double-up and dupe the rendering code on D3D9 and work extra hard to manually reproduce the stuff that APIs like DirectWrite do for me so easily, **why should I bother learning D3D11 at all**?

# Answer
> 8 votes
That 66% percent of users on XP are not 60% of gamers who can run an intensive game. For that I would look more toward the Steam Hardware Survey. As of November 2010, almost 60% of Steam Gamers have a DX10 system.

From what I understand DX11 is really similar DX10, but has some new features. It seems like you could write a 9 and 10 version and if you really want to use some extra features to enable eye-candy you could also port the 10 version pretty easily and support the new features.

**And to answer why you should learn it, I think you should learn it if you want the features it provides, if you don't want or need them, don't learn it.**

# Answer
> 4 votes
This is a business decision rather than a technical one. You have to look at the set of potential customers you are excluding by insisting on DX10/11 (as mentioned elsewhere, maybe 57% of Unity users), and compare it against the extra sales you expect by using tech only available in DX10/11.

If your game is not graphically pushing boundaries, you're probably better off making it look as good as it can on with DX9 tech, where you can maximise your potential sales. If it's supposed to be cutting edge, then limiting it to DX9 tech might make it look dated.

The number of potential sales lost by excluding XP customers will pretty much only go down from here. How fast it will drop is not clear, but as has been mentioned, the W7 platform is much more attractive than Vista, so you can probably expect a much more rapid uptake now than while Vista was the current OS. But certainly this will become less and less relevant as a specific issue.

# Answer
> 3 votes
Well it isn't just the percentage of users at the point in time you are starting to make the game that you care about. It's the percentage of users when your game is scheduled to ship (which for a lot of games can be several years down the line). Specifically in this case, Windows 7 has significantly less of a bad rap than Vista has in the gaming circles. Whenever those XP users upgrade their machine next they'll probably install 7 on it.

Plus you can be pretty sure that the techniques in DX11 are probably going to be part of the platform for whatever Microsoft's next console will be, so there's that.

# Answer
> 3 votes
> is there any point, as a game dev, in migrating to the newer technology while you still **have** to support the old technology and provide a similar gaming experience?

Emphasis mine: if you *have* to, then no. If you don't *have* to, then yes.

It's always a choice. Weigh up what you want to make against the number of people you want to be able to experience it.

Personally I'm on Windows XP, and won't be upgrading for a year or two, as XP does what I need. You talk about cool shader fx; I absolutely do not care about cool shader fx. A developer whose main concern is which shaders they can use is not one whose game I am going to buy, as they sound more interested in technology than gameplay.

But if that's the sort of software you want to make, that's entirely your decision - people like me are not in your target market, and you don't need to care about what I think. Most of the people in your target market are indeed going to be upgrading early and often. So you can aim at them. Just don't complain when you don't reach the mass-market - because you weren't making a game for them in the first place.

---
Tags: directx
---


# Question
Title: Was C++ designed for speed, and is it better to not use high level features when teaming with inexperienced programmers?
I have read some optimisation guide for C++, and it seems it requires more knowledge to have a fast C++ code, than using C++ without the high level features of C++ (classes, templates, inheritance, etc.).

C++ is a powerful language, and will be the one used in game programming for a long time, and is still fast because it is a C subset, but as John Carmack said, it has to be used correctly: when dealing with programmers who can't guess alone how to make fast C++ code, isn't it a good idea to force them not to use high level features which can me more delicate to optimise ?

I know compilers do a very good job at optimizing the code they are being given, but they can't change it, or do they compilers that feature some sort of warnings that encourages a good use of OOP, or can compilers automatically optimize OOP code even if it is a slow one ?

EDIT: I'm not bashing C++ high level features bere, I'm just talking about some of the very high level stuff like multiple inheritance and abstract classes. Classes are awesome when just compared to struct's, but multiple inheritance is not that much a universal solution to all software problems.

# Answer
Okay:

1. C++ is a C superset, not a C subset
2. If you're teaming with inexperienced programmers that don't understand inheritance, then it doesn't really matter what language you choose, they're still going to have problems.
3. Compilers can do an amazing job with optimisation. Chances are, apart from a few edge cases, you'll have a hard job writing faster assembly language versions of your functions. And even if you do, it'll take you far longer than writing it in C/C++. Trust that the compiler writers know what they are doing, and worry more about whether or not your team knows what it is doing.

I feel that you are mistaking use of the extended feature set of C++ (inheritance, classes, templates) with a) writing slow code, and b) writing hard to understand code.

You can write hard to understand and slow code in C as well. You can write it in any language. Your choice of language does not automatically lead to good or bad code. C++ simply gives you more language features that might cause problems (i.e. enough rope to hang yourself with). It is a mistake to think that if you simply avoid using the features that make C++ different from C, that you will not encounter those problems.

All that said, there are complex structures (multiple inheritance, complicated template code, and various other anti-patterns) which you absolutely should avoid using unless everyone on your team understands them. While they are possible, they are certainly not advised, both for performance and maintainability reasons. But you can write some incredibly clean, structured, and above all fast code using C++'s features, even when you are a programmer of only medium skill. The language is not what causes the problem.

With any language, you should be aware of the consequences of using particular language features, both in terms of performance, and in terms of maintainability and readability.
> 18 votes

# Answer
> isn't it a good idea to force them not to use high level features which can me more delicate to optimise ?

Let me preface this entire answer with the fact that this is *my* personal philosophy on coding practices and how I run my teams, and that there are different people with different priorities.

My answer to this is absolutely not, but that's because speed of code execution isn't as important as *shipping the game*.

The reason those higher level features exist is so that you can write code a little more abstractly. And by doing that you can theoretically get more done in less time (or fewer lines of code). Usually there is a speed tradeoff. For example, virtual functions and RTTI have a speed hit. Is it worth the speed hit? In my eyes, the answer is yes.

Anyway, for all the computationally heavy stuff (i.e. pathfinding), it's more about the algorithm anyway.

If you have sections of code that are speed critical (not all code is speed critical), then maybe you want to take one of your more advanced guys and optimize that carefully. Each individual particle structure probably shouldn't have a vtable, for example. But part of being a good technical director is realizing where those heavy bottlenecks are and paying special attention to them.

Besides, in my experience, your real performance gains come from things like how your code manages the GPU. Draw calls, occlusion, that kind of thing.

Specifically speaking of your Carmack reference, read the section on "code lineage" from this article (it's at the bottom). The Doom Resurrection code base I worked on went heavy on boost/stl/delgates/etc, the levels themselves used LUA as a scripting language, and there were a bunch of things that were not ideal at all in terms of performance. I'm not going to say the code was perfect at all. Even with my lax feeling about code performance there were things I didn't like. But we shipped the game quickly with a few number of people. And you can read Carmack's own impressions on it there.
> 2 votes

---
Tags: c++
---


title: Top down space game control problem

text:
# Question
Title: Top down space game control problem
As the title suggests I'm developing a top down space game.

I'm not looking to use newtonian physics with the player controlled ship. I'm trying to achieve a control scheme somewhat similar to that of FlatSpace 2 (awesome game). I can't figure out how to achieve this feeling with keyboard controls as opposed to mouse controls though. Any suggestions?

I'm using Unity3d and C# or javaScript (unityScript or whatever is the correct term) works fine if you want to drop some code examples.

Edit: Of course I should describe FlatSpace 2's control scheme, sorry. You hold the mouse button down and move the mouse in the direction you want the ship to move in. But it's not the controls I don't know how to do but rather the feeling of a mix of driving a car and flying an aircraft. It's really well made. Youtube link: FlatSpace2 on iPhone

I'm not developing an iPhone game but the video shows the principle of the movement style.
**Edit 2** As there seems to be a slight interest, I'll post the version of the code I've used to continue. It works good enough. Sometimes good enough is sufficient!

```
using UnityEngine;
using System.Collections;

public class ShipMovement : MonoBehaviour
{
    public float directionModifier;
    float shipRotationAngle;
    public float shipRotationSpeed = 0;
    public double thrustModifier;
    public double accelerationModifier;
    public double shipBaseAcceleration = 0;
    public Vector2 directionVector;
    public Vector2 accelerationVector = new Vector2(0,0);
    public Vector2 frictionVector = new Vector2(0,0);
    public int shipFriction = 0;
    public Vector2 shipSpeedVector;
    public Vector2 shipPositionVector;
    public Vector2 speedCap = new Vector2(0,0);

    void Update()
    {

   directionModifier = -Input.GetAxis("Horizontal");

   shipRotationAngle += ( shipRotationSpeed * directionModifier ) * Time.deltaTime;

   thrustModifier = Input.GetAxis("Vertical");

   accelerationModifier = ( ( shipBaseAcceleration * thrustModifier ) ) * Time.deltaTime;

   directionVector = new Vector2( Mathf.Cos(shipRotationAngle ), Mathf.Sin(shipRotationAngle) );
   //accelerationVector = Vector2(directionVector.x * System.Convert.ToDouble(accelerationModifier), directionVector.y * System.Convert.ToDouble(accelerationModifier));
   accelerationVector.x = directionVector.x * (float)accelerationModifier;
    accelerationVector.y = directionVector.y * (float)accelerationModifier;
   // Set friction based on how "floaty" controls you want

    shipSpeedVector.x *= 0.9f; //Use a variable here
    shipSpeedVector.y *= 0.9f; //<-- as well
   shipSpeedVector += accelerationVector;

   shipPositionVector += shipSpeedVector;

   gameObject.transform.position = new Vector3(shipPositionVector.x, 0, shipPositionVector.y);
    }

}

```

# Answer
> 4 votes
So if I understand correctly, you want left and right arrows to turn your ship, and up and down arrows to control thrust.

I have implemented this control scheme in a space shooter prototype I made once.

The below code is very naive non-language specific code example. Don't take it too literally.

EDIT: OOps, the code doesn't cap negative acceleration caused by friction. So the ship will actually start going backwards after a while. So changed the "code" a bit.

```
update( deltaTime )
{

   if( leftButtonPressed )
   {
      directionModifier = 1
   }
   else if ( rightButtonPressed ) {
      directionModifier = -1
   }
   else {
     directionModifier = 0;
   }

   shipRotationAngle += ( shipRotationSpeed * directionModifier ) * deltaTime;

   if( upButtonPressed ) {
     thrustModifier = 1
   }
   else if( downButtonPressed ) {
     thrustModifier = -1
   }
   else {
     thrustModifier = 0
   }

   accelerationModifier = ( ( shipBaseAcceleration * thrustModifier ) ) * deltaTime

   directionVector = Vector2( cos( shipRotationAngle ), sin ( shipRotationAngle ) )
   accelerationVector = Vector2( directionVector.x * accelerationModifier, directionVector.y * accelerationModifier )

   // Set friction based on how "floaty" controls you want
   frictionVector = -directionVector * shipFriction

   shipSpeedVector += accelerationVector

   // APPLY friction vector to shipSpeedVector
   // Make sure that friction vector doesn't speed to go in the opposite of the
   // original direction. Otherwise your ship will go backwards instead of stop.

   //IMPORTANT: (I'm too lazy to add code here) Cap speedvector to a maximum speed.
   //Remember to cap total speed, not just X and Y components of the speedVector

   shipPositionVector += shipSpeedVector
}

```

# Answer
> 1 votes
i converted the psuedo-code into C#:

```
void Update()
{

   directionModifier = Input.GetAxis("Horizontal");

   shipRotationAngle += ( shipRotationSpeed * directionModifier ) * Time.deltaTime;

   thrustModifier = Input.GetAxis("Vertical");

   accelerationModifier = ( ( shipBaseAcceleration * thrustModifier ) ) * Time.deltaTime;

   directionVector = new Vector2( Math.Cos(shipRotationAngle ), Math.Sin(shipRotationAngle) );
   accelerationVector = new Vector2( directionVector.x * accelerationModifier, directionVector.y * accelerationModifier );

   // Set friction based on how "floaty" controls you want
   frictionVector = -directionVector * shipFriction;

   shipSpeedVector += accelerationVector;

   // APPLY friction vector to shipSpeedVector
   // Make sure that friction vector doesn't speed to go in the opposite of the
   // original direction. Otherwise your ship will go backwards instead of stop.

   //IMPORTANT: (I'm too lazy to add code here) Cap speedvector to a maximum speed.
   //Remember to cap total speed, not just X and Y components of the speedVector

   shipPositionVector += shipSpeedVector;
}

```

If there is something wrong with this, please leave a comment.

Thanks to Nailer for providing psuedo-code

---
Tags: c#, unity, javascript
---


# Question
Title: Trying to find a game development competition
About a month or two ago one of my friends participaded in a game development competition. The theme was "infinity". I think he had either a week or a month to finish the game. The problem is I cannot for the life of me find or remeber the name of the site. (Its not Ludum Dare)

I am hoping someone here might know what I am talking about.

# Answer
This? http://experimentalgameplay.com/blog/2010/09/neverending-in-september/
> 2 votes

---
Tags: competition
---


# Question
Title: How to prevent a character from going up a steep hill with a height map?
I've been trying to make my character unable to go up steep hills, but I just can't manage to make it work. I'm using a simple height map which stores the height for every (x, z) point within the map. I've tried to do this(using C# and XNA):

```
float height1 = TerrainHeightAt(cam.Position);
float height2 = TerrainHeightAt(cam.Position + cam.GetVelocity());
//If the difference between the two is bigger than a certain constant, don't move.

```

Basically I find the current height and the future height of the camera. Then, I check if the character is attempting to go up a too steep hill, and if so, I prevent the character from moving. This is not working and I can't see why it isn't.

So my question is: **What am I doing wrong?** I would appreciate any link(specially using XNA, but general articles would be great too) showing how to achieve this.

Thank you.

# Answer
Well if you can calculate the normal of the terrain at your desired future point, you can see if the angle of that is less than some value, and if is then allow the player to move along that.
> 6 votes

# Answer
The problem with height difference is that it's dependent on forward velocity. So as long as a the player slows down enough they could climb almost anything.

* If you have a 45° slope and you move forward 1 unit/update you'll travel up 1 unit/update.
* If you have a 80° slope and you move forward .17 unit/update you'll travel up 1 unit/update

As Tetrad said, you need the normal of the ground under the player and compare that to the direction they are trying to move. If the angle difference is over a certain threshold don't allow the movement.
> 4 votes

# Answer
check the diffrence between the two heights to give you something of a steepness mesure.

```
if(height1 < height2) {
    // Its uphill
    float diffrence = height2 - height1;
    if(diffrence > somepredefinedmax)
         StopMove();
}

```
> 3 votes

---
Tags: xna, c#, maps
---


title: 2D Top down view maps

text:
# Question
Title: 2D Top down view maps
I was wondering how this works.

Do you load the **complete** map when the game starts up, or do you load parts of the map at runtime?

And how would you save the maps? Would it be in XML or some binary format?

Thanks!

# Answer
> 23 votes
I agree with eBusiness. It depends on the size and how you want to edit it.

**Estimate the byte size of your map** in a reasonably compact representation. Also decide which parts of the map can change as the game plays. Those parts that don't change can be loaded and don't have to be saved. If the estimated size is small, just store everything in memory. It's not worth the extra complexity of loading parts of the map and tracking what you've loaded or not, unless the data is so large that it's necessary.

For example if you were writing **Civilization II**, your map size might be 100x100 tiles.

1. Each tile is one of 12 types, so you can store that in 4 bits. That means the main map is 100 x 100 x 0.5 bytes = 5,000 bytes to store the tile types. The main map never changes.
2. You can also improve map tiles with roads, irrigation, etc., and there are up to 7 improvements. That means 2^7 different values, taking 7 bits, but we'd probably just use 1 byte for it. That give us 100 x 100 x 1 byte = 10,000 bytes to store the improvements.
3. The fog of war tells us which map tiles you've seen, so you need 1 bit per player. If you limit to 8 players, that's another byte per map tile, or 10,000 bytes for the fog of war.
4. Finally, there are all the cities and units. You might estimate that each player has up to 20 cities and 100 units, and each of these might require 100 bytes of data (wild guess), so that's 12,000 bytes (much more if you're using XML).

That's under 30k for a compact binary representation the Civ II map + objects, so you can store all of it in memory, even if you use a verbose format that's much larger. I got the above numbers from someone reverse engineering the Civ II map structure.

**Daggerfall**, considered by some to have a ridiculously large map, appears to be 5000x2500 and around 25 megabytes, but it also has a large number of NPCs (750,000 is what I've read but that seems very high). On today's desktop/laptop machines this too could fit into memory, but on mobile devices or browsers that might be a bit too big. There's a wiki describing the Daggerfall map format.

You can reduce the size by identifying and **factoring out redundancy**. For example, instead of storing 100,000 identical trees or swords each in an XML format, store one tree and one sword and 100,000 references to them. In the binary formats that reference might be only 1 or 2 bytes, and in a more verbose format the reference can still be reasonably small.

**Do the simplest thing** that works for your game. If the map is small, it doesn't matter if you use a compact or verbose format. If the compact format would fit into memory but the verbose format would not, you have to decide whether the extra work of the binary format is more or less than the extra work of loading portions of the map. That'll depend on the game. In a Civ-like game where you need all the data to simulate turns, the binary format is probably a better choice. In a Daggerfall-like game where you don't need to load areas except what's near the player, loading portions of the map is probably a better choice. If the map is *so* big that even the compact format won't fit in memory, then first ask yourself if it's really worth all the extra work to deal with it, and if so, design a binary format that you can load portions of.

For my current (hobby) project, the maps and all the objects on them fit into 50 MB, so keeping it all in memory would be fine. However, I want it to run in the browser, and 50 MB is more than I want to transfer over the network, so I'm keeping them all in memory on the server and then loading only parts of the world in the client. My map tiles are 1 byte per tile, 2048x2048 tiles (4 MB). The objects (trees, chairs, orcs, etc.) are JSON-encoded for simplicity. In the client I only load the map areas (including their objects) that are near the player.

# Answer
> 4 votes
How much to load depends at least on how big the map is, if the data can reasonably fit in memory then there is really no reason to bother with progressive loading.

The most notable thing XML does is take up a lot of extra storage/memory/network space/traffic. If you think using XML is fun, be sure to do so only for relatively small amounts of data.

When you design a data format you should have in mind how you want to edit this data. You could use a simple text editor to write your data as a plain text file, you could use these files directly or you could convert them to a binary format to save space. You could use an image editor to make your levels as bitmaps, again, you might want to convert to a smaller file.

Or you could make your own editor, in which case there is little reason for not using a compact binary format.

# Answer
> 1 votes
There is no one answer to these questions. These are all inherently up to you.

You could save maps anyway you like and display/render them at any time.

---
Tags: 2d, tiles, sprites, maps
---


# Question
Title: How to integrate PS3 & Xbox 360 games to Facebook?
After some research online, I am unable to find any concrete references for how to go about implementing Facebook functionality from either Xbox 360 or PS3 games. There is apparently some degree of integration, but how does one go about hooking into Facebook's API from within a console title?

Is there any How To documentation online? Or alternatively, is anyone aware of a developer that specializes in incorporating this type of functionality in an existing codebase?

For an answer unaffected by NDA, does anyone know of a company that specializes in integrating PS3 or Xbox games with Facebook?

# Answer
You cannot do it directly. We moved it so all the API interaction was done server-side so it was post-gateway. Made screenshots a real pain actually. You could have some limited interaction if your Facebook app just watched for changes in their Live profile, not sure if you can get stuff like the rich presence data that way though.
> 1 votes

---
Tags: facebook, xbox360, playstation3
---


title: A good Unity project to get started

text:
# Question
Title: A good Unity project to get started
What types of game should I start making to get started with Unity 3D? Any ideas?

Remember: it should be small, and not art-intensive.

# Answer
> 4 votes
Take one of the existing Unity example projects and modify it. This gives you a good solid base to work from.

---
Tags: unity
---


title: Effects for Programmers

text:
# Question
Title: Effects for Programmers
Does anyone have any good resources for creating special effects, aimed at programmers. I'm not specifically interested in particle effects, but broader things like:

1. Fullscreen effects, blur, depth of field, damage
2. Explosions, shockwaves
3. Weapons, lasers, projectile
4. Environment - light "glows" and beams, water, bubbles, dust etc

I'm interested in these things from a technical perspective rather than an artistic one.

EDIT: To clarify, I'm not interested in the low level details like "a method for doing depth peeling on SPUs" or "fast particle rendering with vertex textures", I'm interested in how people have combined various techniques into a recipe to show a special effect for the game.

For example - when rendering a "space" explosion:

1. Draw opaque bright sphere at center.
2. Draw alpha'd shockwave around a random axis.
3. Expand sphere and decrease alpha.
4. Expand shockwave and rotate UVs.
5. Spawn particles showering randomly from center.
6. Wobble camera when shockwave reaches viewer position.

# Answer
> 6 votes
I'm a big fan of many things moving simultaneously at slightly different rates.

Take a look at (shameless plug) KØЯ., a vertical shooter I wrote a bit back. I'm quite proud of the explosions. They're a bunch of simple arcs (literally, I drew a circle in Gimp, then deleted an offset circle out of it, then saved it as a .png) rotating about all three axes at a random speed, expanding at various speeds, slowing down at different speeds, and fading out at different speeds. All of that is random. I just tweaked the randomness a bit until it looked good and went from there.

One thing I've started to realize is that subtle intentional breaking of the laws of physics looks awesome. I imagine we've all seen anime with people leaping off walls or falling ten stories and landing in an instant. We know that stuff isn't possible, so our brains interpret it as "omg this person is so awesome they can defy physics."

The explosion effects are the same way. You can't have an expanding sphere of explosion with some parts accelerating and some parts decelerating. That's crazy talk! That can't happen! And yet, that's exactly what I do, so, bam! It looks awesome.

You can also - as you can see in KØЯ. - get a lot of mileage out of "stylistic design" (read as "the programmer sucks at art so he makes monsters that consist of a bunch of colored boxes") and fancy linework and bloom, as long as it's all consistent and looks like the designer was clever instead of just incompetent.

Fundamentally, though, look at other games or movies and see what they did. Go play Gratuitous Space Battles for a few hours. Or look at GSB's source material - space combat movies, Star Trek and Star Wars, and go from there. Play games with awesome effects, watch movies with awesome effects, watch anime with awesome effects. Analyze it from there and figure out how to fake the behavior you want.

# Answer
> 12 votes
Examples for these kind of things is pretty much what the GPU Gems series covers.

Books , , and  are available for free on nVidia's website.

# Answer
> 10 votes
If you're relatively new to graphics programming, the most important thing for a lot of special effects is to understand alpha blending, and blending modes in general.

For glows, explosions, and particle effects, additive blending is your best friend.

Once you understand the effect of adding or multiplying colours, and the ways in which you can use alpha channels, then you are well on your way towards creating some fairly decent special effects.

Remember that good special effects aren't always the most complex or most physically correct effects. Simple effects can often be very effective if executed well.

# Answer
> 1 votes
Look at some of the early playstation era games, like Final Fantasy 7. Given the low resolution it is often easy to pick out the parts, or at least a good portion of them.

Even given your edit though this is still a very artist based question, probably more so than before. For this reason there is not a particular formula for an explosion or whatnot. 10 different animators would easily create 10 different explosions when given the same precise request.

---
Tags: software-engineering, graphics-programming, graphic-effects, special-effects
---


# Question
Title: Mini Game Platform for PC - similar to Warcraft III Custom Games
I think it would be fun to make a game for pc that has an online community like Warcraft III (the RTS, not the MMORPG), aka there's lobbies and chat rooms and users can host games to play with eachother. And there's no seriousness, just fun mini games that last on average 30-60 minutes, more or less depending on the game.

I searched google but it's really hard to find anything. Is there anything similar to this idea that's already out there? Or is this a first?

Also, in making this, any recommendations, flaming, or random comments? (yes I know it is hard to make an online game and such, especially since I have no experience with networking. I do have 2-3 years of programming experience, however).

**Some more info on what I want to create.**

I want it to be easy for users to create games and play with friends. All of us game creators have ideas, and we probably draw them out on paper (graph paper for me). Wouldn't it be amazing if it was a matter of a couple hours to transfer that idea to a fully working game, even if it is in 3d?

# Answer
If you just want to kludge a couple of quick game ideas together for online play, have you already looked at Starcraft 2's Galaxy Editor? It's the first thing that came to mind, since you already seem familiar with Warcraft III Custom Games. You can whip up a basic Starcraft 2 Melee map together in a few minutes, and that's a great way to learn the tool and have fun with friends at the same time. Then drill down into Blizzard's scripting tools and create custom games. It'll still all look like Starcraft, but you can at least try out new game ideas fairly quickly.

If you're not specifically interested in multiplayer and just want to use chat rooms for socializing, I'd suggest looking at Kongregate's API. You'll get pretty robust chat and community functionality for very little code, and you can focus your programming experience on making small Actionscript games.
> 3 votes

---
Tags: game-design, game-industry, game-center, online
---


title: WPF & C# - Game Overlay + Streaming

text:
# Question
Title: WPF & C# - Game Overlay + Streaming
Greetings

I'm in the process of making a Scoreboard for a game (Starcraft II). This scoreboard is being made as a WPF Application with a C# code-behind. I already have a version which works for 90% in WinForms but I lacked the support to easily make it look a lot nicer which are available in WPF.

The point of this application will be to form a kind of overlay on top of a running game. In this overlay people can see the Score, Map, Players, Colors, etc. Basically all the info they need.

Since the main look of the app in WPF is based on an image with a transparent background I have set most Background values to Transparent. However when I do this the entire application does not get registered by streaming software. For example it just shows my Desktop or the game I'm playing but not my application even though it IS there. I can see it with my own eyes but the audience on the stream cannot.

Does anyone have any experience with this matter because it's really doing my head in. My entire application will be useless if it is not visible on streams. If I have to put the background on a color rather than transparent the UI will be completely demolished as well in terms of looks.

I'm basically trying to make a game-overlay in C# & WPF which is able to update with little hassle for the viewer. I have little to no knowledge regarding C++ and DirectX so I would not know where to start in that regard. This project currently holds 1 Developer and 1 Graphic Designer so it isn't a big scaled project, it will also be distributed for free once/if it gets finished. Any tips are welcome!

Thank you for your time reading and your possible insights.

# Answer
Your window gets rendered using the HW acceleration of the video card to get transparency effects, and bypasses standard Windows GDI stack, which is captured by most streaming utilities.

Basically, you can a) hook DirectX's drawing functions and draw your overlay on top of the game (like Fraps does, for displaying FPS counter. AFAIK Steam overlay works the same way), though it can cause problems with anti-cheating tools

or b) advice your users to use streaming apps that CAN capture layered windows (as there are a number of screenshot tools that can, I assume there are streaming apps, too, though i havent used them personally)

or c) make important parts of your application square and not transparent.

or d) contact Blizzard to see if they have SDK for interacting with the game (Little chance, but you could probably at least get some advices)
> 2 votes

---
Tags: c#, pc, wpf
---


# Question
Title: How to control the list of items on the screen?
I am an experienced app developer (c#) however I am just looking at starting 2d game development.

I have read some articles and understand the concept of the gaming loop controlling the application flow. However there seems few articles explaining general concepts for an existing developer. From these I assuming that each on screen item becomes it's own object and handles it's own location, drawing, collision detection etc. (though correct me if I am wrong)

My question is how to control the list of items on the screen? Are these stored in a simple collection and then removed as they fall out of play and is this collection held by the game engine or individual components? An example would be bullets from a gun?

# Answer
> 5 votes
> Are these stored in a simple collection and then removed as they fall out of play and is this collection held by the game engine or individual components?

There are a lot of ways of handling it, but sure, that's one way.

What some games do is have a giant list of all Entities in the world (which implies that there's some World class, or equivalent, managing all this stuff), where everything in the game is an Entity.

Your update loop might look something like this:

```
update all entities
remove entities that are marked for removal
draw all entities

```

Some other games do sublists for different types of entities. Like there's a list of projectiles in the world whose loop is treated like the above. This way you don't necessarily have to have everything in the world have a singular base class.

# Answer
> 1 votes
I was having issues with this same thing, one good source to look at is the Octane 2D/3D Engine. I like the way it solves this exact problem; simply.

There are many ways to do it, but the general rule of thumb (for most things actually) is keep it as simple as you need it. You may need to up-grade it later, probably not.

A simple deque or list of entities is going to be the easiest. Then you simply need to iterate the list each game loop, updating all the entities (unless some ISDEAD flag has been set on them).

And your 'on screen item' is best described as a game object or game entity. :)

# Answer
> 0 votes
I've just started working on a 2-d game myself on android. I have a map and some menu/windows on the screen. I draw the map first, and for the menus, I have something like this in the main drawing loop:

```
drawMap(canvas);
if(menuActive) drawMenu(canvas);

```

The drawMenu will take care of drawing the menu at the correct place. However, to check whether the user clicked on the menu, I have something like this where I read in inputs:

```
if(menuActive) handle_menuAction(event);

```

Here I check whether the user clicked the menu location. The handle\_menuAction can do something like return true if the user hit the menu, or return false if they didn't.

If I wanted to turn off the menu, I just set menuActive = false and none of the drawMenu() or handle\_menuAction() will be activated and I don't have to worry about it anymore.

Hope this helps.

---
Tags: game-design, 2d, architecture
---


title: Creating A Board Game AI

text:
# Question
Title: Creating A Board Game AI
I want to code a board game that name is Okey and mostly popular in Turkey. http://en.wikipedia.org/wiki/Okey

But i have got some problems about AI.

Firslty let me explain the game..

The game is played by 4 players.

In this game there are 106 tiles, 2 of them are fake joker. Other 104 tiles are divided 4 colours generally green, black, blue and red. All colours have two sets of tiles. A set ise contains 13 tiles that numbered sequentially 1 to 13.

Each player start 14 tiles (one is start 15 and starts first) and throws one of the most unwanted tile the next player. Next player can get this tile or can get another tile from stack in the middle of table. The game played in anti-clockwise..

The aim of this game is find the valid sequence of 14 tiles as soon as possible. Player can align tiles by sequential numbers in the same colour until 13. For examle Green 1, Green 2, Green 3. There is an exception here, 1 can be follow to 13. For example Red 12, Red 13 and Red 1 is a valid set. But Red 13, Red 1 and Red 2 is not valid.

Or player can align tiles by colors in the same number. For examle Green 1, Black 1, Red 1, Blue 1.

Each set need to be 3 or more tiles to be valid and each of this set named as "Per". Less then 3 tiles is not valid for the finish. A valid finish set can be like this. G: Green, B:Blue, R:Red, BL: Black G1|G2|G3 B2|R2|BL2 R9|R10|R11|R12 BL13|R13|G13

Last thing, when starting game a tile selected to determine joker (okey). For example if you select Blue 3; Blue 4 will be joker (okey) and player can use this tile instead of any tile that player needs to win or complete a set (per).

Of course these rules are general rules and summarized to explain question. If you can read English you can check this link for more information http://tr.wikipedia.org/wiki/Okey or translated page by Google Translate http://translate.google.com/translate?js=n&prev=\_t&hl=en&ie=UTF-8&layout=2&eotf=1&sl=tr&tl=en&u=http://tr.wikipedia.org/wiki/Okey

So which AI algorithm that i can used? I searched for minimax theory and alpha beta pruning. But these theories are generally about 2 players game like chess or tic-tac-toe.

Original Question is at stackoverflow: https://stackoverflow.com/questions/4419628/creating-a-board-game-ai

# Answer
If you swap tiles for cards the description of the game sounds incredibly similar to the card game Gin Rummy. You may be able to find some direct AI resources by searching against that.

One option for AI that is agnostic to the number of players and can be used to create different AI personalities:

1. Play the board game, ideally with some friends, although you can play all the hands yourself, but with a computer handy and Excel open.
2. Talk out load what your thought process is. There will be a number of discrete points that you consider when making a decision. Things like "does the unwanted tile give me a playable set", or "get me a step close to a set", or "add to an existing playable set".
3. Then once you have the list of all the items you consider when making a decision of what tile to pick up and what tile to discard start to create number weights for them based on what is most important to you.
    1. Example: It might be three times as important for you to get the 3rd tile in a sequence as it is to get the 4th tile in an existing sequence.
4. Once you have all these weights for all the things you look at when making a decision you can use Excel to calculate a score for each action. So you have a worksheet where each row represents an action choice and each column represents a deciding factor. If that factor is true for that action you multiply it times the weight, if that factor is false you score it zero. Then you add up all the scores and the one with the highest value is what the AI will choose to do.
5. Play the game with Excel open. Each turn see if the score outcome matches the outcome you would choose. If it doesn't adjust the weights based on your thinking until it does. After several games the AI should play the game the same way you do. If you've been playing consistently with a group of friends who all have different weights then you'll have AI's with various personalities.

You can then control difficulty by not always selecting the highest rated option. Since the lower the score the worse the decision.
> 3 votes

---
Tags: c#, algorithm, ai, multiplayer
---


# Question
Title: How do I get an XNA 4.0 game to run on other machines?
Whenever I try and run a game made in XNA 4.0 on a machine other than one used for development, it just won't run. I've followed the instructions here to ensure that all the dependencies are present.

To be clear I've done the following:

1. Downloaded and installed the Microsoft .NET Framework 4 Client Profile.
2. Downloaded and installed the Microsoft XNA Framework Redistributable 4.0.
3. Made sure I am not using anything contained within `GamerServices` and `XNA.Net.*`, my references are as follows:

> Microsoft.Xna.Framework
> Microsoft.Xna.Framework.Avatar
> Microsoft.Xna.Framework.Game
> Microsoft.Xna.Framework.Graphics
> Microsoft.Xna.Framework.Storage
> Microsoft.Xna.Framework.Video
> Microsoft.Xna.Framework.Xact
> mscorlib
> System System.Core
> System.Windows.Forms
> System.Xml
> System.Xml.Linq

I also followed the advice here to ensure the problem was not within the code itself.

---

I've tried the follow methods to get it to run (on both Vista and 7):

* Use the built in publishing functionality. This results in an error saying that `Microsoft.Xna.Input.Touch` needs to be present in the GAC. I've tried adding `Microsoft.Xna.Input.Touch` to the references, and this does not fix the issue.
* Copy the XNA dll files locally. This results in an error message stating that `Microsoft.Xna.Game.dll or one of its dependencies could not be located`.
* Copy over everything contained in `Release`. This results in an `Application X stopped working...` or `APPCRASH` error message the second it starts. My code is never reached.

Is there any way to get this to work? I've been trying to get this to work with the deadline looming, and it's been a source of unneeded stress.

# Answer
> 6 votes
A clue may lie in the fact that there shouldn't be any Xna.Input.Touch reference in a windows project - XNA 4.0 only supports touch on WP7. Are you sure you have XNA 4.0 installed and not the *beta*, which did support Xna.Input.Touch on windows?

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


# Question
Title: Securing HTTP data from a JavaScript game to server
Suppose I am doing a JavaScript game, and I wish the game to update the server if the user has successfully completes the game and his outcome.

How should I ensure that the request came from the JavaScript game, and that the data sent has not been tampered with. I am using PHP as the server-side language.

I do understand that no strategies are going to be 100% fool-proof, and any measures taken is more of a deterrence than absolute protection.

**On Edit:** Let's supposed we're not using server verification of each user's step (as in a traditional MMO). The game could be a mini-game as part of a web game or educational game (space invaders or a real-time game, for example) and requiring a server-side component for each of those games could be tedious.

**Example:** Supposed, when the game is completed, a request is sent to the server via. AJAX

```
game_finished.php?user_id=1&outcome=success&score=88

```

A user could 'fake' the server in believing that the game has been completed correctly by sending that request to game\_finished.php. How could this be made more difficult?

# Answer
*a sliding block puzzle, for example*

This is an example where server-side verification is trivial. It doesn't need to verify each step until the game is over. Just send the entire move list, and the server replays it to make sure it's correct.

(Edit: The point of this answer isn't to pick on examples until you find one that isn't trivially validatable. Rather, it should make you go back and look at the game you're actually making - it's probably trivially validatable, or only needs a small tweak to be.)
> 10 votes

# Answer
You can do it the Warcraft way: Use Javascript only for sending movement commands to the server, and let the server handle logic.

This still leaves you open to robots (javascript programs that move things faster an more precisely than humanly possible) but that's a big step compared to leaving the door open to the /game\_finished.php trick.
> 2 votes

# Answer
If you are having the client calculate the score, there is no way to validate it beyond (as pointed out) having the server replay the game to confirm it gets the same score.

There are though types of games you can design that don't work based on just a numeric score. A server side script can generate a random addition math problem for example, and when the user submits the answer it can compare their answer with the correct one and score it server side.

But if your game is a complex one (like the space invaders example), there's not much you can do about it beyond either a) trusting the client, or b) letting the server manage the game.
> 1 votes

# Answer
There are many methods, but all of them will fail eventually. You can add some hash value, or query key renewed with every query.

But the most important thing is, that all of your super **encoding functions are send as source codes to clients' browser** and that is THE problem. To make it little harder, you can use function send by Ajax query, so sources won't be available under an url. Function should be send compressed, and maybe even in parts, so it will be harder to copy it all. I would also check this code in page like http://jsbeautifier.org/ if after making it readable your code is easy to understand.
> -1 votes

---
Tags: javascript, security, php
---


title: Cross platform data format

text:
# Question
Title: Cross platform data format
I've got a best/common practice question about cross platform development. We're developing a Unity game and we've got a custom data format (a modified jpeg) that a C# tool we developed pumps out and gets loaded into unity using a dll. We use some nice gdi+ tricks on Windows with this file format, however when we move this to the Mac, we're running into issues that we think is the mono implementation of gdi+ is missing something.

That aside we're not sure what the best practice moving forward is. Should we develop a new file format that works cross platform and is loaded the same on both systems, or should we use a platform specific data format that allows for the use of the C# tricks on Windows and maybe a different trick on Mac?

# Answer
> 3 votes
Best practise is definitely to define your data format independent from any tools you use to read or write it, so if best practice is your criterion you should probably design a new format. But practically, if you can reasonably hack a way to get the format working on Mono that may be an okay solution.

Different formats for different platforms? I really wouldn't want to go there, that's bona fide technical debt.

Edit:
I'd suggest that you simply store multiple files in a container format, if you got tools available for handling it you could use a zip file, otherwise a simple custom format with length prefixed blocks may be optimal.

---
Tags: cross-platform
---


# Question
Title: Handling sound effects for Multiple Collisions
How can I generate somewhat realistic sound effects for collisions in a physics engine that simulates lots of objects?

E.g. take \>10 marbles that are bouncing off walls and off each other.

If I generate a sound for each collision I would quickly overload the system (Windows Phone 7).

Is there an algorithm that lets me combine multiple collisions to create fewer sound effect instances?

# Answer
Usually what you do in this case is let the sound system handle it.

So somewhere there's a collision happening. And where that collision happens you call a "play bounce sound" function.

In pseudocode just change your sound class to do something like this

```
void Update()
{
    timeSinceLastBounceSound += Time.deltaTime;
}

void PlayBounceSound()
{
    if( timeSinceLastBounceSound < someThreshold )
        return;

    // do whatever you do to play the sound
}

```
> 2 votes

# Answer
You could create a new sound that is a sort of "many marbles hitting at once" sound, then play it if there are more than 10 active collisions at once. Play any individual collision under 10, and then the "many marbles" sound if there are more than 10.

Think of it like simulating a crowd applauding. At some point it just sounds like a crowd applauding, not a collection of individual claps.
> 4 votes

---
Tags: performance, sound, xna-4.0, windows-phone-7
---


# Question
Title: Lightwight cross browser library for server side push?
I am looking for a lightweight javascript library that allows the server to push update information to the client reliably and regularly. We use a fixed turn time of 300ms and often there are only about 20 bytes of changes. So doing polling using XMLHttpRequest would imply a huge overhead (3-way tcp handshake, http request headers, http response header).

There area number of alternatives, but they have limited browser support:

* streaming \<script\>-tags in another frame (does this work on IE?)
* MIME multipart/x-mixed-replace responses (Firefox, Safari, Opera only?)
* WebSockets (removed from recent beta version of Firefox and announced to be removed from Opera 11 because of security issues)
* Server-sent events (only Opera?)
* Java / Flash relays (requires the users to have those plugins installed)
* Polling using XMLHttpRequest (huge overhead)

Is there a website which has *recent* information on which technology works in which browser? Are there javascript libraries which provide a common cross browser interface that hides the messy details? (Yes, i know that it still requires me to write multiple server sides, but that is rather easy. And more important it is easy to write automatic tests for the server sides).

# Answer
> 7 votes
You should look at socket.io

http://socket.io/

It combines almost all the technologies you describe in a consistent API

---
Tags: networking, html5, server-push
---


# Question
Title: Minimum target resolution for a desktop PC/Mac Game?
Lets assume I start a new **PC/Mac *desktop*** (not netbook) game today that will take something like one year to be released publicly and that is a lot about graphic details (not realistics, just graphically "rich").

The higher screen resolution the better but I build the game in a way that adapt to the screen (3D, screen space relative ui, etc). However I still need to have a minimal resolution to be sure my UI and texts are still clear in low resolutions.

**For the moment I'm assuming that 1024x768 is the really lower resolution any such game could ask for. But as time is going on fast I'm thinking maybe I'm wrong and a game with visual details should target higher resolutions as minimum resolution, if started today?**

Assuming Steam users would be the target audience, I looked at the Steam Hardware Survey to get an idea but it don't talk about the resolutions of games being played, only about desktop resolution. I'm assuming that most players will play most games with lower resolution than their desktop resolution...?

# Answer
> 5 votes
1024x768 (or less) is still the minimum resolution you should be targeting. Plenty of laptops sold between ~2006 and now have fully capable video cards, but are stuck to the same resolution they were sold at.

Depending on the game, it may be even less - netbooks commonly sold with a 1024x600 resolution during the same period, so a casual or web-based game may want to target that as well. People using TVs as monitors may have a display of 1280x720, and that's the resolution most console games will target. Phone platforms are just now breaking into VGA and higher resolutions.

W3 Schools has a year-by-year breakdown of resolutions for people browsing their website. 1024x768 still made up 20% of the visitors in January 2010.

# Answer
> 2 votes
Steam details: http://store.steampowered.com/hwsurvey

```
Resolution   %Users
1024 x 768   7.47%
1152 x 864   1.41%
1280 x 720   0.72%
1280 x 768   0.72%
1280 x 800   5.88%
1280 x 960   1.21%
1280 x 1024  15.13%
1360 x 768   1.34%
1366 x 768   6.27%
1440 x 900   10.14%
1600 x 900   3.63%
1600 x 1200  0.94%
1680 x 1050  18.46%
1920 x 1080  15.72%
1920 x 1200  6.71%
Other        4.26%

```

# Answer
> 1 votes
I'd say 800x600. Some netbooks have only 600 pixels tall screens (usually 1024x600), and among laptops widescreen configurations where the vertical height is absurdly limited are more and more common.

Update: oh, I see that you added the "only for desktops" requirement. Then my answer doesn't apply any more for this special case.

# Answer
> 1 votes
As the trend has been going towards 16:9 aspect-ratio, I'll probably target 1280x720 as minimum screen-size. Within a years timeframe, 800x600 should definitely be a thing of the past.

---
Tags: graphics, pc, resolution, screen, macos
---


# Question
Title: Integrating a leader board with FaceBook?
Think like how Bejeweled 2 does its Blitz mode where it connects to Facebook, pulls your friends names and their top scores for the week. Are there any libraries, etc. that already help facilitate this process? I would rather not re-invent the wheel if necessary.

# Answer
Check out the Mochi Media Scores API as a general purpose leaderboard system. If you could get the list of friend IDs from Facebook you might be able to leverage it to create one.

**DIY**

You probably already know how to do this yourself, but if you wanted to implement it, you could do something like this...

First, create a database of scores, where each row has player's Facebook ID, score and date/time of score. Every time someone plays your game, record the score along with their Facebook ID and the current date/time.

To generate a friends scores leaderboard for someone, query Facebook for a list of the person's friends, specifically their IDs. Then query your scores database for entries matching the given IDs. Generate the leaderboard you want.
> 3 votes

---
Tags: facebook, leaderboards
---


# Question
Title: Can you write games for Rock Band or Guitar Hero controllers in XNA?
Can you use the XNA framework to write games for XBox Live Arcade that require Rock Band or Guitar Hero instruments?

# Answer
> 8 votes
According to this site (http://blogs.msdn.com/b/dawate/archive/2008/02/05/building-a-3d-game-in-xna-from-scratch-free-video-tutorial-series-now-available.aspx), the Guitar Hero buttons map directly to the standard control on an Xbox 360 controller. Here's what it says (has a video and everything):

> 10). Determining What's What On The Guitar Controller The controller for Guitar Hero games maps directly to controls on a standard Xbox 360 controller, but It's not immediately obvious what exactly the whammy bar, strum bar, and orange button do. Rather than go hunt for documentation, we can find out by experimentation in less than 5 minutes.
> Download WMV (4:45, 14.5 MB)

I haven't watched it, but I have seen other games that used a Guitar Hero controller in XNA. Good luck!

# Answer
> 5 votes
The XNA documentation includes an article that lists how various alternate 360 controllers map to the gamepad buttons and triggers: Using Alternative Input Devices (Xbox 360).

Also, despite the article title, the information applies to PC as well, since those alternate controllers will still appear as the gamepad under XInput on Windows (and therefore to XNA).

# Answer
> 2 votes
The short answer is yes-ish. The controllers for the most part just send standard button inputs which is why they can be used in the dashboard. More recent stuff like the Pro Guitar for Rockband3 probably aren't accessible with XNA, but the standard controllers sure.

You should be able to use this older utility to see what maps to what on the controller

---
Tags: xna, xbox360
---


title: Managing animations

text:
# Question
Title: Managing animations
I'm developing a 2d game that requires sprite based animations. I was thinking about which is the most convenient way to manage many of these sprites all together with timings.

I already know how they should be managed by principle but I was looking for a possibly object-oriented way to manage them all. The easy part is that I shouldn't care about which specific sprite of an animation is shown related to a position or movement of the object itself, they're just static (as far as I can tell).

I'm using Java + Processing to handle the drawing.

Any suggestions?

# Answer
When I write 2d games, I tend to set it up like this:

```
class Sprite:
    has a Vector2 for position
    has a Collection (Array or Hashmap) of Viewers/Renderers (each could be a static image or an Animation that encapsulates spritesheet functionality)
    has a reference to the current Viewer/Renderer to update and draw
    has a State management system
    has whatever other properties you need (possibly bools for horizontal and vertical flipping)

```

The state management system can be a FSM pattern, or a simple enum and switch statement. Its purpose is to point the current Viewer/Renderer reference to the appropriate one from the collection based on the sprite's state

I'm not familiar with Processing, so I can't much on the details of the Viewer/Renderer interface/abstract class and the static image vs sprite sheet implementations.

Check out Brandon Furtwangler's blog, it's C# and XNA, but he shows off his really solid architecture for managing sprites. His animation system is also really cool, and although it uses lambdas, you may be able to achieve similar effects with anonymous methods in Java with only slightly more verbosity.
> 4 votes

# Answer
For each animation set a period as a number of frames, and make a mapping from the frames of that period to their respective images.

Your render function should have a counter associated, for each frame rendered increment the counter, and for each animation choose the frame to draw as counter modulus period.
> 2 votes

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


# Question
Title: Correct order of rotation and translation
Trying to get this right in openGL:

1) glRotate( cameraRotation )

2) glTranslate( -cameraPosition )

3) glRotate( objectRotation )

4) glTranslate( objectPosition )

5) Draw Object

is that right?

# Answer
You're right about having the camera applied first and then the object transform, because this allows the usage of pushing and popping matrix states between objects.

Aside from that there is no "correct" order, other than a basic assumption that the transforms will be applied in the reverse order to which you call the matrix functions.

So if for example you do:

```
glRotate(Camera_Rotation)
glTranslate(Camera_Position)
(optional push)
glTranslate(Object_Position)
glRotate(Object_Rotation)
glScale(Object_Scale)

```

The result will be that the object's vertices will first be scaled (along the local XYZ axes), then rotated (around the local origin), and then translated into "world" space. Then the world-space co-ordinates will be translated such that the camera is at the origin, and finally everything will be rotated around to the correct view direction. This is probably what you want for a basic scene.

As Richard Fabian says, you generally want to consider the camera transforms as an inverse, though you might equally replace the camera transforms with a lookAt() function or similar, to directly construct an appropriate view matrix.

If you push the matrix stack after setting up the camera, you can pop/push for each object without having to set the camera up again.
> 2 votes

# Answer
It would help if this had some proper context to it. But the general rule of thumb as far as I am aware is this:

* Scale
* Rotate
* Translate
> 1 votes

# Answer
Because a camera is usually the inverse (because the position and rotation of the camera are applied inverse to the scene to bring the scene into the camera's space) the order of the transforms is a little odd.

it's more like:

```
// fixed
glRotate( -cameraR );
glTranslate( -cameraP );
glTranslate( objectP ),
glRotate( objectR ),

```

EDIT: Doh, Jason is right. I'm going to blame it on not doing OpenGl in a while ;) OpenGl does indeed apply your transforms in reverse order so my original post was the opposite of correct ;) Another thing to consider is, not many people I know actually use these gl functions. Most people use a full math library once they've got started, mostly because without that you're going to be quite stuck when it comes to more advanced animations and camera paths. Also, as Jason mentions, a look-at matrix is a fundamentally more accurate description of a camera transform, so you should probably look into using matrices rather than these base functions.
> 1 votes

---
Tags: 3d, opengl, c
---


title: Creating Level iPhone

text:
# Question
Title: Creating Level iPhone
I am thinking about a new game idea for the iPhone and presumably all the levels would have to be made programatically. So Im wondering what the best method to approach it?

Say I have a game with a standard typical 2d, top down maze. Thise maze is simply made up of walls, multiple rectangles on screen, making paths.

Do I have to manually work out the position of every rectangle and put it in with an x and y position or is there a better way? I see this taking, forever, there must be certain ways developers approach these situations to get by them efficiently and quickly surely?

Thanks.

# Answer
Are you saying you want to *generate* the levels, or do you want to create them "by hand" in code (world.addRectangle(10,10,100,20)etc)? If you want to generate the levels procedurally, look inte algorithms for maze construction and adapt them to your needs.

If you want to construct the levels yourself, you can place the data in a separate file and parse it. Can be as simple as rectangles in a csv file, or xml. (Or svg, in which case it would be a small step to creating the levels in a program like Inkscape. But then you'd need to use or write an svg parser.)

Some languages (Lua for example) make it really simple to read data from files and turn them into data structures. Since you're writing a game for the iPhone, you can play with creating your levels using a plist. You can read them into a data object with one method invocation.
> 2 votes

# Answer
I'm confused as to your use of 'programatically'. Do you mean procedurally, that is generate-as-you-go, or in the code, hardcoded? I'm pretty sure you don't need that in iPhone games - how would they have the images?

So instead of having to hardcode the coordinates, you want to save the effort and use an editor. A question on 2D level editors.

I would use a level editor, or just put it in a data file. Literally something like:

```
01001110
01101010
00001001

```

It would be quicker than the rectangles definitely, but not as good as a level editor - which would be simple to make or use an existing one, and would generate similar output.

What I'm suggesting is to stop thinking about rectangles and start thinking about **walkable** and **unwalkable** tiles. Your walls would obviously be unwalkable, and the floor walkable. You would have a graphic (or just a black square drawn) where a wall is, and you would use those tile coordinates as the collision boundary. Lots of tiles = a wall.

Even if you do mean procedurally - which is not a limitation of the iPhone platform - the above would still work, just without the files. Google anything about maze generation or roguelike maps.
> 2 votes

# Answer
For such a job I figure you'll get away with drawing the maze using a paint program and have a piece of code turning the image into a what data you need. Of course, if you just need a maze you could just write a maze generator, with the added benefit of being able to make random mazes on the fly. There is some interesting talk on the subject here: Reduce the number of edges of a graph, keeping it connected
> 1 votes

---
Tags: game-design, iphone, design-patterns, level-design
---


# Question
Title: What is the best way to render eletric wires (like in gta 4)?
From the top of my mind, I see 2 ways to do it :

* classic mesh. (but that's likely to be a lot of tris for little screenspace)
* bilboards (but the placements of the billboards may be tricky. still looks like the best solution)
* a box with a shader (the parametric shape would be in the shader, seems tricky).

Any idea ?

refs : Screenshot1 Screenshot2

# Answer
> 1 votes
I'd consider doing it as two flat lines, set at ninety degree angles, such that the cross-section of the wire was literally a cross. If you wanted to be a little cleverer, you'd do the billboard thing, such that you had one flat line always directly facing the player.

Meshes and shaders seem overkill.

(Well, okay, the billboard thing might use a vertex shader. But seriously, just do two flat lines unless that's actually causing problems.)

---
Tags: rendering, shaders, 3d-meshes
---


title: BoundingFrustum Performance Issues

text:
# Question
Title: BoundingFrustum Performance Issues
I have noticed that BoundingFrustum.Intersects() is a rather slow check in XNA. I am doing only 256 checks per frame and it eats up arround 50-60% of availible time when running at 60fps. This is kind of crazy. I would like to know if anyone else has experienced these types of performance problems with the BoundingFrustum class in XNA? Does anyone suggest I make my own boundingfrustum class/struct?

(One pitfall, when using the BoundingFrustum class, is declaring a new instance of it every frame... for some reason it is a class and not a struct. I am not doing this.)

# Answer
It seemed a little strange to me so I made a little app to test how much time it took. It appears that the time the intersects method takes varies by where the axis aligned bounding boxes are positioned. This makes sense because more checks are needed in some cases to verify that an intersection is not occurring.

I imagine you are running this code on the Xbox 360 since you have a large performance impact. Using Reflector it is easy to see that the method was not coded with speed in mind. The function is riddled with floating point operations and function calls. The compact .Net framework does not inline any function calls and combined with the horrible floating point performance I can see why so much time is used up by the intersects function.

I did some research and came across this article: http://zach.in.tu-clausthal.de/teaching/cg\_literatur/lighthouse3d\_view\_frustum\_culling/index.html

There are various faster methods for frustum culling you could implement to speed things up. Here is a reasonably accurate intersects implementation which is about 7 to 10 times faster. *(note: it does give a few false positives, see the "Geometric Approach - Testing Boxes" section of the article above)*

```
public static class FrustumHelper
{
        public static Vector3 GetNegativeVertex(this BoundingBox aabb,
                                                ref Vector3 normal)
        {
            Vector3 p = aabb.Max;
            if (normal.X >= 0)
                p.X = aabb.Min.X;
            if (normal.Y >= 0)
                p.Y = aabb.Min.Y;
            if (normal.Z >= 0)
                p.Z = aabb.Min.Z;

            return p;
        }

        public static void FastIntersects(this BoundingFrustum boundingfrustum,
                                          ref BoundingBox aabb,
                                          out bool intersects)
        {
            intersects = false;

            Plane plane; Vector3 normal, p;

            plane = boundingfrustum.Bottom;
            normal = plane.Normal;
            normal.X = -normal.X;
            normal.Y = -normal.Y;
            normal.Z = -normal.Z;
            p = aabb.GetPositiveVertex(ref normal);
            if (-plane.D + normal.X * p.X + normal.Y * p.Y + normal.Z * p.Z < 0)
                return;

            plane = boundingfrustum.Far;
            normal = plane.Normal;
            normal.X = -normal.X;
            normal.Y = -normal.Y;
            normal.Z = -normal.Z;
            p = aabb.GetPositiveVertex(ref normal);
            if (-plane.D + normal.X * p.X + normal.Y * p.Y + normal.Z * p.Z < 0)
                return;

            plane = boundingfrustum.Left;
            normal = plane.Normal;
            normal.X = -normal.X;
            normal.Y = -normal.Y;
            normal.Z = -normal.Z;
            p = aabb.GetPositiveVertex(ref normal);
            if (-plane.D + normal.X * p.X + normal.Y * p.Y + normal.Z * p.Z < 0)
                return;

            plane = boundingfrustum.Near;
            normal = plane.Normal;
            normal.X = -normal.X;
            normal.Y = -normal.Y;
            normal.Z = -normal.Z;
            p = aabb.GetPositiveVertex(ref normal);
            if (-plane.D + normal.X * p.X + normal.Y * p.Y + normal.Z * p.Z < 0)
                return;

            plane = boundingfrustum.Right;
            normal = plane.Normal;
            normal.X = -normal.X;
            normal.Y = -normal.Y;
            normal.Z = -normal.Z;
            p = aabb.GetPositiveVertex(ref normal);
            if (-plane.D + normal.X * p.X + normal.Y * p.Y + normal.Z * p.Z < 0)
                return;

            plane = boundingfrustum.Top;
            normal = plane.Normal;
            normal.X = -normal.X;
            normal.Y = -normal.Y;
            normal.Z = -normal.Z;
            p = aabb.GetPositiveVertex(ref normal);
            if (-plane.D + normal.X * p.X + normal.Y * p.Y + normal.Z * p.Z < 0)
                return;

            intersects = true;
        }
}

```
> 3 votes

---
Tags: xna, collision-detection, scene-graph, culling
---


title: Colour Problems When Using SDL_Resize()

text:
# Question
Title: Colour Problems When Using SDL_Resize()
In a 3D SDL application I inherited (I have little 3D or SDL experience), I have a 'screenshot' routine that either saves a full-size image or a scaled image, depending on the context (differing key-press). To save a full-size (i.e. graphics-mode-sized) screenshot I'm using:

```
SDL_SaveBMP(SDL_GetVideoSurface(), SDL_RWFromFile(filename.c_str(), "wb"), 1);

```

This works exactly as-intended, and saves an 8-bit bitmap (the display mode is *always* 8-bit, for another reason entirely) as expected.

However, in order to resize the image, I'm making use of a library that came heavily recommended in several places when searching for a suitable surface-/image-resizing library for SDL: SDL\_Resize.

I'm implementing this as such:

```
SDL_Surface *toResize = SDL_GetVideoSurface();
SDL_Surface *resized = SDL_Resize(toResize, (int)w, (int)h);

SDL_SaveBMP(resized, SDL_RWFromFile(filename.c_str(), "wb"), 1);
SDL_FreeSurface(resized);

```

This works *mostly* as intended. It saves a resized, 8-bit bitmap, seemingly with the correct palette. However, the colours in parts of the image are incorrect, e.g.

Now, I don't need the output images to be 8-bit, I'd be perfectly happy with a 24-bit or 32-bit bitmap, if I could solve this problem; but I can't find out the answer to either of these questions:

* **How do I convert an SDL surface to a different bit-depth?**
* **How do I ensure that the output image displays the colours correctly after resize?**

I'm anticipating that I may have to settle for a higher-bit-depth bitmap, and that's fine... but a few pointers in the right direction would be fantastic.

Many thanks!

# Answer
> 1 votes
To "convert" an SDL surface to another bit-depth, use SDL\_ConvertSurface. This function is slightly mis-named, as it actually makes a new surface rather than converting the surface in-place (which isn't really possible).

I don't know how SDL\_Resize works, but the problems you are seeing can be caused by it using a 24/32 bit buffer internally when rescaling and performing bilinear filtering. This results in colors in the scaled image which are not present in the original, which must then be mapping back to the palette, apparently poorly.

It also looks bad enough that SDL\_Resize may also only support one palette, forcing your image into that color space before working with it. But even if it kept the original palette, the accuracy would be questionable.

---
Tags: image, sdl
---


# Question
Title: Loading and drawing materials using Lib3ds
Hey all, i'm currently using Lib3ds to load models into my C++/OpenGL project. So far, i've been follow the model loading tutorial found *here*.

The tutorial gives a good example of how to draw the vertices and normals using VBO's, but so far i've been lost as how to do the same thing with materials.

Could i get an explanation/example of how to both **load** and **draw** materials of my meshes using Lib3ds and OpenGL?

# Answer
> 2 votes
Explanation: every mesh face has a material, basically you need to load each material and during rendering:

```
for each mesh do
   for each face do
      setup face material
      draw face
   end
end

```

But this will be inefficient and the ideal would be to group faces by material. You can after load process the mesh and group the faces with the same material, then you can draw each face batch at once for each material.

---
Tags: opengl, 3d-meshes
---


title: Rotate vector by matrix?

text:
# Question
Title: Rotate vector by matrix?
If I have a Vector, say (1,1), how can I rotate it around the origin (0,0)?

I'm working in XNA if that helps.

# Answer
Just multiply the vector by a rotation matrix:

```
| fx |     | cos a    -sin a | | sx |
| fy |  =  | sin a     cos a | | sy |

```

where `fx` and `fy` are final coordinates of the object after the rotation and `sx`, `sy` are starting one. Obviously `a` is the angle involved.
> 10 votes

# Answer
Since you are using XNA, there is an easy way to do the above, which can be found in this following thread. In shows how to perform the transformation in 3D or 2D. For 2D, it is as simple as:

```
point = Vector2.Transform(point, Matrix.CreateRotationZ(AngleToRotate);
point += originPoint;

```

Note that AngleToRotate is in radians. If you want to use Degrees you can can take advantage of

```
MathHelper.ToRadians(float degree)

```

which is a static method.
> 13 votes

---
Tags: xna, graphics, mathematics, vector, windows-phone-7
---


# Question
Title: Techniques for mapping "nodes" and paths between nodes in a world space that extends in three dimensions
I'm trying to create a travellable map/world. I want to model able-to-be-occupied nodes/tiles/locations and allowed paths between them to create a space infinitely able to be built upon in all directions (not just flatland), in a browser-based game ( http://ninjawars.net , for a sense of it).

For example your character will be in a node "a field", and could then move north into "the first floor of a shack", or south or east or west. After moving north, movement choices would then be: south back to the field, or up to the second floor of the shack.

Basically, a grid maze with the minor complexity of the up and down option.

What are useful methods for modeling both the inhabitable nodes and the paths between them? X,y,z euclidean coordinates and relational lists of available connections from individual nodes?

Or are there alternatives to grids that could still allow fun visual representation of movement options?

# Answer
Each node could have a 3d index and 8bit flag where you use 6 of those bits to determine if a direction is walkable or not.

```
Example node:

XYZ(choose data-type depending on your map size requirements)
128,129,523

UDEWNS(up,down,east,west,north,south)
100001

```

Would mean you can walk up and south from zone 128,129,523.

When you walk one of the directions increment/decrement the appropriate dimension. Walking up from the example zone would bring you to 128,129,524

Hope this helps.
> 1 votes

# Answer
If your map is not extremely dense, you would be best off defining it with a list of nodes rather than an actual array or grid. Create a list of nodes, where each node has a set of links to what node you will go to if you travel N, S, E, W, U or D. This is how MUDs typically work I believe. Also text-based adventure games.

Here is a bit of pseudo code to define a field node, and a shack and the shack's second floor...

```
// --- Define field node
node[1].name = "field";
node[1].description = "You are standing in a farmers field.";
node[1].up_to = 0;
node[1].down_to = 0;
node[1].north_to = 2;
node[1].south_to = 0;
node[1].west_to = 0;
node[1].east_to = 0;

// --- Define shack first floor node
node[2].name = "shack";
node[2].description = "You are on the first floor of a shack.";
node[2].up_to = 3;
node[2].down_to = 0;
node[2].north_to = 0;
node[2].south_to = 1;
node[2].west_to = 0;
node[2].east_to = 0;

// --- Define shack second floor node
node[3].name = "second floor";
node[3].description = "You are on the third floor of a shack.";
node[3].up_to = 0;
node[3].down_to = 2;
node[3].north_to = 0;
node[3].south_to = 0;
node[3].west_to = 0;
node[3].east_to = 0;

```

The "\_to" values represent the ID of the node you'll go to if you travel in that direction. If the "\_to" value is zero, that means there is no path that direction. With this kind of system, you can see how the player can go north and be on the first floor of the shack. And from the first floor they can go south back to the field, or up to the second floor.

When you program a system like this, it is very easy to use the path information to dynamically give the player information on where they are. For example suppose that the current node they are in is set in the variable "current\_node". You can then check each of the 6 directions and print out possible travel information to the player like this...

```
north_to = node[current_node].north_to;
if (north_to != 0) {
   print "A path leads north to " + node[north_to].name;
}

south_to = node[current_node].south_to;
if (south_to != 0) {
   print "A path leads south to " + node[south_to].name;
}

east_to = node[current_node].east_to;
if (east_to != 0) {
   print "A path leads east to " + node[east_to].name;
}

west_to = node[current_node].west_to;
if (west_to != 0) {
   print "A path leads west to " + node[west_to].name;
}

up_to = node[current_node].up_to;
if (up_to != 0) {
   print "A path leads up to " + node[up_to].name;
}

down_to = node[current_node].down_to;
if (down_to != 0) {
   print "A path leads down to " + node[down_to].name;
}

```

One thing a system like this lets you do is concentrate detail where you need it, and avoid it where you don't need it. You could let the player cross a mountain pass and enter a shrine in only a few steps, with a set of nodes linked like this...

WEST SIDE OF MOUNTAINS \<--\> MOUNTAIN PASS \<--\> EAST SIDE OF MOUNTAINS \<--\> SHRINE

If you tried to to that on a map of evenly sized tiles, it would take a large number of tiles to simulate the distance across the mountain pass.

Another advantage of a map like this is that it's very expandable. Suppose I want to put a basement in the shack in the pseudo code example above. I just need to add a new node for the basement, and change the "down\_to" link on the shack's first floor to point to the basement.

If you'd really like to have some graphics with the game, you could associate a picture with each node, and the picture is shown to the player when they visit that node. These nodes could even be places where players click, walk around, explore, etc. This is about how Club Penguin manages rooms, and also many click adventure games like "Ben There, Dan That".

Of course this approach does not work with a tiled map or one where you want to let the player go any place they'd like to go.
> 3 votes

# Answer
If you want a scalable solution use a graph data structure (Wikipedia Link)

With a graph you can associate each region with a node on the graph. Each node contains the neighbours of that node in the graph (the nodes that are connected to it).

You also have a lot of increased flexibility with a graph, for example:

1. A region had a north, west and east exit (no south) - You wouldn't have to worry about setting the south exit to NULL or whatever, you just wouldn't add that node to the neighbours list
2. Say you wanted to go from a town to a dungeon, but you couldn't go back the same way because for some reason the exit was closed off by demons, this is where Directional Graphs come in. You could have a neighbour called Dungeon in Town's neighbours list, but don't add a Town neighbour to the Dungeon node (meaning that you can go from Town-\>Dungeon, but Dungeon-\>Town is impossible)
3. If you wanted a fancy effect of hopping from region to region, you could easily implement some pathfinding like A\* to figure out the shortest path for you.

You *could* go with a connectivity matrix, but as you say you wanted something in 3-dimensions, so this would essentially be a 3-dimensional array which would get VERY big VERY fast.

If you want a solution that you can easily add nodes to (for example, when expanding on your game) then I'd definitely recommend using a graph.
> 2 votes

# Answer
Depending on how you decide to implement this, you could (1) simply build a graph of visitable nodes using pointers or references or (2) if your language supports it, you could use proper tail calls; Programming in Lua has a good example of this directly related to game development.
> 1 votes

---
Tags: maps, world-design, browser-based-games
---


title: iPhone Game - Sprites

text:
# Question
Title: iPhone Game - Sprites
I have made games with cocos2d for the iphone however I am looking to move on from that, is there a good direction you could suggest? If not I was planning on using what the SDK gives me, and so for example to make a sprite, say the player on screen, rather than a CCSprite, what would be best to use? What do I need to go and learn?

Thanks.

# Answer
cocos2d is using OpenGL ES as its rendering engine, so if you wish to move on, OpenGL ES is the next step.
> 3 votes

---
Tags: game-design, iphone, sprites
---


title: UDK iOS: System Requirements confusion

text:
# Question
Title: UDK iOS: System Requirements confusion
Unreal Development Kit for iOS was recently released. The system requirements note that Windows is needed. Does this mean that iOS game development is possible on a PC now?

I am confused since I thought iOS development required an OSX machine.

Thanks in advance.

# Answer
> 4 votes
As Tim Holt mentioned you will need a PC to run the Unreal Editor to create your content. It also allows you to test your game in an emulator or transfer the content to your iPhone. BUT, to submit your application you will need a Mac.

The following documentation page explains all this.

Also don't forget that you will need to be a registered iOS developer - meaning pay the $99/year to be able to even test application on your iPhone. This process for Provisioning is explained in the following two documentation pages:

# Answer
> 1 votes
You need Windows to run the Unreal Editor to create content. Build the game on Windows, export to iOS.

---
Tags: iphone, unreal
---


# Question
Title: Is there an approach in creating an AI Framework?
I am creating a board game using Actionscript 3.0. I've finished it to the point of the game playable with (computer players making random decision). I'm now working to create an AI framework/module ( Designing and creating classes that will be used to drive the AI). Is there a commonly/popular approach on creating an AI framework)? I've searhed around abit and could only find algorithms and sample codes. What I'm not looking for game/code specifics but more to thinking process in designing and modeling the AI.

# Answer
The AI broadly depends of what is it supposed to do. What I mean is that so many kinds of AI exist that it is impossible to just cover them all.

For your specific purpose of a board game (or at least, a perfect information game) you usually use minmax trees and all the possible optimizations starting from there. (eg AB-pruning).

These algorithm can easily be developed as a framework since what you really need are basically 2 functions:

* a function `(game state, player) -> game state list`, which computes all the possible moves from a specific state of the game for a player
* a function `(game state, player) -> float` which is the kernel of the algorithm. This function is used to evaluate how good is a state for a specific player. This is the heuristic involved, and it is what you will tweak of the whole algorithm to make your AI more cleaver.

One you build the main algorithm (which goes recursively over a tree) you could easily adapt it to whatever board game you like by modifying just the two functions described above.
> 5 votes

# Answer
Behavior trees have been growing in popularity lately as a way to partially decouple game logic from AI flow. You will probably want to find a library that implements the basic elements though, it is annoying to write from scratch.
> 3 votes

# Answer
I don't think there's a generic approach because AI is not so much a component or a system as a broad classification of algorithms, many of which do entirely different things. There is no standard interface that could be applied to them all, nor a standard representation that could be used across them.

You need to decide exactly which parts of your program require an AI approach (eg. picking a move to make), then select an algorithm that facilitates that (eg. minimax).
> 0 votes

---
Tags: software-engineering, ai, actionscript-3, game-mechanics, procedural-generation
---


# Question
Title: How to do pixel per pixel modeling in unity3d?
So generally I want to have api like `pixels.addPixel3D(new Pixel3D(0xFF0000, 100, 100,100));` (color, position) where pixels is some abstraction on 3d sceen objet.So to say point cloud. It would have grate use in deep space/stars modeling... I want to set each pixel by hand (having no image base or any automatic thing)... So point is modeling something like

Or look at alive flash analog here

How to do such thing in unity?

# Answer
As Joe pointed out, unity is not the right tool for this. I would suggest something as simple as glut if you do not require other features that unity offers. What you want to do is render all the desired pixels as particles off-screen, that is, on the GPU: High-Speed Off-Screen Particles.

Your particles will most likely be in a 3D grid. A large 3D grid is a problem (for example 256\*256\*256) as there are too many grid cells that you have to process, in which case you would want to design your own spatial graph, for example an Octree, to process only the cells that contain particles. For simpler patterns and not too many particles, you can get away with sequential grids.
> 3 votes

# Answer
Unless you really want to render out little cubes for each pixel, you'd probably want to do this with sprites.
> 1 votes

# Answer
You could use C# or javascript to generate the desired image as a heightmap, then place those on a bunch of planes. You could also look at the heightmap generator in the procedural generation demo, Unity has in there projects, for how to place the "Pixels"/planes at the desired height or distance from the camera.

This isn't any different than Tim's answer really, it just uses planes instead of cubes. Either way you will most likely have an object/instance for each "pixel" anyway.

Also If you are going for the look above you will probably need to have a sprite manager that converts the jpeg into the associated grouping of cubes/planes, that way you don't have to do anything special for the assets.
> 1 votes

---
Tags: unity
---


# Question
Title: What are the minimum requirements for UDK on iOS?
Infinity Blade asks for 3GS or better devices, which I'm told is because it uses OpenGL ES 2.

Will every game made with the iOS version of the UDK only work with 3GS devices and up?

# Answer
> 1 votes
UDK for iOS requires OpenGL ES 2.0, which is not available on the PowerVR MBX GPU featured on the devices prior to the iPhone 3GS. In other words, valid targets for the iOS UDK are:

* iPhone 3GS
* iPhone 4
* iPod Touch 3rd gen
* iPod Touch 4th gen
* iPad

# Answer
> 0 votes
You need a device that supports OGLES2, so yes.

---
Tags: iphone, hardware, udk
---


# Question
Title: Javascript injection problems to beat my game! HELP
So I have a web application game that runs completely on the client side and just returns the score back to the server to list the highest scorer. Now I have noticed that I can easily manipulate the scores via accessing the variables from the console and injecting my own value! This SUCKS! I am a total noob in this kinda development and have absolutely no clue how I can stop this apart from obfuscating the code and praying to god that the hacker doesn't figure out which variable is he supposed to use! Now I was hoping there are better ways to stop the hacker to gain access of my variables. Could someone help me out with this issue!?

# Answer
> 4 votes
Google for "javascript obfuscation". This will muddy your code up for when you deploy it. It will change your identifiers to more cryptic things so people will not be able to deduce what the score variable is called unless they monitor all the variables while running the game. Javascript's at a disadvantage since the code is directly readable by the user. Technically people can decompile Flash and read the bytecodes, but that's more work in general.

The real problem lies in when you submit the score to the server. Assume the client side can not be trusted at all regardless of the technology you used to create the game. Eventually data needs to come out of the game in the form of an HTTP request that can be easily viewed and modified. Look at this StackOverflow question. When people submit scores, you need to be smart about accepting and validating them.

Don't worry about this stuff until your game is robust and popular enough to warrant the concern. You'll need to analyze the relationships between player and game events and theoretically possible scores in order to make an effective anti-cheat system.

---
Tags: game-design, javascript, console
---