title: Adding a short delay between bullets

text:
# Question
Title: Adding a short delay between bullets
I'm having some trouble simulating bullets in my 2D shooter. I want similar mechanics to Megaman, where the user can hold down the shoot button and a continues stream of bullets are fired but with a slight delay. Currently, when the user fires a bullet in my game a get an almost laser like effect. Below is a screen shot of some bullets being fired while running and jumping.

In my update method I have the following:

```
if(gc.getInput().isKeyDown(Input.KEY_SPACE) ){
    bullets.add(new Bullet(player.getPos().getX() + 30,player.getPos().getY() +  17));
}

```

Then I simply iterate through the array list increasing its x value on each update.

Moreover, pressing the shoot button (Space bar) creates multiple bullets instead of just creating one even though I am adding only one new bullet to my array list. What would be the best way to solve this problem?

# Answer
You can add a little timer:

```
if(gc.getInput().isKeyDown(Input.KEY_SPACE) &&
 gameTime.getTimeMS() - shootTime > shootDelayInMilliseconds) {
   shootTime = gameTime.getTimeMS();
   bullets.add(new Bullet(player.getPos().getX() + 30,player.getPos().getY() +  17));
}

```

Basically you are noting the last time your character shot, then ensuring that enough time has passed before shooting again.

As for adding multiple bullets to the array list, it's doing this because you likely can't press the space bar fast enough to only have the space bar pressed for one frame. Each update you're adding one bullet. Add the delay like above will likely solve that problem. If you want to have a longer delay before you start repeating shots, you can doing something like:

```
if(gc.getInput().isKeyDown(Input.KEY_SPACE) && !previousInput.isKeyDown(Input.KEY_SPACE)) {
   startShootTime = gameTime.getTimeMS();
}
if(gc.getInput().isKeyDown(Input.KEY_SPACE) &&
 gameTime.getTimeMS() - shootTime > shootDelayInMilliseconds &&
 gameTime.getTimeMS() - startShootTime > initalShootDelayInMilliseconds ) {
   shootTime = gameTime.getTimeMS();
   bullets.add(new Bullet(player.getPos().getX() + 30,player.getPos().getY() +  17));
}

```

Where `initalShootDelayInMilliseconds` is the time before holding the space bar causes repeated shots and `shootDelayInMilliseconds` is the time between each repeated shot thereafter. This is similar to the keyboard input for many text editors, holding a key for a certain amount of time will cause that key to repeat at a (often shorter) delay rate.
> 4 votes

# Answer
In Java this is the code if you use ArrayList..

```
public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode(); ///get the key code of key pressed

    if (keyCode == KeyEvent.VK_SPACE) {
    if (!fireballs_array.isEmpty()) {  /// check if the array list is empty or not
        int last = fireballs_array.size()-1;  // get the last element index
        if(fireballs_array.get(last).getY() <550) //get y axis of last element
        {
            fire();
        }
    }
    else {
        fire();
    }
}

```
> -1 votes

---
Tags: java, slick
---


# Question
Title: Why does my model render differently than its preview?
I've been importing .fbx files that I made with 3DS Max 2012 into Unity, and it's quite neat to see my models running around in game. However, I can't help but notice that the models, as they're rendered in game, vary substantially from what they look like in the preview (and also what they looked like in 3DS Max).

Observe:

```
           In-Game                   Unity Preview            3DS Max

```

My gut tells me that I'm not setting up Unity's lighting system properly. What, then, do I need to do, to either my scene or my model, in order to get the left-most picture to look like the middle one?

# Answer
It looks to me like lighting is your problem.

According to this the default lighting in 3DS Max is essentially a headlamp (a directional light coming from the viewport), so the faces pointing towards you will appear the brightest.

Your Unity preview has a directional light shining towards the bottom right (I could have said "located in the top left", but remember, a directional light has no position).

As for your Unity scene, it doesn't look like you have lighting at all, hence the flat-shaded look of your model. To solve that, I would start with some simple things and ask: do you have any lights in your scene (point, directional, or spot)?

Update: According to your comment, you only have the default ambient light enabled in your scene. Note that ambient light is not the same as diffuse light. Ambient light, in typical lighting models, is a shortcut that accounts for light bouncing off of other surfaces. I won't go into much more detail, so I'll refer you here for more information. Note in that link that the version of the blob lit by ambient light looks flat-shaded, exactly like your model in Unity.

The solution to your problem is pretty straightforward then: add a point, direction, or spot-light to the scene. Your model will then look more like it does in the Unity preview.
> 3 votes

# Answer
I know it might sound weird, but it looks to me that you set your Camera Projection to Orthographic instead of Perspective. This is how I would explain the flatness. I also believe that you simply imported the 3Ds Max light with your character face. You should try to remove this light and render the object without it. If it doesn't look good enough, I will advise you to use a spotlight in Unity instead.

I hope that helps.
> 1 votes

---
Tags: unity, lighting, fbx
---


# Question
Title: which platform to choose for designing a game
I am new to gaming platform and don't have any experience in gaming as well. I want to develop a small shooting game and don't have any idea from where to start and which platform to use like things. I have some experience in java and .net. Can anyone help me in giving me a start? I don't mind even if this question is voted down or closed. But please do help me. I've tried searching other similar questions but everyone is already into gaming and i can't get any of the words. Please refer me to some books or tutorials

# Answer
> 1 votes
I would suggest you take a look at XNA or Unity. XNA is perfect if you have some c# knowledge, its free and there are plenty of resources out there.

I'dont have any experience with Unity so I cannot describe pro's and con's and major differences between them, but I found XNA to be pretty complete and easy to begin with.

---
Tags: game-design, software-engineering
---


# Question
Title: Is it safe to run multiple XNA ContentManager instances on multiple threads?
My XNA project currently uses one ContentManager instance, and one dedicated background thread for loading all content.

I wonder, **would it be safe to have multiple ContentManager instances, each in it's own dedicated thread, loading different content at the same time?**

I'm prompted to ask this question because this article makes the following statement:

> If there are two textures created at the same time on different threads, they will clobber the other and you will end up with some garbage in the textures.

I think that what the author is saying here, is that if I access one ContentManager simultaneously on two threads, I'll get garbage. But what if I have separate ContentManager instances for each thread?

If no-one knows the answer already from experience, I'll go ahead and try it and see what happens.

# Answer
> 4 votes
It should be fine. See: http://xboxforums.create.msdn.com/forums/t/18034.aspx .

I disagree with the comment - "*If no-one knows the answer already from experience, I'll go ahead and try it and see what happens.* should be done before asking this question." - as regards this particular question since threading problems are often hard to tease out so it's, to me at least, better to ask since you might test, find nothing, go live, and have a lot of crash reports start coming in because of some small architectural difference on a particular chipset that exposes a race condition your testing on other chipsets missed.

# Answer
> 0 votes
I'm using the a content tracker library (originally on CodePlex, but now available here) to load content in background with no problems.

It lets you unload individual assets, force file read (for editors), know the relationship among assets... it's worth it.

---
Tags: xna, multithreading
---


title: Where to implement storable items

text:
# Question
Title: Where to implement storable items
I'm creating a multiplayer online trading game. The things that are traded range from raw items to complex products. For example `Steel` is a raw item. `Mechanical Assembly` is a more complex item that requires `2x Steel` and maybe `1x Rubber`. Then `Hydraulics` is an item that contains `2x Mechanical Assemblies` and `1x Electronics` (which is another complex item). So and so forth.

These items will be created by me, players can't create their own items, so it doesn't need to be able to handle arbitrary layers of complexity for items.

If my example isn't clear, think Minecraft. You have wooden planks, which can be made into sticks. From there the sticks - combined with metals - can be made into tools. My game is nothing to do with minecraft or any sandbox building game, but it uses a similar progressive complexity to creating items that I want to have in my game.

My question is basically, how do you store something like this assuming that I will want to add more items in the future? Do you store it in a database or in a seperate library that the game uses?

**EDIT**

None of the items actually "do" anything, they are simply there to either sell, purchase, or combine with other items to make a more complex item, which can then be sold, purchased or combined... you get the idea. The items themselves would not have any properties, but the instances of the items would. For example an item that one player has would have a certain "quality" and if they were selling it a certain "price". An instance of that same item that a different player had would need to have a different "quality" and "price" if they were selling it.

I think the price part will not be required on an individual item because instead I would have a "sale" object which was for a price and contained certain items.

# Answer
> 2 votes
If it's going to be an online game with constant communication between the server and the client, then relational database on the server side is the way to go. In SQL, for example, you can have the following tables:

```
TRADEGOODS (id, name) //examples: (3, "Steel"), (4, "Wood")
PROPERTY (id, name)  //examples: (2, "Sell price"), (3, "Buy price")
TRADEGOODS_PROPERTY (tradegoods_id, property_id, value)
//example: (3, 2, 5000)   This would mean that the sell price for steel is 5000 credits.

```

Then you could have a table representing the inventory of the player:

```
INVENTORY(player_id, tradegoods_id, amount)

```

A simple transaction would be, if the player with the id 5 sells 10 steel to the shop, to reduce the 'amount' value by 10 where the 'tradegoods\_id' is 3 (steel) and the 'player\_id' is 5. Of course you have to check if this is a valid transaction... But I think you get the idea.

Edit: Important to note that your clients should NEVER access directly the SQL database. They only communicate with the server application, which will access the database when necessary.

# Answer
> 0 votes
I think a big question you need to ask yourself is, what information actually needs to be stored? (And your question is a little vague as well)

If it's just a list of recipes (i.e., A + A + B = C), you could probably store it in something as simple as an XML document, which could then be saved locally to whatever's running the server and deserialized when needed. Simply assign each item an ID number (an int or enum should be fine) and serailize both the list of component IDs, and the id of the resultant product.

Using XML lets you make changes to recipes without having to recompile, or give each player a new build, which is a definite plus in a multiplayer game, I think.

---
Tags: architecture, storage
---


# Question
Title: Passing elapsed time to the update function from the game loop
I want to pass the time elapsed to the `update()` method as this would make easy to implement the animations and time related concepts.

Here's my game-loop.

```
public void gameLoop(){
    boolean running = true;

    long gameTime = getCurrentTime();

    long elapsedTime = 0;
    long lastUpdateTime = 0;

    int loops;

    while (running){

        loops = 0;

        while(getCurrentTime()>gameTime && loops<Global.MAX_FRAMESKIP){
            elapsedTime = getCurrentTime() - lastUpdateTime;
            lastUpdateTime = getCurrentTime();

            update(elapsedTime);

            gameTime += SKIP_STEPS;
            loops++;
        }

        displayGame();
    }
}

```

getCurrentTime() method

```
public long getCurrentTime(){
    return (System.nanoTime()/1000000);
}

```

update() method

```
long time = 0;

public void update(long elapsedTime){
    time += elapsedTime;
    if (time>=1000){
        System.out.println("A second elapsed");
        time -= 1000;
    }
}

```

But this is printing the message for 3 seconds.

Thanks.

# Answer
> 4 votes
First, you should avoid calling getCurrentTime() multiple times per loop. You will potentially be getting different values at different times. Call it once at the start of the loop and use that value as the current time for the rest of the loop. Also, you are advancing gameTime by a fixed amount each time rather than the length of the frame, you are sort of mixing a fixed step and variable length frame concept here. To have variable length frames, you probably want something more like:

```
long elapsedTime = 0;
long lastUpdateTime = getCurrentTime();
long gameTime = 0;

while (running){
    gameTime = getCurrentTime();
    elapsedTime = lastUpdateTime - gameTime;

    // This is where you can apply a minimum frame time if you want, at the
    // very least, you should make sure elapsedTime > 0, since
    // you don't want to run 0 length frames
    if (elapsedTime < Global.MIN_FRAME_LENGTH)
        continue;

    update(elapsedTime);

    displayGame();

    lastUpdateTime = gameTime;
}

```

That inner loop is only necessary if you want to have a *maximum* frame time, in which case you could do something like:

```
long gameTime = getCurrentTime();

long elapsedTime = 0;
long lastUpdateTime = getCurrentTime();
long currentTime = lastUpdateTime;
long frameTime = 0;

while (running){

    currentTime = getCurrentTime();
    elapsedTime = lastUpdateTime - currentTime;

    if (elapsedTime < Global.MIN_FRAME_LENGTH)
        continue;

    while (elapsedTime > 0) {
        frameTime = elapsedTime;
        if (frameTime > Global.MAX_FRAME_LENGTH)
            frameTime = Global.MAX_FRAME_LENGTH;

        update(frameTime);
        elapsedTime -= frameTime;
    }

    displayGame();

    lastUpdateTime = currentTime;
}

```

---
Tags: game-loop, timing
---


# Question
Title: Are there tools for testing multiplayer code?
Are there reliable tools that can simulate real life-like network conditions e.g. networks with different bandwidth, different latencies, packet loss etc...?

# Answer
> 5 votes
RakNet's FAQ has some recommendations for such tools:

> How do I simulate lag?
>
> In a hurry, use RakPeer::ApplyNetworkSimulator. But I recommend http://www.netlimiter.com/ instead. There is also Network Emulator Toolkit (NEWT) from http://blog.mrpol.nl/2010/01/14/network-emulator-toolkit/ or Introducing True Network Emulation in Visual Studio 2010

# Answer
> 1 votes
http://www.netlimiter.com isn't bad. The free version allows you to put different bandwidth limits on the connections in your machine. Not sure that it can do packet loss though.

---
Tags: networking, multiplayer, tools
---


# Question
Title: Issue with Mapping Textures to Models in Blender
I've been trying to texture a model using Blender, but when I draw on the UV Editor it doesn't show up on the model, and I can't draw on the model itself. I've tried saving the image and the 3D View is set to Texture. Everything seems to be in order and I've followed several tutorials, but none of them seem to work with the version I'm using (2.64-- update was necessary for import plugin) and I'm absolutely stumped.

How can I draw textures to the model? If not within Blender itself, how do I export/import the textures?

EDIT: Vertex Paint works, though it is insufficient for my purposes. In addition, moving to the rendered view produces a solid-color model with none of the applied textures.

# Answer
> 1 votes
There is a common cause for textures not showing up in the viewport in Blender. It's a bit confusing, but I'll try to make it clear. You can assign textures to a mesh in two different places!

You can set textures on materials. These textures will always show up in renders but not always in the viewport. Assign textures to materials using the material properties.

You can also set textures on faces individually. These will never show up in renders, but can be seen in some viewport configurations. Assign textures to faces using the UV/Image editor by selecting faces in the 3d view and changing the current image in the uv/image view. Selecting a face in the 3d view will change the image in the uv/image view.

The texture assigned to a face is the texture that will receive texture paint operations on that face.

Which of the textures show up in the viewport depends on both the viewport display settings (3d view properties panel -\> display -\> shading) and the viewport shading mode.

1. With single or multi-texture shading, only the face textures will be displayed.
2. If the Cycles renderer is enabled, only the material textures will be displayed.
3. With GLSL shading and "textured solid" enabled, face textures will be displayed in 'solid' mode, and material textures in 'textured' mode.

---
Tags: textures, blender
---


title: Load order in XNA?

text:
# Question
Title: Load order in XNA?
I am wondering whether the is a mechanism to manually control the call-order of

```
void Game.LoadContent()

```

as it is the case with

```
void Game.Draw(GameTime gt)

```

by setting

```
int DrawableGameComponent.DrawOrder

```

?

* except the order that results from adding components to the `Game.Components` container and
* maybe there exists something similar with `Game.Update(GameTime gt)` ?

**UPDATE**

To exemplify my issue consider you have several game components which do depends to each other regarding their instantiation. All are inherited from `DrawableGameComponent`.

Now suppose that in one of these components you are loading a `Model` from the games content pipeline and add it to some static container in order to provide access to it for other game components.

```
public override LoadContent() {

    // ...

    Model m = _contentManager.Load<Model>(@"content/myModel");

    // GameComponents is a static class with an accessible list where game components reside.
    GameComponents.AddCompnent(m);

   // ...

}

```

Now it's easy to imagine that this components load method has to precede other game components that do want to access the model m in their own load method.

# Answer
> Now suppose that in one of these components you are loading a Model from the games content pipeline and add it to some static container in order to provide access to it for other game components.

if other components need the model, they should get it throught the content manager...

in case a component need to know what model has other compnent, maybe you need a post initialization method where it succeed

```
public void Initialize()    {...}
public void PostInitialize() {...}

```
> 1 votes

# Answer
The `Game.LoadContent()` method will (in the default template) have the line `base.LoadContent();` in it. That will call the `LoadContent()` methods of all your `DrawableGameComponent`s.

If you have content that must be loaded before some other `Component` tries to access it, then you can simply load it in the `Game.LoadContent()` method, before calling `base.LoadContent();`

However, I'm still unsure why you need to access the loaded content from other components before the `Update()` \- `Draw()` cycle starts.
> 0 votes

---
Tags: xna, c#, component-based
---


title: Drawing order in XNA

text:
# Question
Title: Drawing order in XNA
When manually setting the drawing order of game components by setting

```
int DrawableGameComponent.DrawOrder

```

can one use any integer numbers as long an order is defined like

* component1 =\> drawing order: 2
* component2 =\> drawing order: 5
* component3 =\> drawing order: 10
* component4 =\> drawing order: 323

or do these integers have to be consecutive and starting with zero like

* component1 =\> drawing order: 0
* component2 =\> drawing order: 1
* component3 =\> drawing order: 2
* component4 =\> drawing order: 3

?

# Answer
It can be anything

`This value can be any integer. Components in the GameComponentCollection are drawn in ascending order based on their DrawOrder.`

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.drawablegamecomponent.draworder.aspx
> 5 votes

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


title: LWJGL - OpenGL - Texture shading

text:
# Question
Title: LWJGL - OpenGL - Texture shading
I want to use LWJGL to create a shader that all it does is change the color of the given texture. For example I tell it to draw the letter A using a sprite sheet then I can tell the shader to draw the letter in a certain color. How would you do something like this without needed to create different colored letter sprite sheets?

Task for the shader: Simply change all pixels to a certain color in the texture. Input: Color , texture. Output: it draws onto the screen the new colored texture.

How do i accomplish such a thing?

# Answer
I am using the shaders from the OpenGL ES Book Chapter 9 Sample as base link.

First, I'll need a variable to pass the `vextex color` to the `vertex shader`. But I would also need to send this information to the `fragment shader` with a `varying` variable. Like this:

```
attribute vec4 a_color;
varying vec4 v_color;

```

Then, I'll just pass this information to the `fragment shader` from my `vertex shader`:

```
v_color = a_color;

```

In the `fragment shader`, where I would have the line `gl_FragColor = texture2D( s_texture, v_texCoord );`, I could just do something like:

```
gl_FragColor = texture2D( s_texture, v_texCoord ) * v_color;

```

So, if you have a texture with values `(1,1,1,1)`, and a `v_color` with values `(1,0,0,1)` (Red), it will result in `(1, 0, 0, 1)`.
> 1 votes

# Answer
If you are using fixed function OpenGL with GL lights, you need to tell it to modulate the base color (from glColor and lighting equations) with the texture:

```
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

```

Otherwise, just multiply the vertex color by the texture color in the fragment shader.
> 1 votes

---
Tags: opengl, textures, shaders, lwjgl, color
---


title: Rotating 2D Object

text:
# Question
Title: Rotating 2D Object
Well I am trying to learn openGL and want to make a triangle move one unit (0.1) everytime I press one of the keyboard arrows. However i want the triangle to turn first pointing the direction where i will move one unit. So if my triangle is pointing up and I press right the it should point right first and then move one unit in the x axis. I have implemented the code to move the object one unit in any direction, however I can not get it to turn pointing to the direction it is going. The initial position of the Triangle is pointing up.

```
#define LENGTH 0.05

float posX = -0.5, posY = -0.5, posZ = 0;
float inX = 0.0 ,inY = 0.0 ,inZ = 0.0; // what values????

void rect(){
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glPushMatrix();
    glTranslatef(posX,posY,posZ);
    glRotatef(rotate, inX, inY, inZ);
    glBegin(GL_TRIANGLES);
    glColor3f(0.0, 0.0, 1.0);
    glVertex2f(-LENGTH,-LENGTH);
    glVertex2f(LENGTH-LENGTH, LENGTH);
    glVertex2f(LENGTH, -LENGTH);
    glEnd();
    glPopMatrix();

}

```

# Answer
> 1 votes
Every rotation in gl is according to a given vector. Dependending from where you are looking at the triangle, you will have to rotate according to that vector. For instance, if you are looking from z\>0, you have to rotate your triangle with

```
inZ = 1

```

such that the triangle rotates according to the vector (0,0,1).

UPDATE:

Generally speaking, this code needs some attention. In openGL, you must understand the concept of MODELVIEW, VIEWPORT, and PROJECTION, all the three are matrixes. You are using a PROJECTION matrix to draw your object, which conceptually is not correct (even if you can). In general lines, you have to define your viewport and projection, and only then you can draw a model (e.g. a triangle, or a cat). See this answer, which has some insight about these concepts.

# Answer
> 0 votes
`glRotatef()` creates a rotation around the axis specified by the vector. Try `glRotatef(angle, 0, 0, 1);` to rotate around the Z-axis.

For example:

```
// Set up orthogonal 2D Projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, screenWidth, 0, screenHeight, -1, 1);

// Set up View matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-cameraX, -cameraY, -cameraZ);

// Set up Model * View matrix
glPushMatrix();
glTranslatef(modelX, modelY, modelZ);
glRotatef(modelAngle, 0, 0, 1);
// draw model
glPopMatrix();

```

Pay attention to the order of matrix operations.

---
Tags: opengl, 2d, rotation, glut
---


# Question
Title: How important is Programming for a Level Designer?
I'm currently attending school in a Level Design program, and I was wondering how important programming really is in being a Level Designer?

I'm apparently incapable of learning programming (despite my best efforts), and tend to do very well in all other courses 3D modelling, story/character design, narrative and dialogue writing, environmental and conceptual design etc.

I'm wondering if my strengths in the other areas are enough (with practice) to let me become a Level Designer, or I'm wasting my time if I can't program?

I really want to be a Designer, but I just can't seem to wrap my head around the "language" of programming in general (Java kicks my teeth in even with tutoring and additional work on my own).

# Answer
> 10 votes
The answer is: it depends. Unfortunately that's probably the best you're going to get. While a level designer isn't as likely to be using Java (but it's possible), they're commonly going to implement some form of scripting language. Depending on the type of level design you're doing, scripting may be *all* you do. It's good that you have the skills in art and language, and you may find a job that's all about using only those talents. Wasting your time? No, you're pursuing what you want to do, that's not a waste of time. However, you should continue to pursue your programming. Since, while you may be able to find work only doing the tasks you're good at, it narrows your opportunities quite a bit. Keep at the programming. If a tutor is not helping you understand the basics, then you probably need a new tutor. If you're still struggling there are a lot of programming resources for young children that may be useful for you to crack the barrier that's keeping you from understanding the process.

# Answer
> 3 votes
No matter what field in game design you pick, programming is going to appear in some shape or form. For example in Maya it is used to create nifty functions for exporting or manipulating geometry. In level design you will see it when you are creating events to occur, like scrolling to the next screen in a classic Zelda game. I am however, by no means trying to discourage you for looking into being a level designer, just know that sooner or later you will have to use some programming.

Being good at art and story telling is fantastic and an area I have yet to master, but since you are so confident in your skills there you should continue trying to branch out as a jack of all trades. But like you said, programming is not really your thing so you should start with something nice and easy (not JavaScript as that is way over complicated by being poorly written).

The simplest form of programming I have found so far is the event scripting in RPG Maker XP. Although there is a new version out, I suggest you download that and just do some simple stuff, make the screen change to a new map, add items when you walk over squares, initiate NPC chatting, etc. RPG Maker does almost everything for you minus the scripts to kick it off the events, so I find it's a great place to start if you just want to muck around with things.

If you want to skip the cute stuff and get into some basic raw programming, try taking a spin over to Khan Academy they have a lot bunch of videos you can check out about some of the basics. You don't really need to become a master of programming (stuff like threads and manipulating the gpu) but if you can understand the basics of `if` statements, `for`/`while` loops, and a handful of other commands, you should be fine in pursuing a lite-programming game design career.

# Answer
> 2 votes
Programming experience is a highly desirable trait for a level designer looking to enter the industry. While there are certainly positions available which do not include any scripting responsibilities, these positions are not as numerous as those that would require scripting.

To put it in a different perspective, given the choice between two candidates for a design position, one with scripting experience and one without, studios would be much more inclined to hire the person with scripting experience. Even if they are being hired for a position which would not initially require scripting, responsibilities in game development change rapidly, and that additional scripting experience is valuable.

Something you might be interested in looking at are the requirements listed for job openings throughout the industry. You'll find things like the following:

* Programming or Scripting experience (C++, Lua, other proprietary scripting languages, or similar).
* Experience creating first-person levels using Unreal, Quake, Half-Life, or similar technologies
* Excellent written and verbal communications skills

Some listings have all of these, some leave out the scripting experience. Overall though, I would say that the listings that require or prefer scripting greatly outnumber those that do not. In addition, having programming experience also opens the possibility of fitting into a Technical Designer's role, further expanding the list of potential jobs you could take.

I'd also throw in that having programming experience can help strengthen communication between you and the engineers you work with, and good communication between disciplines is crucial in game development.

To sum up, I'd strongly encourage you to continue to put your best efforts into learning how to script. If anything, your determination in doing so will be a desirable trait when you go in for a job interview :)

As for an easy language to get started in, I'll make my plug here for Python. Super simple to learn and use.

# Answer
> 1 votes
I would say that programming is non-essential for a typical level design position. Of course more knowledge about the game development process is always helpful, but I'm sure there are many level designers who don't have to do any scripting at all.

Personally I expect you probably could pick up the basics of scripting anyway, because it is usually less demanding than regular programming, and because anybody can learn if they put their mind to it.

---
Tags: software-engineering, level-design, jobs
---


# Question
Title: What programming languages are sufficient for web browser game development?
I am wondering with what kind of languages such a multi-player online game was written?

I am trying to find a list of web programming languages which could be sufficient for both of these websites. My thought was HTML, CSS, JavaScript, PHP, SQL.

# Answer
> 3 votes
There are basically two types of web browser games from technological perspective:

**1. Games that do not require server back-end (client only)**

These are mostly casual arcade-like games - e.g. shooters, platformers and side-scrollers - which usually require no data persistence, networking or multiplayer capabilities, or which only require client side data persistence and multiplayer capabilities (e.g. hot-seat, split screen).

To create such a game you only require to create code, that will run on the client side.

This can be done using either native web browser technologies - HTML, CSS and JavaScript - or using various technologies that come as web browser plugins and extensions - Flash, Java applets, Silverlight, and possibly some others.

**2. Games that require server back-end (client + server)**

These are more complex games such as turn-bases strategy games and RPGs, which usually require some server side data persistence, networking or multiplayer capabilities. It can also be simple client side games, that just require some ranking or top scores capablities.

These games also require the client side code, same as the games without the server back-end, but they also require the server side code, which will communicate with the client code to transfer and process the game data to provide the required persistence and multiplayer capabilities.

For this there are literally tons of options, ranging from PHP, Python, Ruby and MySQL all the way to ASP.NET, Java and Oracle or the most recent options such as using JavaScript with Node.js. Presently it is possible to write server side applications and web applications with just about any popular language. The choice here would be limited by the specific requirements of the game at hand - server OS, security, performance, load balancing, ...

---

As for your question about what is sufficient, it mostly depends on if you require the server back-end or not.

If it is a simple enough game that can run on client only, then I think that especially HTML5 + JavaScript is presently a killer combination for any client code. It is native to the web browser and it has most of the capabilities of technologies such as Flash and Silverlight, therefore it is sufficient and most straightforward.

For the server side, if there are no special and strict requirements on some of the aspects mentioned above, you could just stick with the programming languages and frameworks that you know and like to use, and it would be sufficient.

---
Tags: software-engineering, browser-based-games, web
---


# Question
Title: How to begin serious game development (in C++)
I would like to start developing games. I have tried before *Game Maker 8*, which was a very easy way to start creating games, if you were new in game development. Then, I tried *Unity 3D*, which was a much more serious and complete tool to create computer-games, and required some experience. And now, I would like to start creating games, and don't use any special environment or developer, but just code (in C++ preferably). So, here is my question: from where should I begin, if I would like to start programming games? Thanks in advance.

***Note:*** I work in ubuntu 10.04, I can also use windows 7, but I prefer ubuntu.

# Answer
Any of these already existing posts on gamedev may be useful. In fact, this is just a short list of the top voted questions (most of them are closed, because they don't fit this site's objective) on Gamedev.
> 10 votes

# Answer
If you already know some C++ then I would suggest using SDL Its a great library that does alot for 2D game development and can even do some OpenGL stuff when you move onto 3d. If you don't know any C++ at all start with some C stuff and then just add classes and all that junk and you have C++. And just a side note: C++ is not that hard I don't see why everyone thinks its such an ogre.
> 5 votes

# Answer
Best thing IMHO is to start with something achievable but with obvious potential for scale and complexity to it so there is always something to go on to. I think something like a 2D side-scrolling platformer is good for this.

It means you can work from basic "getting something (anything) working" to control, gravity and then combat, AI, better graphics. The possibilities are limitless but because there is a way to make something work visually at almost every stage you won't have the sort of steep curve to get it to work that you would with some other genre of game.

...

One minor point I would make is that I probably wouldn't do it in C++ (let the flames begin!) to begin with because unless you're really experienced, you're probably going to spend more time fighting with the code to get it to work than you are dealing with the things specific to your gaming. That might not be helpful for motivation. One of the main reasons to use C++ is for speed and I'd put that down the list of "ways to expand this or make it better" until speed (or lack of) is noticeable in what you're doing.
> 4 votes

---
Tags: c++, software-engineering
---


title: Safe zone implementation in Asteroids

text:
# Question
Title: Safe zone implementation in Asteroids
I would like to implement a safe zone for asteroids so that when the ship gets destroyed, it shouldn't be there unless it is safe from other asteroids.

I tried to check the distance between each asteroid and the ship, and if it is above threshold, it sets a flag to the ship that's a safe zone, but sometimes it work and sometimes it doesn't. What am I doing wrong?

Here's my code:

```
for (list<Asteroid>::iterator itr_astroid = asteroids.begin(); itr_astroid!=asteroids.end(); )
{
    if(currentShip.m_state == Ship::Ship_Dead)
    {
        float distance = itr_astroid->getCenter().distance(Vec2f(getWindowWidth()/2,getWindowHeight()/2));
        if( distance>200)
        {
            currentShip.m_saveField = true;

            break;
        }
        else
        {
            currentShip.m_saveField = false;
            itr_astroid++;
        }
    }
    else
    {
    itr_astroid++;
    }
}

```

At ship's death:

```
if(m_state == Ship_Dead && m_saveField==true)
{
    --m_lifeSpan;

}

if(m_lifeSpan<=0 && m_saveField == true)
{
    m_state = Ship_Alive;
    m_Vel   = Vec2f(0,0);
    m_Pos.x = app::getWindowWidth()/2;
    m_Pos.y = app::getWindowHeight()/2;
    m_lifeSpan = 100;

}

```

# Answer
> 3 votes
This should work for checking if the center of the screen is safe for the ship only when the ship is dead. As soon as your ship is no longer in the dead state, the center will be considered safe (because of the if statement and intialization to true.) If you want the ship to be considered unsafe when it is not dead, you can change the logic around a bit (set initial value to false, check if ship is dead, if dead make safe, run asteroid check for loop.)

I see that you mentioned my comment about boolean logic helped make things a bit more consistent, but I'm not really sure what the new problem is. I would be happy to edit my answer if you can tell me more about what the goal of your check is, when it should succeed, and when it should fail.

```
currentShip.m_saveField = true;

for (list<Asteroid>::iterator itr_astroid = asteroids.begin(); itr_astroid!=asteroids.end(); iter_astroid++)
{
    if(currentShip.m_state == Ship::Ship_Dead)
    {
        float distance = itr_astroid->getCenter().distance(Vec2f(getWindowWidth() / 2, getWindowHeight() / 2));
        if (distance < 200)
        {
            currentShip.m_saveField = false;
        }

    }
}

```

it seems you want your ship to not be safe when it is not in the Ship\_Dead state so you should use a modified version of the above code:

```
currentShip.m_saveField = currentShip.m_state == Ship::Ship_Dead;

if (currentShip.m_saveField)
{
    for (list<Asteroid>::iterator itr_astroid = asteroids.begin(); itr_astroid!=asteroids.end(); iter_astroid++)
    {
        float distance = itr_astroid->getCenter().distance(Vec2f(getWindowWidth() / 2, getWindowHeight() / 2));
        if (distance < 200)
        {
            currentShip.m_saveField = false;
            break;
        }
    }
}

```

# Answer
> 1 votes
If you want to put the ship in center of the screen, it may happen that player will wait a long time until the area is safe (potentially even forever). Especially because in a typical Asteroids game the asteroids are teleporting from one side of screen to another, making you unable to control their position. So if you want to block player's movement when "dead" (just before placing a new ship), and your asteroids indeed wrap around the screen boundaries, the only way I see to solve it is creating a repel field in the center, that pushes approaching meteors away. Strength of the repel could be based on squared distance of an asteroid from screen's center.

---
Tags: c++, opengl, logic
---


title: How to read BC4 texture in GLSL?

text:
# Question
Title: How to read BC4 texture in GLSL?
I'm supposed to receive a texture in BC4 format. In OpenGL, i guess this format is called GL\_COMPRESSED\_RED\_RGTC1.

The texture is not really a "texture", more like a data to handle at fragment shader.

Usually, to get colors from a texture within a fragment shader, i do :

```
uniform sampler2D TextureUnit;
void main()
{
   vec4 TexColor = texture2D(TextureUnit, vec2(gl_TexCoord[0]));
(...)

```

the result of which is obviously a v4, for RGBA.

But now, i'm supposed to receive a single float from the read. I'm struggling to understand how this is achieved.

Should i still use a texture sampler, and expect the value to be in a specific position (for example, within TexColor.r ?), or should i use something else ?

# Answer
In case of having one-channel images you should use `texture2D` as follows

`float TexColor = texture2D(TextureUnit, gl_TexCoord[0]).r`

which basically forces to read only the first (and only) channel of the image and stores its value into TexColor. At least, this is how I handle shadow maps for example (which are stored in one-channel images.
> 2 votes

# Answer
Let's provide a complete answer.

First:

```
texture2D(TextureUnit, vec2(gl_TexCoord[0]))

```

Since we're talking about RGTC, we're in GL 3.x+ land. You shouldn't be using `texture2D` anymore; just use `texture`. That way, if you change the type of `TextureUnit`, everything will still work. But that's minor.

Also, `vec(gl_TexCoord[0])` is better spelled `gl_TexCoord[0].xy`. But again, minor.

The main thing is this: accessing a (non-shadow) texture *always* returns a 4-component vector. It doesn't matter what the texture's format is; it returns 4 components. If a texture doesn't actually provide all of the components, then the missing components will be filled in by the vector (0, 0, 0, 1).

Let's take your format: `GL_COMPRESSED_RED_RGTC1`. This uses the `RGTC1` style of compression, and it provides the `RED` color component. So it fills in only the red component; every texture access will therefore be (R, 0, 0, 1). If your format was `GL_COMPRESSED_RG_RGTC1`, then you would get the `R` and `G` components; every texture access would provide (R, G, 0, 1).

Therefore, if you want the red component from the texture, just ask for it:

```
texture(TextureUnit, gl_TexCoord[0].xy).r

```

Of course, texture swizzling can mess around with this too. But that's a discussion for another time.
> 5 votes

# Answer
From the shader's perspective, a block-compressed texture like BC4/RGTC1 behaves just like any other texture; the GPU hardware automatically handles the block decompression and filtering on your behalf. BC4 is a single-channel texture, so you are correct: use texture2D() -- or texture() in more recent GL versions -- and the data you want will be in the TexColor.r field.
> 4 votes

---
Tags: textures, glsl, fragment-shader
---


title: How do I do random isometric paths?

text:
# Question
Title: How do I do random isometric paths?
I'm working on an isometric city generator, and I am looking for a little push in the right direction. I'm looking to randomly generate roads on an isometric plane. I have never done path making before, and I've Googled it and didn't find any articles relating to what I am trying to do.

Basically, my program generates a random isometric city and I am hoping to add roads to that.

# Answer
> 5 votes
The "isometric plane" is just the normal 2D plane, and every algorithm which procedurally generates roads on a 2D grid will do.

There's a nice overview of possible methods available online; just quoting relevant parts of the reference list off "A Survey of Procedural Techniques for City Generation" (2006) by George Kelly and Hugh McCabe (Google it if you want the full text) as an example:

* Yoav I H Parish, Pascal Mueller; 2001. "Procedural Modeling of Cities"
* Jing Sun and Xiaobo Yu and George Baciu and Mark Green; 2002. "Template-based generation of road networks for virtual city modeling"
* Thomas Lechner, Ben Watson, Uri Wilensky, Martin Felsen; 2003. "Procedural City Modeling"
* Greuter S., Parker J., Stewart N., and Leach G.; 2003. "Real-time procedural generation of \`pseudo infinite' cities"

# Answer
> 1 votes
Algorithms may differ depending on what culture you want represent. Mexicans and Americans build cities in a grid, that is parallel and perpendicular streets and avenues. This is the simplest to program, because you just need to make a vertical street every let's say 10 tiles, and horizontal avenue also every 10 tiles. Some cities make road structure harder to implement, e.g. with crossroads looking like stars \*, and some consist of nearly random process of historical evolution of the city.

---
Tags: procedural-generation, isometric
---


# Question
Title: correct pattern to handle a lot of entities in a game
In my game I usually have every NPC / items etc being derived from a base class "entity". Then they all basically have a virtual method called "update" that I would class for each entity in my game at every frame. I am assuming that this is a pattern that has a lot of downsides. What are some other ways to manage different "game objects" throughout the game? Are there other well-known patterns for this? My game is a RPG if that changes anything

# Answer
First of all, this question doesn't really have anything to do with design patterns. This is closer to optimization, though it's lacking a performance problem. So, question #1: is your current entity system a performance bottleneck? If no, don't worry until it actually is.

If it already is, there's a few things you can do:

1. Sort entities by type (or store them in separate arrays and iterate through them separately). This will ensure that entity code is reloaded no more times than it's necessary.
2. Update some entities less often. The easiest way to do that is to increment an internal delta time value for each entity (or a group) and actually update the entities when it reaches a certain value, at which point it is cleared (set to 0) again.
3. Merge many entities into one and internally use algorithms that fit the data best.
> 4 votes

# Answer
You could keep an Array of entities that need to be updated. Every time a entity is changed, it calls a callback function (or notifies the class holding the Array in other way) so it is added to the Array, and the Array is cleared after all updates are done. It may be slower if you're 'updating' (calling update methods of) most of the entities every frame anyway.
> 0 votes

# Answer
First of all, define "a lot," and check that there really is a problem. You can easily handle thousands of game entities with your model on even modest hardware with no performance problems to speak of (assuming you don't have something really silly going on in one of the update functions themselves).

That said, there are some superior design approaches to use in the general sense. The usual mantra is to make use of component based design of some form. In other words, favor composition over inheritance. Don't have classes inherit from entity instead, have the entity be a container for component objects, which then either contain (preferable) or contain logic (also very useful, though some specific forms of component based design ban logic components).

The advantage to this approach from a performance perspective is that you can remove any need to call update() on components that have no logic, and hence from any entities that have no logic components. If you have an item that just lays on the ground, and hence has nothing to update and has no logic components, it won't be touched during your update loop.

You can also just keep the update() method on components and entities. Really, honestly, it scales just fine even in many larger AAA titles, so long as you don't have a ridiculous number of objects live at any given time, and apply some sense to how your entities/components are allocated and iterated over in memory. The performance bottlenecks in most games are completely outside of the logic update loop, and are off in the specialized systems that do many many operations, e.g. the physics/collision system, graphics, resource streaming, path-finding, etc. These are all things that you should never do in an update() method of an entity/component, no matter what the design of your engine is; these belong in specialized, optimized systems.

The true advantage of a component based design (whether it's a rigidly adhered-to entity system design or the complete spaghetti-like chaos of Unity's component system, or something sensible that falls in between) is that it allows a separation of logical modules, it facilitates data-driven design of game object behavior, and through those allows for a greatly increased rate of game design iteration and hence a better game made with less time/money/bugs. Components also make hooking up an editor to your game data quite a bit easier, as well as allowing designers to make new types of in-game entities without needing to wait for a programmer to make every little change.

In other words, worry less about the number of objects or performance, and worry more about how easy it is to totally change up and tweak large parts of your game design. Virtually no well-known successful game has ever gone from initial design to release without having some massive changes to the game's direction somewhere in the middle, usually after building enough of the game to get a prototype in front of players and find out how well the design ideas actually work. The more flexible and future-proof your object design is, the better off you'll be.

The main introductory article on the topic is http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/.

There's also a great set of slides from Scott Bilas, who worked on Dungeon Siege and helped pioneer the use of components in game engines (back before just about everyone started using them): http://scottbilas.com/files/2002/gdc\_san\_jose/game\_objects\_slides\_with\_notes.pdf
> 0 votes

---
Tags: c++, rpg, design-patterns
---


title: Turning to face mouse

text:
# Question
Title: Turning to face mouse
Given three points on the same Y plane;

* A ship
* A point along the ships heading
* A mouse cursor

How can I find which direction and angle the mouse cursor is from the ships heading?

I have a limited turn speed on the ship - so I can not simply point the ship at the mouse, but tell it to steer left or right until it faces in the same direction of the mouse.

# Answer
> 2 votes
```
ship_dir =point_on_heading-ship_pos(ition) //vector ship is heading in
mouse_dir=mouse_pos-ship_pos               // vector from ship to mouse position

```

You can find the angle between these two vectors;

```
ship_dir.Normalize(); //divide by length
mouse_dir.Normalize();//divide by length
dot_prod=DotProduct(ship_dir,mouse_dir);
angle=acos(dot_prod); //cos-1, this will give angle between two vectors

```

BUT that doesn't tell you which way to turn (left or right)(positive or negative)(clockwise or anti-clockwise).

You also need to consider the normal to the mouse\_dir. The dot product between two vectors is positive if the angle is less than 90deg.

```
mouse_normal=(-mouse_dir.y,mouse_dir.x);
dot_prod=DotProduct(ship_dir,mouse_normal);
if(dot_prod>0) //+ive value means the angle is <90deg therefore, ship_dir is on 'left'side of mouse dir, so clockwise is shortest route
    rotate clockwise;
else
    rotate anti_clockwise;

```

---
Tags: 3d, vector, mouse
---


title: Monster's AI in an Action-RPG

text:
# Question
Title: Monster's AI in an Action-RPG
I'm developing an action rpg with some University colleagues. We've gotton to the monsters' AI design and we would like to implement a sort of "utility-based AI" so we have a "thinker" that assigns a numeric value on all the monster's decisions and we choose the highest (or the most appropriate, depending on monster's iq) and assign it in the monster's collection of decisions (like a goal-driven design pattern) .

One solution we found is to write a mathematical formula for each decision, with all the important parameters for evaluation (so for a spell-decision we might have mp,distance from player, player's hp etc). This formula also has coefficients representing some of monster's behaviour (in this way we can alterate formulas by changing coefficients).

I've also read how "fuzzy logic" works; I was fascinated by it and by the many ways of expansion it has. I was wondering how we could use this technique to give our AI more semplicity, as in create evaluations with fuzzy rules such as
`IF player_far AND mp_high AND hp_high THEN very_Desiderable`
(for a spell having an high casting-time and consume high mp) and then 'defuzz' it. In this way it's also simple to create a monster behaviour by creating ad-hoc rules for every monster's IQ category.

But is it correct using fuzzy logic in a game with many parameters like an rpg? Is there a way of merging these two techniques?
**Are there better AI design techniques for evaluating monster's chooses?**

# Answer
i reply because when i saw your post i 'saw' one possible reply : probability.
Imagine :
* Health is beetween 0/100% = 0.0/1.0
and you normalize each value so that they fit in this range
* Distance would be 100% if player within reach, and 100%-10%\*(timetoreach) otherwise ( here monster further from 10 seconds wouldn't react to the player ).
Aggressivity would be a specific factor for each 'race' (maybe with radom changes to spice up things)
* Anger would be 100% (or even more) if monster was hit or treasure stolen or (near) monster's friend is hit by player, but less than 100% if the monster just saw you, and much less if monster is cool and didn't see you. (Well... you could say also that if the monster didn't saw you, it shouldn't attack. But monsters talk together...)
* Bersek would be a special factor that would be \>1 and greatly raise the chance the ennemy attack : imagine an alarm bell is ringing : all monsters are seeking a target (and talk together or hear a message on speakers ... :-) )
* Mistrust would be 100% or higher if you are running fast dressed only with a flashing pink pant and with a sword covered of blood, and Mistrust would be very low if you walk slowly dressed as a priest...

So once you have all those normalized factors f1, f2, f3, .... you multiply them P=f1\*f2\*...\*fn and you get the probability the monster attack within a given time range. So if (Math.random()\>P) you make the monster attack (and grunt)...

If you need to adjust the relative influence of a factor, use Math.pow(Probability, power) to 'shape' the probabilty of each factor. if you use a pow \>1, you give more influence to a factor, if you use a 0 \< pow \< 1, you give less influence to it.
Expl1 : with pow=3 (\>1). 0.2 -\> 0.08 0.5 -\> 0.125 0.8 -\> 0.512
Expl2 : with pow = 0.3 (\<1). 0.2 -\> 0.6 0.5 -\> 0.81 0.8 -\> 0.94. --\> Conclusion : With a shape pow \< 1, when the factor is close to 0 , this does not bring down the whole attack probabilitiy --\> the factor has less influence with pow \<1, and the less influence pow is closer to zero. (and vice versa).

The probability would be now P = pow(f1,p1)\* pow (f2,p2) * pow (f3,p3) * ...
and each 'time range' (?= 10 seconds ?) you throw the dice and see what happens. But you should also throw the dice on a monster on which an event happened ( the monster saw the player / heard him / heard/saw a fight / heard the alarm ringing /... ).
Rq : Some events should always trigger an attack (monster attacked by player/...).
Rq2 : you might want to shape the random function also, and use other shaping function(sin, ln, ...)

computation can be faster if you detect fi == 0 within the factors ( or 'low' fi / 'low' shaped fi).

Hope this helps.
> 2 votes

# Answer
Check out this book on Behavioral Mathematics by Dave Mark:

http://www.amazon.com/gp/aw/d/1584506849

He has also done some excellent talks at GDC if you happen to have Vault access.

The book goes over the use of utility functions, response curves, and composition of behaviors with planning using mathematics and simple architecture. This lets you combine those utility functions with decision making without needing to write another architecture for it. I've personally seen this approach successfully used for RPG AI, procedural obstacle course generation, and action decision making.
> 4 votes

---
Tags: ai, rpg, design-patterns
---


title: Index out of bounds, Java bukkit plugin

text:
# Question
Title: Index out of bounds, Java bukkit plugin
I'm getting index out of bounds errors in my Bukkit plugin, and it's really beginning to piss me off...

I for the life of me can't figure this issue out!

Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

This is where I believe the code to be erroring...

```
for(int i = 0; i <= staffOnline.size(); i++) {
            if(i == staffOnline.size()) {
                staffList = staffList + staffOnline.get(i);
            } else {
                staffList = staffList + staffOnline.get(i) + ", ";
            }
        }

```

# Answer
The objects in collections in Java are usually indexed starting with zero. Also, the method `.size()` returns the numbers of elements inside the collection.

So, if the size is 1, you can only access the element 0. Not 0 and 1 like you're doing, because the element 1 do not exist.

Try this:

```
for(int i = 0; i < staffOnline.size(); i++) { // changed here
        if(i == staffOnline.size() - 1) { // and here :)
            staffList = staffList + staffOnline.get(i);
        } else {
            staffList = staffList + staffOnline.get(i) + ", ";
        }
    }

```
> 4 votes

---
Tags: java, minecraft-modding, bukkit
---


# Question
Title: How to choose cell to put entity in in an uniform grid used for broad phase collision detection?
I'm trying to implement the broad phase of my collision detection algorithm. My game is an arcade game with *lot of* moving entities in an open space with relatively equivalent sizes.

Regarding the above specifications, i decided to use an uniform grid for space partitioning. The problem i have right know is how to efficiently choose in which cells an entity should be added. ATM i'm doing something like this:

```
for (int x = 0; x < gridSize; x++) {
    for (int y = 0; y < gridSize; y++) {
        GridCell cell = grid[x][y];
        cell.clear(); //remove the previously added entities
        for (int i = 0; i < entities.size(); i++) {
            Entity e = entities.get(i);
            if (cell.isEntityOverlap(e)) {
                cell.add(e);
            }
        }
   }
}

```

The `isEntityOverlap` is a simple method i added my `GridCell` class.

```
public boolean isEntityOverlap(Shape s) {
    return cellArea.intersects(s);
}

```

Where `cellArea` is a Rectangle.

```
cellArea = new Rectangle(x, y, CollisionGrid.CELL_SIZE, CollisionGrid.CELL_SIZE);

```

It works but it's damn slow. What would be a fast way to know all the cells an entity overlaps?

Note: by "it works" i mean, the entities are contained in the good cells over the time after movements etc.

# Answer
> 4 votes
pseudo-code:

```
ClearAllCells();
foreach(entity)
  int minXCoord = floor(entity->GetPosition().x-entity->GetRadius()) / CollisionGrid.CELL_SIZE;
  int minYCoord = floor(entity->GetPosition().y-entity->GetRadius()) / CollisionGrid.CELL_SIZE;
  int maxXCoord = ceil(entity->GetPosition().x+entity->GetRadius()) / CollisionGrid.CELL_SIZE;
  int maxYCoord = ceil(entity->GetPosition().y+entity->GetRadius()) / CollisionGrid.CELL_SIZE;
  for ( int x = minXCoord; x <= maxXCoord; x++ )
    for ( int y = minYCoord; y <= maxYCoord; y++ )
      grid[x][y].add(entity);

```

Basically, instead of iterating over every entity for every grid square, checking if the entity is in that grid square, just iterate over every entity once, calculating what grid indices it intersects.

This approach works effectively for any size entity and any size cells.

# Answer
> 3 votes
Use cell coherence. Don't throw away all that good data from the previous frame.

Basically, most of the time, an entity will be in the same cell (or neighbor) as in the previous update.

*Unless it moves really fast.*

Some pseudocode... \[EDIT\] flaws in comments fixed

```
//assuming the cells have been pre-populated from the previous update
//pass one
for each cell
    for each entity in the cell
       if(cell fully overlaps entity){
           do nothing
       else{
           if(cell does not intersect the entity){
               remove entity from cell
           }
           foreach neighbor_cell//8 neighbor cells
               check_add entity to neighbor cell
               // this method will add entity to the cell if they overlap
       }

```

The effectiveness of this approach is highly dependent on the relative sizes of cells and entities.

E.G. If you have 1000 cells and 1000 entities, your algorithm will require 1,000,000 rectangle overlap checks.

If you have 1000 cells and 1000 entities, then you have on average 1 entity per cell, so the first pass of my algoritm will require 1000 overlap checks. \[not counting entities on boundaries\].

# Answer
> 1 votes
The approach with the intersection check is right, however the way you are iterating over the entities/cells is very inefficient. Also you won't need to do the check every frame for every entity as only a few will move fast enough to cross multiple.

If you have a regular grid you can calculate the position in this grid by a simple division, then you just need to check that tile and the tiles around it, not every tile:

```
foreach(entity in entities)
{
  tileX = entity.x/gridWidth;
  tileY = entity.y/gridHeight;

  entity.currentGrid.removeObject(entity);
  grid[tileX][tileY].addObject(entity);
  entity.currentGrid = grid[tileX][tileY];
  if(entity.intersect(grid[tileX-1][tileY-1].shape)) grid[tileX][tileY].addOverlappingObject(entity);
  if(entity.intersect(grid[tileX][tileY-1].shape)) grid[tileX][tileY].addOverlappingObject(entity);
  [etc ...]
  if(entity.intersect(grid[tileX+1][tileY+1].shape)) grid[tileX][tileY].addOverlappingObject(entity);
}

```

For calculating things less often while catching most errors from this you'll need to predict if the object will change the grid cell it is in soonly.

```
[... calculate distance object needs to go into the next cell ...]
if(speed > distance)
  watchedObjects.pushBack(entity);

```

The loop in which this is then processed in could look like this:

```
// Game loop
while(true)
{
  [... do other game loop stuff ...]
  foreach(entity in watchedObjects)
    [... check if they have changed their position in the grid...]
  if([... 0.25 seconds have passed since last time ...])
  {
    grid.clear();
    watchedObjects.clear();
    foreach(entity in entities)
    {
      [... recalculate the position of every object in the grid...]
      [... check whether it is likely that the object will go over the border in the next 0.25 seconds ...]
    }
  }
  [... do the actual collision detection ...]
  [... do other game loop stuff ...]
}

```

---
Tags: java, collision-detection, grid, space-partitioning, slick
---


# Question
Title: Loading sound in XNA without the Content Pipeline
I'm working on a "Game Maker"-type of application for Windows where the user imports his own assets to be used in the game. I need to be able to load this content at runtime on the engine side.

However I don't want the user to have to install anything more than the XNA runtime, so calling the content pipeline at runtime is out.

For images I'm doing fine using Texture2D.FromStream.

I've also noticed that XNA 4.0 added a FromStream method to the SoundEffect class but it only accepts PCM wave files.

I'd like to support more than wave files though, at least MP3.

Any recommendations? Perhaps some C# library that would do the decoding to PCM wave format.

# Answer
I hadn't noticed the FromStream method, that's a good one to remember. I'm now curious about using FromStream vs DynamicSoundEffectInstance, since you could theoretically accomplish a lot of the same work with both methods.

Google turned up this library: http://robburke.net/mle/mp3sharp/ And you could also conceivably call lame.exe from within your app to decode the sound.

I'd be wary of MP3 though, it's a legal can of worms. Adobe pays a hefty fee to Fraunhofer for the right to use it in Flash. Ogg Vorbis is a superior format, easily converted from mp3 using free and open-source software, and there seem to be many more C#/.Net decoder libraries for it.
> 3 votes

# Answer
I decided to give this problem another try today and finally managed to load an OGG file at runtime into a `SoundEffect` object. Here's what I did! First download the library below which contains a class capable of decoding OGG files:

**Prerequisite - Download library**

**Please keep in mind that the answer was written using the OggSharp library, which is now deprecated and replaced by the NVorbis library.**

The library already has an example, but it uses `DynamicSoundEffectInstance` and streams the audio. But I wanted to load it all at once into a regular `SoundEffect` object so the process was a bit different.

**Step 1 - Decode file**

First create an instance of `OggDecoder` and initialize it with your file:

```
decoder = new OggDecoder();
decoder.Initialize(TitleContainer.OpenStream(@"sound.ogg"));

```

**Step 2 - Get decoded data**

Read all of the data into a buffer. This is the decoded raw PCM data of the file:

```
byte[] data = decoder.SelectMany(chunk => chunk.Bytes.Take(chunk.Length)).ToArray();

```

**Step 3 - Create SoundEffect from stream containing complete wave file header**

However, the stream that `SoundEffect` requires must contain not only the raw data, but also the complete wave file header. You can use this helper method to write the header plus the data:

```
private static void WriteWave(BinaryWriter writer, int channels, int rate, byte[] data)
{
    writer.Write(new char[4] { 'R', 'I', 'F', 'F' });
    writer.Write((int)(36 + data.Length));
    writer.Write(new char[4] { 'W', 'A', 'V', 'E' });

    writer.Write(new char[4] { 'f', 'm', 't', ' ' });
    writer.Write((int)16);
    writer.Write((short)1);
    writer.Write((short)channels);
    writer.Write((int)rate);
    writer.Write((int)(rate * ((16 * channels) / 8)));
    writer.Write((short)((16 * channels) / 8));
    writer.Write((short)16);

    writer.Write(new char[4] { 'd', 'a', 't', 'a' });
    writer.Write((int)data.Length);
    writer.Write(data);
}

```

Use that method to write the data to a stream that can be fed to `SoundEffect.FromStream`:

```
using (MemoryStream stream = new MemoryStream())
using(BinaryWriter writer = new BinaryWriter(stream))
{
    WriteWave(writer, decoder.Stereo ? 2 : 1, decoder.SampleRate, data);
    stream.Position = 0;
    soundEffect = SoundEffect.FromStream(stream);
}

```

**Step 4 - Use the SoundEffect as normal**

Your OGG file is now loaded and can be used like any other `SoundEffect` loaded through the content pipeline:

```
soundEffect.Play();

```
> 7 votes

# Answer
If you're only targeting Windows, I've found that the easiest way is to bypass the XNA Audio API altogether and use something else.

I found the FMOD API to be great for this, and it even comes bundled with a C# wrapper already. I've added my own wrapper around theirs and here's the bare minimum you need to load a sound from a file and play it:

The wrapper:

```
namespace YourNamespace
{
    using System;
    using FMOD;

    public class SoundSystem
    {
        public SoundSystem()
        {
            RESULT result = Factory.System_Create(ref _system);
            if(result != RESULT.OK)
                throw new Exception("Create SoundSystem Failed");

            uint version = 0;
            result = System.getVersion(ref version);
            if (result != RESULT.OK || version < VERSION.number)
                throw new Exception("Create SoundSystem Failed");

            result = System.init(32, INITFLAGS.NORMAL, (IntPtr)null);
            if (result != RESULT.OK)
                throw new Exception("Create SoundSystem Failed");
        }

        public System System
        {
            get { return _system; }
        }

        private readonly System _system;
    }

    public class Sound
    {
        public Sound(SoundSystem system, string path)
        {
            _system = system;
            RESULT result = system.System.createSound(path, MODE.HARDWARE, ref _sound);
            if (result != RESULT.OK)
                throw new Exception("Create Sound Failed");
        }

        public void Play()
        {
            Channel channel = null;
            RESULT result = _system.System.playSound(CHANNELINDEX.FREE, _sound, false, ref channel);
            if (result != RESULT.OK)
                throw new Exception("Play Sound Failed");
        }

        private readonly SoundSystem _system;
        private readonly FMOD.Sound _sound;
    }
}

```

And how to use it:

```
SoundSystem system = new SoundSystem();
Sound sound = new Sound(system, "song.mp3");
sound.Play();

```

Of course that wrapper is just the bare minimum, but should be simple to expand in order to expose any other features you need.
> 2 votes

---
Tags: xna, c#, sound
---


# Question
Title: Scanline filling of polygons that share edges and vertices
In the image below (a perspective projection of an icosahedron), the scanline (red) intersects that vertex at the top. In an icosahedron each edge belongs to two triangles. From edge a, only one triangle is visible, the other one is in the back. Same for edge d. Also, in order to determine what color the current pixel should be, each polygon has a flag which can either be 'in' or 'out', depending upon where on the scanline we currently are. Flags are flipped according to the intersection of the scanline with the edges.

Now, as we go from a to d (because all edges are intersected with the scanline at that vertex), this happens: the triangle behind triangle 1 and triangle 1 itself are set 'in', then 2 is set in and 1 is 'out', then 3 is set 'in', 2 is 'out' and finally 3 is 'out' and the one behind it is set 'in', which is not the desired behavior because we only need the triangles which are facing us to be set 'in', the rest should be 'out'.

How do process the edges in the Active Edge List (a list of edges that are currently intersected by the scanline) so the right polys are set 'in'?

Also, I should mention that the edges are unique, which means there exists an array of edges in the data structure of the icosahedron which are pointed to by edge pointers in each of the triangles.

# Answer
(NB I've answered your related question on this topic as well. You may want to check that answer before reading this one.)

Once you've produced a z-buffer using linear interpolation, you will no longer be operating on the full edge list of your underlying projected geometry, but rather a reduced subset due to occlusion.

This subset is produced as follows:

You will produce the z-buffer itself which stores only depth; and in order to to maintain only unoccluded vertices you will at the same time build a separate, matching structure (same resolution) which contains no information except for (at the pertinent "pixel" locations) IDs of each projected vertex that was unoccluded after your z-buffer was built (that is, those that are actually visible in your z-buffer). It is this second buffer that you will now use to do in-out checks for scanline rasterisation.

HTH.
> 0 votes

---
Tags: 3d, projection, pixel, computational-geometry
---


title: Scan-Line Z-Buffering Dilemma

text:
# Question
Title: Scan-Line Z-Buffering Dilemma
I have a set of vertices in 3D space, and for each I retain the following information:

* Its 3D coordinates (x, y, z).
* A list of pointers to some of the other vertices with which it's connected by edges.

Right now, I'm doing perspective projection with the projecting plane being XY and the eye placed somewhere at (0, 0, d), with d \< 0. By doing Z-Buffering, I need to find the depth of the point of a polygon (they're all planar) which corresponds to a certain pixel on the screen so I can hide the surfaces that are not visible. My questions are the following:

1. How do I determine to which polygon does a pixel belong to so I could use the formula of the plane which contains the polygon to find the Z-coordinate?
2. Are my data structures correct? Do I need to store something else entirely in order for this to work?

I'm just projecting the vertices onto the projection plane and joining them with lines based on the pointer lists.

# Answer
> 4 votes
You will need an active edge list, which contains a list of all polygon edges intersected by the current scanline. You will also need an in/out flag for each polygon on the scanline. The flags are toggled on/of as you cross an edge for a polygon.

The rules are drawing for each pixel along a scanline are;

1. no polygon flags are 'in', then draw background
2. only one polygon flag is 'in', the draw the colour of that polygon
3. two or more polygon flags are 'in', use you plane equation to find out which is closest at that pixel position.
4. as we move onto the next pixel check the AEL (see below) to see if we are crossing an edge. if so toggle the appropriate flag.

An important component in the data structure needed for this algorithm is the edge node. Each edge in the polygon is represented by an edge node. An edge node contains the following information;

1. yupper , the y co-ordinate of the upper end-point of the edge.
2. ylower , the y co-ordinate of the lower end-point of the edge.
3. xint , initially the x co-ordinate of the lower end-point of the edge. As the algorithm progresses, this field will store the x co-ordinate of the point of intersection of the scan-line.
4. ym , the reciprocal of the slope of the line ( 1/m ).
5. link to the polygon which own the edge.

When constructing an edge node for the edges, the following must be taken into account;

1. Horizontal Edges are ignored (an edge node is not generated for these), these edges will be drawn when the adjacent edges are processed.
2. If two edges share a vertex AND the vertex is an upper end point for one edge and a lower end point for another edge, the yupper of the lower edge must be reduced by 1. this is to allow the in/out toggle to work correctly.

In the above image the very top scanline intersects to edges at the top of the triangle. the two edges cause it to toggle from "out" to "in" to "out", which is correct. However, the second line also intersects two edges and is toggled "out" which is incorrect. The solution is to lower the y-int of the lower edge in this case. Now teh scan line only intersects one edge at the vertex.

This adjustment will not have any effect on the shape of the triangle as the xint will be used to determine where to start drawing. The effect of lowering the vertex is to cause it to be removed one scanline earlier than it would otherwise. All this assuming you are scanning from bottom to top.

Most implementations maintain an Active edge list (AEL), a list of edges. which contains all the edges intersected by the current scan line. The AEL needs to be maintained as we move from on scan-line y to the next scan-line (y+1) ;

1. Add any edges whose ylower is equal to y .
2. Colour the pixels along the scanline as described above
3. One or both of the edges in the AEL will no longer be intersected by (y+1) . Remove the edges from the AEL, where yupper is equal to y .
4. The intersection point of the scan line with the remaining edges will change for the new scan-line. xint is updated to xint+ym . Note that xint must be stored as a real number to avoid round-off errors.
5. increment y (to the next scan line)
6. Repeat until the last scanline is drawn.

# Answer
> 1 votes
Ken's addressed scanline rendering (well) but not the occlusion problem.

So... you are asking about partially visible polys. That is where the beauty of combining scanline rendering with the z-buffer comes in.

(Using the formula of a plane to determine the depth at a given coordinate, like raycasting through every individual pixel, is unnecessarily complex and costly. Avoid that.)

Instead:

1. Determine a list of all onscreen triangles.
2. Transform the vertex by multiplying it by the projection matrix. This gives you depth at that vertex, and store that value in your depth buffer (and in a separate "vertex depth" buffer -- see my answer to your other question).
3. For each set (triangle) of 3 vertices, perform linear interpolation between the vertices to get the depth value for each intervening pixel, and store that value in your depth buffer.

Once you've done this z-buffer part, you will no longer need to concern yourself over edge sorting for potential occlusion. **In essence, the output of what I have described above is what you will use as the input to the step that Ken describes.** The z-buffer, existing as a maximum-resolution quantisation of the display surface (i.e. the screen), can accommodate for any full or partial occlusion with the highest accuracy possible -- this being resolution of the screen itself, leading to no possible depth discrepancies in the final output. PS. In software, continuous geometric approaches may be cheaper depending on scene complexity, with the z-buffer being more expensive (being a discrete / iterative approach) but still much easier to implement.

This is why hardware z-buffering is favoured: It is both conceptually simple and very fast when implemented in hardware.

---
Tags: 3d, depth-buffer, computational-geometry, rasterization
---


title: Foreach loop with 2d array of objects

text:
# Question
Title: Foreach loop with 2d array of objects
I'm using a 2D array of objects to store data about tiles, or "blocks" in my gameworld. I initialise the array, fill it with data and then attempt to invoke the draw method of each object.

```
foreach (Block block in blockList)
  {
    block.Draw(spriteBatch);
  }

```

I end up with an exception being thrown "Object reference is not set to an instance of an object".

What have I done wrong?

**EDIT:** This is the code used to define the array

```
Block[,] blockList;

```

Then

```
blockList = new Block[screenRectangle.Width, screenRectangle.Height];
  // Fill with dummy data
  for (int x = 0; x <= screenRectangle.Width / texture.Width; x++)
  {
    for (int y = 0; y <= screenRectangle.Height / texture.Width; y++)
    {
      if (y >= screenRectangle.Height / (texture.Width*2))
      {
        blockList[x, y] = new Block(1, new Rectangle(x * 16, y * 16, texture.Width, texture.Height), texture);
      }
      else
      {
        blockList[x, y] = new Block(0, new Rectangle(x * 16, y * 16, texture.Width, texture.Height), texture);
      }
    }
  }

```

# Answer
You are using a list. You've forgotten to prepopulate / structure it correctly.

Maybe you created your list so:

```
List<List<Block>> blockList = new ArrayList<List<Block>>();
//OR
ArrayList blockList = new ArrayList(); //older, non-generic ArrayList

```

Remember that a standard 1D list looks like this:

`0|1|2|3`

In your case you've created a list of lists, so you have this:

`0[]|1[]|2[]|3[]`

The square brackets represent the inner lists (of blocks) that sit within each outer list element. To clarify, when indexing your 2D list that would be `blockList[outerIndex][innerIndex]`, which would return you a block, whereas just calling `blockList[outerIndex]` *should* return you a list of blocks. However, that is probably returning `null`, and the reason is as follows...

When you create the outer array (a list of lists), C# does not implicitly create the inner lists. You need to first declare and construct the outer list `blockList` as shown above, and then before you do any real work you need to initialise that by doing

```
for (int i = 0; i < desiredNumOfRowsPerColOrColsPerRow; i++)
{
    blockList.Add(new ArrayList<Block>());
}

```

If you had chosen to use a fixed size 2D array (`Block[,] blockArray`) you would not have experienced this problem.
> 2 votes

# Answer
I see three alternatives:

* or blockList is null
* or blocklist contains null values...
* or blocklist contains values that are not of type block

I'd test with this code:

```
foreach (Block block in blockList)
{
  if (block == null)
  {
      System.Diagnostics.Debugger.Break();
  }
  block.Draw(spriteBatch);
}

```
> -2 votes

---
Tags: xna, c#, objects
---


# Question
Title: Creating practically solvable 15 puzzle inputs
I am now developing a 15 puzzle game. I know the method to detect *unsolvable* puzzles. But unlike `8-puzzle`, solution for 15-puzzle takes quite long time for some input states and can be solved within 5 seconds some other set of input states.
Now the problem is that I cannot give the user(the player), a problem for which the solution takes more than **10 seconds**(if he/she chooses to see the solution). So what I want is that when I initially shuffle the puzzle, I want to only present those puzzles which can be solved within 10 seconds. There must be some way to determine the hardness of the puzzle. I tried searching the net but could not find it.
Does anyone know a way of determining the hardness of a puzzle?
**NOTE :** I am using `A* algorithm` to find out the solution on a computer with **3GB** RAM and **2.27GHZ** processor.
**EDIT :** I have an additional requirement also. I am including a Puzzle Solver also. So based on the user's input, the *cpu* will solve the problem. Present A\* algorithm with manhattan distance as heuristic takes a lot of time. First of all I would like to know which algorithm to choose - A\* or IDA or some other. And I would like to know about other heuristics also.

# Answer
> 2 votes
The time needed to solve a 15 puzzle depends a lot on how the player approaches the problem. Those using a systematic solving method will solve *any* solvable puzzle in about a minute or two, depending on how much practice they've had. On the other hand, a systematic solution will generally take about the same time regardless of how well scrambled the puzzle is.

Meanwhile, people who *don't* use any kind of systematic approach, but just slide the blocks around randomly and hope that they'll fall into place, will probably not manage to solve any but the most trivial of puzzles in any reasonable time, if ever. If they haven't solved it in 10 moves, they probably won't manage to solve it at all.

(Solving a 15 puzzle systematically is easy enough that even new players may figure it out on their own. Just the two rules — 1) solve the puzzle in numerical order, and 2) don't disturb completed rows unless you absolutely have to — will essentially do it, even if you may need to experiment a bit to figure out details like how to get the last block in a row in place.)

Anyway, the point of all this is that the "difficulty of the puzzle" is not well defined — it depends entirely on the solver. Sure, you could use Markus von Broady's suggestion to guarantee that there exists a solution with at most *n* moves, but unless *n* is really small, most people will either fail to spot the solution or will not even try, preferring their own solution method instead.

---

**Edit:** After you clarified the question, I see that you're concerned about the time taken by the *computer* — not the *player* — to solve the puzzle. As you've noticed, using A\* to solve the 15 puzzle can take a while; the problem is that, unless the solver happens to find a particularly good solution early on, the search space quickly branches out into a huge number of partial solutions with identical scores.

The obvious solution there would be to dispense with the A\* search and instead implement a systematic solution method like the one I linked to above. Such methods won't produce an *optimal* solution, but they do produce *a* solution to the puzzle very quickly. (As a bonus, the solution they generate will be of a type which the player can feasibly imitate, whereas the optimal solutions found with A\* tend to seem "magic".)

Alternatively, you might try using A\* in stages — that is, for example, first use A\* to find a sequence of moves that solves the first row of the puzzle, ignoring the other tiles (i.e. treat them as identical and don't include them in the heuristic), then restart A\* from the result of that solution to solve the second row, and so on. (Remember that the last two rows will need to be solved together.) This should produce something similar, but possibly a bit more efficient, than the purely systematic solution.

# Answer
> 5 votes
Just start with finished puzzle, and then make let's say 10 random moves (1 for every second) of tiles to make sure the puzzle is both solvable and can be done in 10 moves. Make sure your moves don't negate previous, e.g. moving 3 tiles in "circle" or moving a tile back where it was before previous move.

KISS

Edit: A\* is not designed to help you in solving 15 puzzle. The fact that your CPU can't do it in 10 seconds show it clearly. There are better algorithms for that, probably you could find one from some programming olympics, but it's not hard to do one yourself when you know the methodology: http://www.wikihow.com/Solve-a-Fifteen-Puzzle

The absurd is, you use complex maths to generate a random puzzle and make sure it is solvable, only to use a complex algorithm to find a solution that in best scenario is an exact opposite of creating this puzzle the easy way, and even then is much more slower because of conditionals taking place.

Edit2: I see now, that your problem is to find a solution after a player moved some pieces in his attempt to solve the puzzle. In regards to my advice above, you could remember player's moves and revert them, or just reset the puzzle or indeed you would need to create an algorithm based on the link provided.

---
Tags: puzzle
---


title: Whats the right program for me?

text:
# Question
Title: Whats the right program for me?
I would like to learn C++ so I can get a job in the game industry, but there are so many options it a little confusing. I know most of you will say I should read up on C++ before attempting to program it but I learn best by doing things rather then reading. That being said I don't understand some of the thing suggested on other questions, because I've read a few trying to find whats right for me, so putting things in the simplest terms would be helpful. I've been making a couple of games 2d using gamemaker and if theres a C++ equivalent that would be perfect, but if not possible I would like an IDE that allows me to easily continue making 2d games, and is fairly simple to learn. Having a 2d sprite editor would be a nice plus but I can understand if its not every thing I want in one program

# Answer
> 3 votes
I should suggest Cocos2d-x and Unity for you.

> **Cocos2d-x**

It is based on C++ (as you would like to learn C++). It is simple, easy to learn and has multi-platform support.

Cocos2d-x is a multi-platform 2D game engine in C++, based on cocos2d-iphone and licensed under MIT. Now this engine has been expanded to iOS, Android, Bada, BlackBerry, Marmalade and desktop operating systems like Linux, WindowsXP & Windows7.

* iOS: stable, well tested on iOS 4.x ~ 5.x SDK.
* Android: stable, well tested on 2.0~4.0, based on ndk r5 ~ r8.
* Bada: stable on Bada SDK 1.0 & 2.0
* BlackBerry Playbook & BB10: stable, contribued by engineers working at RIM
* Marmalade: stable since cocos2d-x-0.11.0
* Windows: stable, tested on WinXP, Vista, Win7. Please upgrde the drive of your video card if you meet problems on OpenGL functions
* Linux: usable.

**Project Resource**

**Tutorials**

**Community Resource**

> **Unity**

If you want a better **IDE** and **everything in one program**, then i should suggest Unity.

Unity is a cross platform game engine and IDE developed by Unity Technologies, targeting web plugins, desktop platforms and mobile devices.

**Project Resource**

**Tutorials**

# Answer
> -1 votes
I suggest that you start with Python instead of C++.

Why?

If you go the Python route you just start programming - it's a mature language, it's interpreted and widely used in the game industry.

You basically write code and run it. And modify and run it.

With C++, however, you write code, compile, fix errors, link, fix more errors and finally - if you're lucky - you run your program. Really a lot of extra complexity, even for the simplest of programs. You will not only have to fight the language itself, but also spend a lot of time on learning to use the development tools (IDE, etc.)

First you need to learn how to program - and not only that, but also algorithms, good software design, etc.

Python is a more direct and immediate way to program. Definitely more joyful than with C++.

You can learn C++ later, but in the meantime check out:

PyGame or Pyglet for 2D game programming.

And then perhaps Panda3D or PythonOgre for 3D programming.

And, once you got some solid programming skills, you'd be ready to move to C++.

Python or Java is what you learn in introductory computer science classes. Sometimes it's C, but almost never C++. C++ is a powerful tool, I just can't recommend it as your first real programming language.

Python is also extremely well documented - just type help(object) into the Python shell. Another reason to go with Python. It's also the fastest growing language currently. ANd as of October 2012, Python ranks at position 8 in the TIOBE Programming Community Index.

---
Tags: c++, 2d
---


title: Basic Use of ApplyImpulse

text:
# Question
Title: Basic Use of ApplyImpulse
I am trying to apply a force to a bunch of b2\_dynamicBodys, but it seems to only work for a random number of items and then stops with an error.

```
     //create some items to move
     bodyDef.type = b2Body.b2_dynamicBody;
     for(var i = 0; i < 5; ++i) {
        fixDef.shape = new b2PolygonShape;
        fixDef.shape.SetAsBox(1,1);
        fixDef.friction = 1;
        fixDef.restitution = .1;
        bodyDef.position.x = Math.random() * 10;
        bodyDef.position.y = Math.random() * 10;
        bodyDef.linearDamping=1;
        bodyDef.angularDamping=.8;
        itemsArray.push(world.CreateBody(bodyDef).CreateFixture(fixDef));  // store for later
     }

```

then i try to apply a force later with:

```
angle = 20;
for (var xIdx=0; xIdx<itemArray.length; xIdx++) {
    itemsArray[xIdx].GetBody().ApplyImpulse(new b2Vec2(50*Math.cos(angle*Math.PI/180),50*Math.sin(angle*Math.PI/180)););
}

```

the error I receive is

```
TypeError: 'undefined' is not an object (evaluating 'c.x')

```

Is there something wrong with saving the items for later use when I am creating them? Does anyone know what is causing this.

# Answer
> 1 votes
Is diceArray.length used in this code:

```
for (var xIdx=0; xIdx<diceArray.length; xIdx++) {

```

the same as itemsArray.length when referencing itemsArray in the same loop?

```
itemsArray[xIdx].GetBody()....

```

So, itemsArray size is definitely 5, is diceArray size 5 too?

Edited now jfiddle source given: ApplyImpulse requires 2 parameters and you are only passing in 1.

I added {x:200,y:200} and all is fine

```
diceArray[xIdx].GetBody().ApplyImpulse(actionVec, {x:200,y:200});

```

---
Tags: javascript, box2d
---


title: Java game object pool management

text:
# Question
Title: Java game object pool management
Currently I am using arrays to handle all of my game objects in the game I am making, and I know how terrible this is for performance. My question is what is the best way to handle game objects and not hurt performance?

Here is how I am creating an array and then looping through it to update the objects in the array:

```
public static ArrayList<VboCube> game_objects =  new ArrayList<VboCube>();
/* add objects to the game */

while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
        for (int i = 0; i < game_objects.size(); i++){
            // draw the object
            game_objects.get(i).Draw();
            game_objects.get(i).Update();
            //world.updatePhysics();
        }
}

```

I am not looking for someone to write me code for asset or object management, just point me into a better direction to get better performance. I appreciate the help you guys have provided me in the past, and I dont think I would be as far along with my project without the support on stack exchange!

# Answer
> 1 votes
As far as storing and retrieving game objects is concerned, you could use a native array but an ArrayList is already nearly as fast as it gets.

Now I'm making a guess, not knowing what your list of game objects contains nor how the objects are drawn and updated, but I'd venture that maybe you do not need to update and draw all objects on every frame. That or the draw or update code itself is inefficient.

HTH

---
Tags: java, 3d, lwjgl, object-pools
---


title: What is the XACT API?

text:
# Question
Title: What is the XACT API?
I wanted to use DirectMusic in my game, but it's not in the June 2010 SDK, so I thought that I had to use DirectSound. Then I saw the `XAudio2.h` header in the SDK's include folder and found that XAudio2 is the replacement for DirectSound. Both are low-level.

During my research I stumbled across the XACT API, but can't find a good explanation on it. Is XACT to XAudio2 what DirectMusic was to DirectSound? By which I mean, is the XACT API a high-level, easier-to-use API for playing sounds that abstracts away the details of XAudio2?

If not, what is it?

# Answer
XACT is a high-level API for audio playback. XACT is implemented in terms of differing lower-level APIs on various platforms, some of which are actually deprecated. DirectSound, for example, is used to implement XACT on older version of Windows and DirectSound itself is deprecated.

On the 360, XACT is implemented in terms of the Xaudio stack; it's thus technically a cross-platform API, although not in the same fashion (as in, not supported by as many platforms as) something like fmod.

You can use XACT via XNA on the 360, and in fact that remains the last current SDK of any type (as of this writing) to support the API -- it's use is no longer supported on Windows as of Windows 8 (June 2010 was the final release of the DirectX SDK, the components formerly provided by that SDK have been integrated into the Windows SDK itself, and the latest version of that SDK removes support for XACT on Windows).

In the sense that XACT and DirectMusic were both built on DirectSound (and are now both deprecated on Windows), they are analogous. However, XACT only ran through DirectSound on XP -- on Vista and 7, it ran through the OS's rebuilt audio stack, primarily the Audio Session API.
> 2 votes

---
Tags: xaudio2, xact
---


# Question
Title: What is a fast way to darken the vertices I'm rendering?
To make a lighting system for a voxel game, I need to specify a darkness value per vertex. I'm using GL\_COLOR\_MATERIAL and specifying a color per vertex, like this:

```
glEnable(GL_COLOR_MATERIAL);

glBegin(GL_QUADS);

glColor3f(0.6f, 0.6f, 0.6f);
glTexCoord2f(...);
glVertex3f(...);

glColor3f(0.3f, 0.3f, 0.3f);
glTexCoord2f(...);
glVertex3f(...);

glColor3f(0.7f, 0.7f, 0.7f);
glTexCoord2f(...);
glVertex3f(...);

glColor3f(0.9f, 0.9f, 0.9f);
glTexCoord2f(...);
glVertex3f(...);

glEnd();

```

This is working, but with many quads it is very slow.. I'm using display lists too. Any good ideas in how to make vertices darker?

# Answer
The problem here, almost certainly, is not that you're "darkening" your vertices by specifying the vertex colors. The problem is more likely to do with how you're rendering everything in general -- you appear to be using immediate mode in your code sample, and although you claim to be using display lists which are somewhat better, you're likely going to want to switch to VBOs as suggested by bobobobo.

However, your performance issue could be somewhere else entirely, for example, you may not be culling your voxels as aggressively as you could. You're not providing enough information to answer the question about your poor render performance, though.
> 3 votes

---
Tags: opengl, lighting, lwjgl
---