title: Best 3D Physics Engine to use with Ogre

text:
# Question
Title: Best 3D Physics Engine to use with Ogre
I am looking for a good physics engine to use with an Ogre game I'm writing.

I would prefer for it to be free, open source, mature, simple to use, easy to learn, and flexible.

I'm currently thinking of using either Newton, Bullet or ODE.

What are the general pros/cons of each?

# Answer
To quote the Ogre forums on the matter.

> Yeah, it's hard to point to any one engine as definitely the best, since they are all quite different. They have different collision shapes (Havok has cylinders, PhysX doesn't), different joints (I think Newton had a corkscrew joint which Havok might have too, but nothing else does) and various other issues. Then there's the api, Newton is based entirely on callbacks (which I don't like), Havok is painfully SSE obsessed (get used to vector math which looks like C rather than C++. Good for performance, but is annoying to use), PhysX needs that stupid driver crap otherwise it's dll won't start, etc.
>
> The most feature filled one is Havok. The animation system alone is enough reason for it (full skeleton animation with physics interaction, skeleton retargetting, inverse kinematics, export tools, etc). Plus if you pay massive amounts of cash you can get Havok Destruction, Havok AI, Havok Behaviour and other bits. (The basic Havok physics and animation components are free for pc).

In short, it will ideally come down to API differences, because overall they are all performing the same operations; minus some performance differences.

What matters most is how *YOU* like them, if you can't use it to its best ability, the spot differences won't matter.

If you find the Physics engine to be your biggest bottleneck (from measurement of course), then later you can weight the odds and ends against each other. I suggest for now you find one which is easiest for you to learn.

Personally, I found Bullet pretty straight forward and simple to learn; it has a nice license, an active community and is not going to be a cause for concern with performance.
> 4 votes

---
Tags: c++, physics, ogre, bullet-physics
---


# Question
Title: Game Asset Storage - Graphics, 3D Models, Sounds
I've recently started completing games and accumulating "assets" -- graphics, sound effects, textures, 3D models, etc. that I can build on and reuse from game to game.

**Is there a great, free place I can store an unlimited amount of this content?** Ideally, I would like to categorize my content (by game) and tag it (eg. icons, characters, sound-effects, soundscapes). Unlimited storage is key, because I want everything stored in one place.

Also, most of my content is strange file formats; graphics are vector done in Flash (.FLA), or in GIMP (.XCF); I don't know what 3D model formats I'll use. Sounds will be .MP3.

Where can I store this stuff?

**Edit:** Not quite 100% dupe, but quite similar to Assets Management, database or versioning system?

# Answer
I would just keep the content carefully sorted into folders for what you call "tags" and subfolders by game. Maybe something like this:

* /assets
    + /2d
        - /spritesheets\_tilesets (i.e. combination images)
            * maybe even a sub folder here for humans, animals, etc.
        - /textures (tileable images)
            * you could have subfolders here for sizes, if they're all square power-of-two textures
        - /animated
            * this would be gifs; animation spritesheets would go in spritesheets\_tilesets
    + /3d
        - maybe different model types? at the very least, maybe two folders here for organic and non-organic, if you have any mocap files they should have their own subfolder obviously, but for the most part 3D models are 3D models. Name them as best as possible, and where necessary put a screenshot of the model with the same name in the same folder so that you can quickly see models without having to load them in your modeling program.
    + /audio
        - /music
            * if you can come up with different mood types or something, that might be good subfolder candidates here
        - /sound effects
            * again, maybe have folders by type - explosion, shoot, ...
        - /voice
    + /video
        - i can't think of any subfolders for video. broken out by game is probably fine.
    + /text
        - /ascii art
        - anything else you think might be an asset

Notes:

* In the "deepest" folder of each of the above things, that's where you should break it out by game if you want.
* Remember, as you fill up the folders, that you can put files in any folder; you don't have to only put files in the deepest folder. A great example is the 2D folder; you're going to have content which doesn't fit the three subfolders I came up with, and probably can't be grouped with anything else, so just leave it in the 2D folder.
* However, to reduce mess, every single file should be properly named. Come up with a consistent naming style and rename all your files to match this style. If you want to capitalize the first letter of every word in a filename, do that for everything; if you don't want files to have spaces but instead replace them with underscores, be consistent with that across all your files. This will help the readibility, both of browsing these folders and of any code or data files that have to list these filenames. Plus it helps you guess at a filename and not have to try variations of capitalization and underscores/spaces/nothing.

Now, assuming you are okay with the above method of organization, you just have to manage and back up a folder! You can use any of many cloud storage solutions to do this. You could have a server somewhere and FTP everything to/from it (don't use a web server; webhosts don't like being used as backup solutions and have no reservations in deleting files if they see you using it as pure backup). One solution I highly recommend you check out is Amazon S3; this would truly be unlimited storage, as you ask for, at a cost. But the price is very low. Or, you can simulate unlimited storage by buying a large hard drive(s) and just keeping everything on it (back it up somehow of course!!). Then you have the benefit of always having fast access to your data, whereas S3 would require a (fast) internet connection.
> 3 votes

# Answer
**unlimited** is a difficult thing. But you don't really mean unlimited, you just mean *really big quota*.

First, compress everything well. On Windows, simply enable 'compressed folders' for the folder where you are placing things. Or to compress as well as possible use a proper archiver such as 7zip. The archive approach has the advantage of being a nice single file that is easy to send to other systems, and typically uses 'solid' compression so the ratio can be substantially higher than a Windows compressed folder; however, it is also much slower and non-transparent to work with.

The best place to keep large amounts of data is locally, but keep multiple copies. External hard-drives are very cheap these days. You can put a lot on a DVD every few months and then put that DVD somewhere safe.

But if you also want off-site backup - good for robust disaster recovery - then email them to your gmail account (using a filter to hide them from normal view, e.g. prefix all subject lines with CRZY or something else that doesn't occur in normal emails). Put some context into the subject and message body so you can search them well using the gmail interface later to find them.

After you have filled up the 7GB or so that gmail offers, you may consider a paid solution.

(gmailFS solutions are not robust and dependable)
> 1 votes

---
Tags: assets, asset-management, storage
---


# Question
Title: Moving objects colliding when using unalligned collision avoidance (steering)
I'm having trouble with unaligned collision avoidance for what I think is a rare case. I have set two objects to move towards each other but with a slight offset, so one of the objects is moving slightly upwards, and one of the objects is moving slightly downwards.

In my unaligned collision avoidance steering algorithm I'm finding the points on the object's forward line and the other object's forward line where these two lines are the closest. If these closest points are within a collision avoidance distance, and if the distance between them is smaller than the two radii of the two object's bounding spheres, then the objects should steer away in the appropriate direction.

The problem is that for my case, the closest points on the lines are calculated to be really far away from the actual collision point. This is because the two forward lines for each object are moving away from each other as the objects pass. The problem is that because of this, no steering takes place, and the two objects partially collide.

Does anyone have any suggestions as to how I can correctly calculate the point of collision? Perhaps by somehow taking into account the size of the two objects?

# Answer
> 6 votes
This is by far the best ball to ball collision detection article I have come across.

Pool Hall Lessons: Fast, Accurate Collision Detection Between Circles or Spheres

# Answer
> 0 votes
You don't want to find the closest point.

You want to find the point on the lines where the distance is equal to the combined radii of both spheres.

# Answer
> 0 votes
If I'm understanding your question correctly you can simply just use a Sphere vs Sphere intersection test, like AttackingHobo has suggested.

The math to do such a test is as follows (correct me if I'm wrong, it's been awhile). Also, this is considering that your spheres have a center and a radius variable each.

The formula for checking goes something like this:

```
distanceOfSpheres <= sumOfRadii^2

```

You have a sphere vs sphere intersection. This is pretty simple, let's see what it looks like in code!

```
bool sphereIntersectTest(BoundingSphere* s1, BoundingSphere* s2)
{
   Vector3 distance;

   // Get the distance between each sphere, center is a Vector3 type
   distance = (s1->center - s2-> center);

   // Determine the sum of both radii
   float radii = (s1->radius + s2->radius);

   // Determine if we have an intersection
   if (distance.length <= (radii * radii))
      return true;
   else
      return false;
}

```

Again, I think that this is the correct answer you may be looking for. If anyone knows that this is wrong please correct me, since it has been a while since I've done this math.

# Answer
> 0 votes
Ok, hopefully this makes sense... Get the vectors of the balls and calculate their collision point, call this p1. Find the angle between the 2 vectors, call this a1. At a1/2 draw a line, this will be in the exact middle in degrees between the two vectors. You need the location on this line where sin(a1/2) = (radius1 + radius2)/2. If this picture is visualized in my head right, this is where the collision occurs. Sorry if this is wrong... its late.

---
Tags: collision-detection, vector, movement, linear-algebra
---


title: Are Loose Octrees Too Loose?

text:
# Question
Title: Are Loose Octrees Too Loose?
I've been reading Real-Time Collision Detection and for loose octrees it recommends expanding each node's AABB length by a factor of 2, making its expanded volume 8 times as large. I am surprised that it needs to be this large, and there must be quite a lot of overlap and unnecessary child node traversals due to this large size. Within the top few levels of the octree, triangles are generally very small compared to the node's volume so I don't see any problem with making their scaling factor much less than 2, perhaps even 1.1 (And then ramping it back up to 2 after a certain depth.)

*This is for an octree holding static background geometry so I'm not concerned with how long building it takes.*

Is there a mathematical reason for the radius ratio being two?

# Answer
The reason that the scaling factor is two is because this is the *absolute minimum* scaling factor that *guarantees* an at-most-cell-sized object can be placed within a single cell that contains it's centre point.

This is easy to visualise - imagine the centre point of a cell-sized object is at the very edge of a given cell - then the far edge of the object will be 1/2 of a cell width outside the cell. Add this boundary to both sides and you get your factor of two...

You are right that this does create overlap and can cause multiple child traversals, but you can avoid "unnecessary" traversals by paying attention to your bounding box as you descend the octree. In practice, you won't need to go very deep most of the time to eliminate the possibility of a collision.

You *could* reduce the scaling factor on the top level octree nodes but **only if** you can guarantee that no object would ever be large enough to extend beyond the size of this margin. There might be a small benefit in doing this, but as soon as you get down a few levels you will need your scaling factor of two anyway - which will account for the vast majority of nodes in the octree.
> 8 votes

---
Tags: collision-detection, octree
---


# Question
Title: For 2D tiled maps is all object and NPC data loaded into memory when the map is loaded?
I'm creating a text RPG in Java, but I think this applies for a GUI as well with regard to the data structure. Each Level is a tiled map. Each Tile object has an (X,Y) coordinate, and references to adjacent tiles, but my question is with regard to storing object and NPC data on that Tile object. Depending on the size of the map I'm loading, this seems like a lot to load, but if that is the commonly accepted practice then I'll go with it.

# Answer
I'm not sure where the problem is that you're asking about. If you need the data, you have to load it. I would personally keep NPCs in a separate list, and track them separately from all the actual tile data. That's how I make these kinds of games.

Because you only need to draw the tiles on-screen; but entities (NPCs) may have collision logic, events, etc. and should always be tracked, regardless of their position.

If you're worried about performance, then I say, don't; just code it, and if problems arise, you have working code to profile and optimize.

**Edit:** The way that I would code it would be to have a 2D array of tiles; each tile has the XY coordinates of the image that it displays, a "walkable" attribute, etc. NPCs/entities would be kept in a separate list, and they would either hold a tile XY coordinates for the tile they're stepping on, or hold a reference to a Tile object with an X and Y.
> 2 votes

---
Tags: 2d, java, data
---


title: Rent-a-Coder style site for artists

text:
# Question
Title: Rent-a-Coder style site for artists
My Google-fu is failing me: is there a site in the same vein as Rent a Coder, but for hiring artists? In particular, I'm looking for a site which fits the following criteria:

* Allows me to specify the style and scope of the work I'm looking for beforehand
* Allows artists to "bid" on the project, including time and cost estimates
* Showcases the work of the bidding artists so that I can see what kind of quality I can expect from each bidder
* Is designed specifically for smaller, short-term projects or one-off graphics

It seems that the original incarnation of Rent a Coder is dead (the above seems to be some sort of knockoff), and that it was probably killed by an unsustainable market full of unrealistically low bids for large projects by unskilled and unqualified "coders." That being the case, such a site might be poorly suited to art as well.

The reason I'd like such a site, though, is that as a "bedroom programmer" with a small budget and little experience in this sort of thing, I have no idea where I should be looking for art or how much I should reasonably expect to pay. Thus, a site with good competition where market prices are somewhat transparent would be ideal.

Any other suggestions about how best to acquire custom artwork as an indie developer are also appreciated.

# Answer
> 1 votes
If you're interested in artists, the best I can recommend is oDesk. I used it once for an artist, and it's fairly good, because it allows you to track their time usage per ten minutes (it takes screen-shots of what they're doing) and it bills by the hour.

There are a fair number of artists there; when I posted a request, I got around 10-20 proposals. (I asked for a nice 2D title screen.)

# Answer
> 4 votes
It sounds like you're after assets rather than an actual artist. If that's the case, then I'd suggest TurboSquid.

Rather than separate artists, it has a whole load of art assets, where some you have to pay for, and others are free (generally "you get what you pay for" applies to the site). The advantage of this site is that you can see exactly what you're getting before entering into any agreement with the artist.

# Answer
> 1 votes
Here is a blog post from Danc @ Lost Garden trying to hook up artists with developers. Karnak games has a great "how-to" on hiring game artists.

# Answer
> 0 votes
There are a few sites like what your describing. I can't remember them but here is one of them.

http://flashgameart.com/artists/

# Answer
> 0 votes
here two of the main ones:

http://www.crowdspring.com

http://www.99designs.com

---
Tags: art, assets, hiring, human-resources
---


title: How to store a shmup level?

text:
# Question
Title: How to store a shmup level?
I am developing a 2D shmup (i.e. Aero Fighters) and I was wondering what are the various ways to store a level. Assuming that enemies are defined in their own xml file, how would you define when an enemy spawns in the level?

Would it be based on time? Updates? Distance?

Currently I do this based on "level time" (the amount of time the level is running - pausing doesn't update the time). Here is an example (the serialization was done by XNA):

```
<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:level="pekalicious.xanor.XanorContentShared.content.level">
  <Asset Type="level:Level">
    <Enemies>
      <Enemy>
        <EnemyType>data/enemies/smallenemy</EnemyType>
        <SpawnTime>PT0S</SpawnTime>
        <NumberOfSpawns>60</NumberOfSpawns>
        <SpawnOffset>PT0.2S</SpawnOffset>
      </Enemy>
      <Enemy>
        <EnemyType>data/enemies/secondenemy</EnemyType>
        <SpawnTime>PT0S</SpawnTime>
        <NumberOfSpawns>10</NumberOfSpawns>
        <SpawnOffset>PT0.5S</SpawnOffset>
      </Enemy>
      <Enemy>
        <EnemyType>data/enemies/secondenemy</EnemyType>
        <SpawnTime>PT20S</SpawnTime>
        <NumberOfSpawns>10</NumberOfSpawns>
        <SpawnOffset>PT0.5S</SpawnOffset>
      </Enemy>
      <Enemy>
        <EnemyType>data/enemies/boss1</EnemyType>
        <SpawnTime>PT30S</SpawnTime>
        <NumberOfSpawns>1</NumberOfSpawns>
        <SpawnOffset>PT0S</SpawnOffset>
      </Enemy>
    </Enemies>
  </Asset>
</XnaContent>

```

Each Enemy element is basically a wave of specific enemy types. The type is defined in EnemyType while SpawnTime is the "level time" this wave should appear. NumberOfSpawns and SpawnOffset is the number of enemies that will show up and the time it takes between each spawn respectively.

This could be a good idea or there could be better ones out there. I'm not sure. I would like to see some opinions and ideas.

I have two problems with this: spawning an enemy correctly and creating a level editor. The level editor thing is an entirely different problem (which I will probably post in the future :P).

As for spawning correctly, the problem lies in the fact that I have a variable update time and so I need to make sure I don't miss an enemy spawn because the spawn offset is too small, or because the update took a little more time. I kinda fixed it for the most part, but it seems to me that the problem is with how I store the level.

So, any ideas? Comments?

Thank you in advance.

# Answer
> 4 votes
One way to do this would be to base the spawn not on time but on horizontal distance traveled (assuming sidescrolling). You can store your enemy waves in a queue with a trigger distance; when your player's distance traveled is greater than the trigger distance of the object at the front of the queue, pop it from the queue and spawn it.

This solution would lend itself more to integration with a graphical level editor than a time-based solution. It'd make it much easier to match up specific points along your scrolling background with when the enemies spawn.

# Answer
> 2 votes
I suggest you study the code of PowerManga as a reference. They have two kind of levels: side-scrolling (tyrian-like) levels where things are positioned at a specific distance from level start and other things are randomly generated, and "still" levels (à la galaga) where one wave is parsed only after the previous one has finished its pattern.

Wave patterns can of course efficiently be planned by successive bezier curves (wikipedia page has a neat animation to explain that).

If I can afford a final comment, I'd completely drop XML here in favour of something more expressive, easier to maintain and more useful in game programming such as a LUA script.

HTH.

# Answer
> 0 votes
Consider procedurally generating enemies. I know it's quite different from the answer you want, and it indirectly solves the problem completely.

If I were to do this, I would assign each enemy unit a "points" value of how difficult it is, then assign levels some number of points -- 100 points are worth a hundred 1 point enemies, or one 100-point enemy, or anything in-between.

You would probably need to constrain this a bit so that you don't get a 100-point boss on the first level, or that you have some minimum number of enemies, and you probably want to periodically poll the list of enemies left and pull the next one on-screen.

You could take it a step further by having formations: collections of positions and points, eg. seven one-point enemies in a single line (row or column), or a five-point flanked by two 3-points.

---
Tags: levels, data, xml, shoot-em-up
---


# Question
Title: XNA Sprite mouse selection with layered/overlapping sprites
If I use mouse coordinates to select a sprite does XNA provide a built in way to return the top-most sprite on the screen at a coordinate?

I am trying to highlight the selected sprite, but when iterating through my sprites at the specific mouse location there can be multiple sprites found. The way my game works any one of the sprites found is valid to be on top.

# Answer
> 2 votes
I don't believe XNA has a built in way to do this. You should definitely implement some kind of ordering or layering system so one sprite gains precedence over the others (unless your game needs multiple sprites to be selected at once from the same mouse click). Once a sprite processes the selection no other sprites should be given the chance to.

# Answer
> 2 votes
It sounds like you need to assign a "depth" or "Z" value to your sprites that defines which is "on top" of each other. Then you would iterate through the sprites as usual but the sprite returned would have the highest "Z" value.

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


# Question
Title: Triangle Strips and Tangent Space Normal Mapping
Short: Do triangle strips and Tangent Space Normal mapping go together?

According to quite a lot of tutorials on bump mapping, it seems common practice to derive tangent space matrices in a vertex program and transform the light direction vector(s) to tangent space and then pass them on to a fragment program. However, if one was using triangle strips or index buffers, it is a given that the vertex buffer contains vertices that sit at border edges and would thus require more than one normal to derive tangent space matrices to interpolate between in fragment programs.

Is there any reasonable way to not have duplicate vertices in your buffer and still use tangent space normal mapping?

Which one do you think is better: Having normal and tangent encoded in the assets and just optimize the geometry handling to alleviate the cost of duplicate vertices or using triangle strips and computing normals/tangents completely at run time?

Thinking about it, the more reasonable answer seems to be the first one, but why might my professor still be fussing about triangle strips when it seems so obvious?

# Answer
> 7 votes
Short Answer: Yes, you need to average the tangent space vectors for each vertex just like you do with normals to achieve smooth shading. For example if a vertex is shared by 3 triangles then the final tangent frame is the average of the 3 face tangent frames.

Long Answer: These days it is generally considered best practice to use index buffers and not worry about triangle strips. The reason for this is twofold. Firstly if your geometry is optimized for vertex caching an index buffer prevents *most* duplicate vertex scenarios and will be just as fast as triangle strips. Secondly making tons of pipeline changes and draw calls can dramatically affect performance. A mesh converted into triangle strips will probably result in the need for multiple draw calls as it's unlikely your entire mesh can be converted into one triangle strip and depending on the architecture of your engine may even require multiple vertex buffers.

Personally I prefer to precompute tangent frames and store them with the mesh data instead of calculating them in shaders. The reason for this is that 3d modelling packages such as Maya and 3DS MAX have very accurate and elaborate methods of generating the correct normals, uv's, tangents, and bitangents and it's much easier to just import them. If you develop your own method and it differs significantly from these art packages your artists are going to start asking you why the lighting on their models looks all messed up in-game because it was the way they wanted it in Maya.

---
Tags: graphics-programming, normals, efficiency
---


# Question
Title: Can't understand these UV texture coordinates (range is NOT 0.0 to 1.0)
I am trying to draw a simple 3D object generated by Google SketchUp 8 Pro onto my WebGL app, the model is a simple cylinder.

I opened the exported file and copied the vertices positions, indices, normals and texture coordinates into a .json file in order to be able to use it on javascript. Everything seems to work fine, except for the texture coordinates which have some pretty big values, like 46.331676 and also negative values. Now I don't know if I am wrong, but isn't 2D texture coordinates supposed to be in a range from 0.0 to 1.0 only?

Well, drawing the model using these texture coordinates gives me a totally weird look, and I can only get to see the texture properly when I am very close (not really me, the cam) to the model, as if the texture has been insanely reduced in it's size and repeated infinitely across the model's faces. (yeah, I am using GL\_REPEAT on that texture wrap thing)

What I noticed is that if I get all these coordinates and divide them by 10 or 100 I get a much "normal" look, but still not in the 0.0 to 1.0 range.

Here's my json file: http://pastebin.com/Aa4wvGvv

Here are my GLSL Shaders: http://pastebin.com/DR4K37T9

And here is the .X file exported by SketchUp: http://pastebin.com/hmYAJZWE

I've also tried to draw this model using XNA, but still not working. Using this HLSL shaders: http://pastebin.com/RBgVFq08

I tried exporting the same model to different formats, collada, fbx, and x. All those yields the same thing.

# Answer
You are correct UV's typically go from 0-1 though as David X mentioned this isn't a requirement. In your case the issue is the frequency of the SketchUp generated UV coordinates. For example if your Y axis (V coordinate) goes from 0 to 46 then that texture, if wrapping is enabled, will repeat 46 times in the V direction. Wrapping also makes it look smaller because you have to duplicate the image many times across the same surface area. Re-exporting as FBX or Collada doesn't do anything to resolve the issue because it's the same UV's either way. To fix this you need to go back to SketchUp and change how it's generating UV's for the cylinder. Perhaps you can specify the UV range yourself or maybe you have to change how the geometry is parameterized. I've never used SketchUp so I don't know exactly how it handles those sorts of things.

Lastly it looks like the vertex winding of the cylinder may be the opposite of your cubes. Graphics API's like OpenGL and DirectX use triangle vertex winding to determine which direction the triangle is facing. This is how they perform backface culling - not rendering the triangles facing away from the camera as an optimization. In the case of your cylinder it appears that the view is looking into the cylinder because the triangles closest to the camera are facing the wrong direction. Once again this is an issue that would need to be resolved in SketchUp and it can be verified by looking at the direction of the face normal for each triangle (it should be pointing outward, not inward).
> 8 votes

# Answer
If you want your uv coordinates to be exactly between 0 and 1, you could use a scale matrix for your model.

So on loading your model, you could check for your max u and v coordinate and create a scaling matrix that will make it more "normal". So that will replace your manual scaling of 10 or 100. So to let it fit, you will need to scale your uv coordinates down to \[0,1\].

```
|1/uMax|0     |
|0     |1/vMax|

```

Of course this is just a workaround and you could better find a way to set Sketchup in the right settings (I think your exporter or Sketchup itself goes wrong here). But if it doesn't work out for you, create your post-loading-processor and save a texture scaling matrix.
> 2 votes

# Answer
(Texture coordinates can definitely be outside of 0-1.) I think this is just OpenGL being weird. IIRC, Spheres use texture coordinates that put the 0-1 square on ~1/16 of the surface, and I wouldn't be suprised if Cylinders do something similar. Fix-wise, you might have to write your own cylinder code, issuing the appropiate texture coordinates.
> 1 votes

# Answer
Looks like SketchUp isn't normalizing your texture coordinates, or using a metric of its own. Having texcoords \< 0 or \> 1 and GL\_REPEAT as texture wrapping means that the texture will be scaled down to fit the geometry and repeated horizontally and vertically.

Try importing the mesh in another modelling package (MilkShape, Blender) and fixing the uv map from there.
> 0 votes

---
Tags: opengl, textures, models, webgl, uv-mapping
---


# Question
Title: How to refresh allegro textprintf_centre_ex text upon keypress?
I'm trying to print the coordinates of a drawn square upon movement. The problem is that the x value doesn't get refreshed on screen.

This is the code I have:

```
#include <allegro.h>

BITMAP *buffer;

void update_screen(void)
{
    blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); // blit the buffer to the screen
}

int init_double_buffering()
{
    // create the memory buffer
    buffer = create_bitmap(SCREEN_W, SCREEN_H);

    if(!buffer)
        return FALSE;

    return TRUE;
}

int main()
{
    int x, y;

    // install allegro, set graphics mode, etc
    allegro_init();
    install_keyboard();

    set_color_depth(32);
    if (set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640,480, 0,0))
    {
        allegro_message("Unable to set graphics mode.\n");
        return 1;
    }

    // initialize page flipping
    if (!init_double_buffering())
    {
        set_gfx_mode(GFX_TEXT,0,0,0,0);
        allegro_message("Unable to initialize page flipping.\n");
        return 1;
    }

    // default coordinates for the rectangle
    x = SCREEN_W / 2 - 5;
    y = SCREEN_H / 2 - 5;

    // main game loop
    while (!key[KEY_ESC])
    {
        // game logic
        if (key[KEY_LEFT] && x) --x;
        if (key[KEY_RIGHT] && x < SCREEN_W-10) ++x;
        if (key[KEY_UP] && y) --y;
        if (key[KEY_DOWN] && y < SCREEN_H-10) ++y;

        // you draw everything to buffer
        clear(buffer);
        rect(buffer, x,y, x+9,y+9, makecol(255,255,255));
        textprintf_centre_ex(screen, font, SCREEN_W / 2, SCREEN_H/2,
               makecol(255, 255, 255), -1,
               "X value is %d!",
               x);

        // show the offscreen page
        update_screen();
    }

    return 0;
}
END_OF_MAIN()

```

# Answer
> 5 votes
The Problem is that you draw your text on the screen and then blit the doublebuffer over that.

Simply change the first argument to textprintf\_centre\_ex from screen to buffer and it works like a charm.

---
Tags: c, text, allegro
---


# Question
Title: Map file format for Real-time strategy game
I am planing to create a 2D RTS game on iPhone using cocos2d, besides the tile map, any other suggestion for storing the map details for the game?

Would be nice if a GUI editor is also provided.

# Answer
A good idea is to build a map editor into the game, invoked with a hotkey when the game is paused in debug builds. It allows you to quickly edit the map during development gameplay and will save you masses of time.

And it might grow into an extra feature of the game if you polish it enough later for end users.
> 3 votes

# Answer
While a dedicated map editor is great to have, it's also quite time consuming to make. The #1 easy shortcut is to define your map format as a subset of a bitmap image format and use a bitmap editor to make the maps. How well this works depend greatly on the requirements for the map, it's easy if the number of different options for each tile fit into a small palette, if not you may have to use multiple pixels for each tile, which complicate the matter and make the solution less optimal.
> 3 votes

---
Tags: iphone, cocos2d-iphone, ios, rts, map-editor
---


title: 2D Platform Game Jumping

text:
# Question
Title: 2D Platform Game Jumping
I'm currently writing a game in XNA for fun which uses C#. I have got my sprites loaded and when the character moves right he looks like he is running right and when he moves left he looks like he is running left.

I been looking everywhere for a good coding example for how to create a jumping ability. I have read all the physics stuff that I can stand and it doesn't help when I can't figure out how to use say space bar to jump yet can't keep them from using space just jump again until they land.

# Answer
Create a variable, canJump and set it to true whenever your sprite is on a jumpable surface. If you are using a negative y velocity every frame then letting collision detection prevent you from falling through the ground then you can set canJump whenever the players sprite collides with terrain. Whenever the player jumps just set canJump to false and it will remain that way until collision detection changes it back
> 8 votes

# Answer
Define this:

```
int gravity = 2, jump=50, spX=20,spY=20, surface=200;
bool click = false;
bool canJump = true;
Texture2D sprite;
MouseState m;

```

---Update---

```
m = Mouse.GetState();

        if (spY < surface)
        {
            spY += gravity;
        }
        else
        {
            if (spY == surface)
            {
                canJump = true ;
            }
        }
        if (m.LeftButton == ButtonState.Pressed)
        {
            click = true;
        }
        if ((click) && (m.LeftButton == ButtonState.Released))
        {
            if (canJump)
            {
                click = false;
                spY -= jump;
                canJump = false;
            }
        }

```

---EndUpdate---

---Draw---

```
spriteBatch.Draw(sprite,new Vector2(spX,spY),Color.White);

```

---EndDraw---

I just tried it, it works fine
> 3 votes

# Answer
Take a look at this tutorial: http://www.xnadevelopment.com/tutorials/thewizardjumping/thewizardjumping.shtml the site is also full of really useful tutorials related to XNA.
> 2 votes

# Answer
What I've done int the past, is have your character hold a velocity in each direction. When I want a jump, I simply say vel\_y -= (jump velocity here). And of course I have a constant gravity.

One other really nice feature you can should look into implementing is the whole concept of "the longer you hold the button the higher you go". I Hate it when games only jump one single constant variable, and don't allow me to have some feeling of control.

Oh, and wall jumps are cool =\]
> 0 votes

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


title: Finding testers

text:
# Question
Title: Finding testers
I am making my first indie retail game, I hosted a prototype on www.agfgames.com but I am struggling to find testers...

Being a company made only of myself, and having no budget (actually, I have huge debts because of college), I cannot hire a testing service, but I am failing to find testers on my own, does not matter how much I try... Sometimes I spend half of the week in marketing, trying to find testers...

All the ones that tested the game, praised it, thus it is not fault of the game, but fault of me not finding the testers around... But since all the few ones that I found praise the game, this mean that I am not getting meaningful feedback...

# Answer
If you are playtesting early builds, it's good to test in-person. You can actually observe players getting frustrated, discovering exploits, or having fun in real-time, and it's easier to ask them questions immediately after they are done testing. For indie games, simpler solutions are often better.

Put your game on a laptop and go to a place where people are hanging out. If it's summer, head for an ice-cream shop and ask people to play your game. Coffeeshops are great for this too. Check out the location beforehand and verify that there are power outlets and that you can have a conversation without yelling, though.

You can put up paper posters at local colleges and schools. I strongly recommend reaching out to middle-schoolers, as they have the skills to play pretty complex games with none of the shyness. (They will tell you *exactly* why a game sucks to your face.) Science/technology/math teachers may let you test a game with their students in exchange for a talk about game development or programming.

Once you're starting to test for stability, definitely put together a friends-and-family email list and send them builds. People who know you will be more likely to get back to you quickly, especially if you need esoteric details from them, such as their processor and graphic specs.

Of course, you want to be able to reach out to total strangers as well, but don't ignore low-hanging fruit.
> 6 votes

# Answer
Try some social websites. Reddit is a really good place to get people to try out your product (if it's interesting enough). Just make sure you find the right subreddit(s) to post it under.

Or try some of your inner circle on Twitter/Facebook/etc.
> 2 votes

# Answer
My company puts up ads on Craigslist and we seem to generally find people. Mention that there is some free pizza in it for them if you need an extra incentive (or money if you happen to have some).
> 1 votes

# Answer
Have you considered offering some sort of incentive for people to find defects?

I wouldn't necessarily use direct financial incentives as they can skew the results (intrinsic vs extrinsic rewards), but you could certainly offer them credit on the game with their name being more prominent the more issues they help find.
> 1 votes

# Answer
Have you ever considered utilizing kids from a school/club by offering an after school program? If you were to present yourself as a game developer and thought that you could offer a class/club/lecture/whatever and that it would positive for them I bet a lot of places would be interested in having you come on by. They would gladly pass the word along to their kids, and I know when I was younger that I thought it was the coolest thing in the world to test games. I really thought that was the best job in the world at the time. =D

If you did do something like that maybe you could break up your testing of the game in parts and have each part be a lesson. That way the kids still get to learn something cool and in return they will learn how to be "testers" by testing your game.
> 1 votes

# Answer
I know this question is old and already answered, but ... have you considered having press-releases of some sort on your site and marketing your game there? It's easier to find people who are the type who will play your game (as opposed to looking in a single, physical, rural city) because the internet brings niches together.

I do this too. On my main site, I have a "labs" section where I post in-development releases, along with a sort of press release that outlines what's new (with screenshots).
> 0 votes

---
Tags: marketing, testing
---


title: Getting Early User Feedback on Games

text:
# Question
Title: Getting Early User Feedback on Games
**Disclaimer:** It may be that I'm already doing all the "right" things, but just don't have enough traffic for it to pay off with people giving feedback.

My question is: **how do you attract early and quality feedback into games, from end-users?** Ideally, I'm looking at a model where the seed of an idea comes from you (or from them, even) and you build it into a game, molding it along the lines that people tell you are best.

Because you're just one opinion. And game developers have a reputation for doing weird and sub-par quality stuff, sometimes.

I'm currently practicing the following:

* **VIP List:** I have a "VIP" mailing list (mostly friends) who agreed to try out game releases and give me feedback. They seem hesitant to say anything negative, and most of them are not really gamers, just doing it because they know me and like my niche.
* **2-4 Week Releases:** I use a form of agile and release iterations every two to four weeks. This means every release is functionally small, but somewhat polished.
* **Press-Releases:** With every release, I also post a small "press release" post identifying the good, the bad, what's next, and screenshots (along with a link to play the latest release version).

I'm not getting that much feedback. What am I missing?

# Answer
> 8 votes
No feedback *is* feedback; it could mean that your testers simply don't find the game engaging enough to feel like investing time in crafting reasonable feedback for you. Obviously it will be tricky to figure out why, but it's possible the people you are putting the game in front of are not the ideal demographic (or are not ideal testers). Or it's possible the game just isn't fun.

You should try to make providing feedback as smooth as possible, ideally requiring no work from the user at all except an opt-in. For example, gathering automatic metrics like heat maps (this video discusses these sorts of things, somewhere around the 40 minute mark, I think) has for player death and/or time-to-complete levels and such can tell you things about your game you might not realize without any actual action on the part of your testers at all (other than them agreeing to allow your game to send you statistics about their play sessions).

You might find that your average game play session lasts five minutes and 95% of the users die or get stuck early in level one, for example. That might suggest why nobody bothers providing much feedback -- they simply get discouraged too early and don't bother.

Even getting written feedback should be optimized -- provide an in-game means (for example, a `/bug` command) to pop up a UI that a tester can write up a bug or some bit of information and send you.

People are lazy. The more friction that is involved in testers sending you information, even as little as opening up their email client themselves, the less likely they are to actually do it.

---
Tags: marketing
---


# Question
Title: Resources to help study of Quake 3 engine
Are there good resources ( manuals, tutorials, etc ) to start studying the code of the Quake 3 engine beyond the code itself?

I'm very interested in know how it's structured for educational purposes and maybe to do some modifications.

# Answer
So, you should start by looking at Wikipedia's article on id Tech 3. That can be augmented by Brian Hook's GDC talk summary and some old stuff on the Element 61 blog. In addition to that, you'll have to trawl through a bunch of whatever old mod tutorials you can find to try and reconstruct what's going on.

I'd suggest starting from the original source release from id, instead of ioquake3 or what-have-you, in order to really see the context of what's going on (how input is handled and directed inside the engine, what sort of underlying event structure is used, etc.).

Some key points that helped me when I was working with it:

* There is always a server; there may also be client logic sitting on top of handling a frame.
* Input is directed first to a console, if interested, then to the GUI, then to the game proper.
* The engine itself is separated (hard!) from the game logic, using trap functions. Look in (if memory serves) the cgame and render projects to find the actual engine code.
* Game logic can be entirely written to run in the Quake 3 virtual machine. When modding and using native dlls, you will have to run the game as `quake3.exe +set sv_pure 0 +set vm_game 0 +set vm_cgame 0 +set vm_ui 0` in order to allow the engine to run native code instead of VM code.
* The UI for the menu system is a strange, evil, twisted stack of structures and callbacks. It is usable once you puzzle it out, but that can take some trial and error. Remember, it's a stack.
* If you are writing code in native .dlls, feel free to allocate memory, write in C++, or whatever else floats your boat. You can use the STL too--there is no reason to rigidly follow the C idioms except where you directly interface with the engine.

Some neat things I've made for it with a coworker:

* Simple command-line interface to call shell commands from the console and dump the stdout/stderr streams back to the console (the Quake console).
* Interface with an SQL database to pull and display records.
* Flexible windowing and widget toolkit for making flexible displays on the client hud (using bar charts, text boxes, picture boxes, context menus, resizeable windows, etc.).
* Slow rockets. :)

Personally, I found that the engine was a great combination of really smart things done in really dumb ways, really dumb things done in really smart ways, and really smart things done in really smart ways. It's a great example of how to have modularity and good structured design in a medium-scale C project.

Lastly, don't feel bad if it takes a while to grok. It took me maybe a month to really be able to know where to find what I was looking for in the engine; if all else fails, start at the application init and just tunnel down into the functions, leaving comments for yourself as signposts. My monitor ended up covered in pink post-it notes with function names, line numbers, and short descriptions of what they did.
> 13 votes

# Answer
The book Focus On Mod Programming in Quake III Arena will help you understand the way the client and server logic are decoupled, client prediction, client side graphics effects etc.
> 3 votes

# Answer
Absolutely.

http://en.wikipedia.org/wiki/Quake\_engine is a good overview of what is out there, but you can get into the details of its architecture quite quickly through its citations.

May i also suggest a couple books on game engine architecture which may be more in line with what you are looking for. While not Quake specific, they go into the details of engine design and run parallel to many aspects of of the Quake engines:

* **3D Game Engine Architecture** \- 978-0122290640
* **3D Game Engine Programming** \- 978-1592003518
> 1 votes

---
Tags: quake3
---


title: Network Multiplayer in Flash

text:
# Question
Title: Network Multiplayer in Flash
Flash has come a long way in the last decade, and it's a well-kept secret getting a Flash game to connect to a multi-client server for chat and/or basic avatar movement in real time.

Why has the industry as a whole not made this a common-knowledge type of thing yet? We keep pushing to the web but I am finding it incredibly difficult gathering learning material on this subject.

Sure, I can find multi-client server socket tutorials in various languages (using select statements and/or threads to handle multiple socket connections), but in regards to Flash applications inside of a browser? NOPE!

Can everyone please share what they know? :\] It's a subject I'd really love to get into but I'm afraid I just honestly don't know enough about how to do it.

# Answer
> 2 votes
The reason you cannot find any info about running a socket server from Flash within the browser is because it is not possible. You can only connect to a socket server from a Flash movie running in the browser.

To run a socket server with Flash you need to create an AIR 2.x application that runs on the desktop. This article on Adobe AIR Developer Center should get you started.

# Answer
> 0 votes
I'd imagine the reason you're not hearing much about Flash connecting to a multi-client server is possibly because you're researching only the Flash-side of things and not the server-side element.

It's less of a front-end / client-side issue, and more of a server-side management of state, connections (i.e. players), data (-base) updates, and what-not.

I've seen a nice abstraction used with SmartFoxPro. They offer the plug-and-play chat client, room client, in-game API that you can hook into as a flash / actionscript developer.

Honestly, you should take a look at multiplayer game development from the server-side perspective (java - redwarf, ruby, python (piston as a framework), even php using a framework like codeigniter for a lightweight application).

Take a look at researching from that angle and hopefully that helps!

---
Tags: flash, networking, multiplayer
---


title: Reproducing several sounds in AS3

text:
# Question
Title: Reproducing several sounds in AS3
I'm trying to reproduce several sounds in a game I'm developing in AS3.

The game is like a TD game, and when I got 10+ of the same tower firing at the same time, I hear a horrible: "PRRRRRRRRRRRRRRRRRRRRRR"...

How should I manage this problem? How do PC games (specially RTS ones) manage this in order to hear something decent instead of an obvious and horrible loop?

# Answer
> 2 votes
I haven't had to run into this issue too many times, but what I've done is have a SoundManager class managing all my sounds - creating, calling, disposing.

If I'm finding overlapping sounds gets annoying (take a massive battle in SC2), I'll have the SoundManager keep track of "currently playing sounds" - increment this when a sound plays, decrement when it's complete, and not allow new sounds to play until AFTER that limit is back at a mangeable level.

Hey a bullet's a bullet. You don't need to hear 50+1 to get the idea of a ton of lasers firing and a battlecruiser.

HTH

# Answer
> 1 votes
Typically what I do is I have the sound manager prevent the same sound from being played over top of each other within a small period of time.

So let's say you have 5 towers that all would start firing at the same time (for the sake of argument, let's say the same frame). They would all tell the sound manager to play a "tower type X fire" sound. The sound manager would see this, and only play a single instance of this sound. That sound type won't be allowed to play again until some short period of time later (a couple of frames at least, maybe close to something like a quarter of a second or so). That'll at least prevent the sound from being really loud.

There's some game/audio design that can go into that as well. Keep the pace of the game slow enough and your sounds short enough that you don't have so many bullets firing on screen at a given point in time.

# Answer
> 0 votes
When you ask to play a sound, it helps to play a 'logical' sound rather than directly triggering a physical wave. Instead, leave the logical sound object to handle that part, and it can do something like playing 1 of several different versions of that sound in sequence (aka 'round-robin' samples), or picking one at random, or pitch-shifting and changing the volume on them slightly to give the impression of them sounding unique, etc.

Most AAA games have dedicated editors so that the audio guy can specify the different samples that go into each logical sound without needing to do any programming. The game then just loads in the sound bank that the tool generates.

---
Tags: flash, actionscript-3, sound, sound-effects
---


# Question
Title: What should "own" the battle state in combat between the player and NPCs?
I have a Map, a Tile, NPCs and the Player. When a player enters a tile in the map, a moveTo event is fired, which calls for any NPCs associated with that tile to be "activated". Those NPCs may be antagonists, and wish to start a battle. The battle state (rounds, initiative, alive/dead, add and removing combatants) seems like it should all belong to the Tile, but that seems too tightly coupled... maybe it should belong to the Map? Thoughts on that?

# Answer
Battles are entirely separate things from any of the objects you mentioned. Yes, they take place on a Tile (and, naturally, within the Map), and happen between NPCs and the Player, but none of these object is the Battle.

I would suggest creating a new object, Battle, to maintain battle state. Hand it the participants and any terrain info it might need (e.g. maybe some NPCs/Players have bonuses on swamp Tiles, or maybe ranged attacks are penalized in forest Tiles), then encapsulate all your battle state logic within the Battle object.

Another approach I've seen (but that I don't like as much; YMMV) is to make the battle a method within either the Player or NPC objects. Hand this object the opponents (if you always only have one Player in a fight, put this method in the Player object and hand it the antagonistic NPCs; this gets really tricky to figure out, though, if you can have multiple participants on *both* sides), and then let it handle the battle state logic. This feels too tightly coupled to me, though, and personally I much prefer the battle logic living in its own Battle object. This also scales better if you add complexities like different tactics to your battle rules -- you can quickly find yourself maintaining a massive amount of code to represent your complex fights, and having that in its own separate object makes that a lot easier to manage.
> 10 votes

---
Tags: game-mechanics, rpg, state, npc
---


# Question
Title: Determining if a character is within the field of view in XNA
I'm trying to creating a field of view for the camera I'm making for a game. It rotates around a circle for 180 degrees while the head moves accordingly. I'm going to bound the field of view within an isosceles triangle using the method described on this website.

The problem I'm having is that I don't know how I'm going to detect if the field of view has intersected with the character as seen in this link.

Any help with this would be greatly appreciated.

\[EDIT\]

sorry I meant an asset in game representing a camera much like the enemy in the second link, not an actual camera class in XNA(really sorry)

# Answer
> 2 votes
Check out Linear Algebra for Game Developers

See the section titled Do Product. It has a tutorial for the math to determine whether an object is in the field of view of another object. Should get you started.

# Answer
> 1 votes
Check out the BoundingFrustum.Contains() function. You give it the view and projection and it builds the frustum. If you're going 2d, then you can add bounding boxes to a custom sprite class - example is here.

Edit: Check here for two different techniques for determining if a point is inside a triangle.

I think the bounding frustum could still work, but might be a bit more work. You can use the BoundingFrustum for things other than cameras. Each NPC would have to have a local view and projection to get their frustum and you can use that to check against a Vector3 (just set Z = 0 for Vector2). If you wanted to draw the frustum for debugging, you can get the points of the box and project them back to 2D just by setting the Z to 0.

---
Tags: xna, collision-detection
---


# Question
Title: How to Make Games Faster (Without Sacrificing Quality)
I posted a similar question on the Programmers SE site. Please read it. I want to know **what specific things I can do to help me create games faster.**

Already, in addition to whatever I wrote there, I am:

* Creating reusable libraries on top of existing engines that I'm using
* Creating reusable assets (graphics, sounds, icons)
* Finding sites where I can find assets quickly (graphics, sounds, icons)
* Using game engines instead of writing code from scratch
* Using agile so my game is customer-focused and gets results
* Biting off small games (like a vanilla rogue-like)

I feel it's not enough; I'm taking far too long to make games. A simple chemistry puzzle game, for example, took nearly 40 hours -- and that's with only half-decent graphics.

What are your recommendations? How can I get better and faster?

# Answer
> 2 votes
The answers in your other question mention typing faster. Something else to consider is, are you spending most of your time actually coding, or thinking about a problem you need to solve? If it's the latter, then one suggestion would be to practice problem solving. If it's the former, then maybe you should look at your typing speed and see if you can improve anything there.

One thing to point out is that it might be worth getting more practice. Participate in a gamedev competition like Ludum Dare or the 7day roguelike event. The more practice you have in making games, the easier it'll be to make the next one.

Finally, games still take a lot of time, and good quality games take even longer. Practice helps, but sometimes it just takes 40 hours to make a game.

---
Tags: productivity
---


# Question
Title: Implementing a 2D destructible landscape (like Worms)
What steps would be involved in constructing a destructible 2D landscape, like in Worms? Ideally, What are some ways that this process could be made efficient as possible?

# Answer
I don't know how the landscape in worms was implemented exactly, but I'm pretty sure they used a bitmap for the landscape (at least in the older games of the series).

A very basic approach would be a bitmap image (B/W) where black pixels represent *air* and white pixels represent *ground*. Destruction of the landscape can be done easily using pixel operations. So if a rocket hits the ground, paint a black circle with `radius = blastRadius` at the point of impact.

You can then render your world (or just a portion of it) using that bitmap. For better performance I suggest you implement it in a way, that you can update/render just a portion of the "world". Eg. if some parts of the landscape are destroyed by a rocket, just re-render the affected areas, not the whole world.

Instead of a B/W image as your "collision-map", you could also use a 24bit image where you use two channels to store the surface-normal (x,y) per pixel and one channel to store the actual "collision-map". Having the surface-normal at hand will greatly help you to calculate bouncing grenades, or to determine if a character can move in a given direction.
> 49 votes

# Answer
### Use constructive solid geometry

I wrote a proof of concept that used constructive solid geometry to handle destructible terrain. I used the GLU Tessellator to perform the boolean operations. The documentation explains how, search for *"CSG Uses for Winding Rules"*.

I fed the triangle output of the tessellator as static polygons into Box2D. The PoC worked quite well. I was able to arbitrarily subtract and add terrain in real-time and the terrain continued to behaved appropriately with Box2D. The only real hiccup was that the GLU tessellator can produce degenerate triangles which Box2D doesn't like, so I had to filter those out by hand.

The next step in the PoC (which I never got around to) was to use the SCC algorithm from the boost graph library to detect when a piece of the terrain had been severed (cut the top off a mountain). The severed terrain would still be destructible but now represented by a dynamic(non-static) Box2D body with the triangles attached as shapes. I had the design worked out but lost interest once I started digging into the boost documentation. I *"plan"* to revisit the idea when I make a scorched earth/Worms game someday.
> 8 votes

# Answer
One possibility off the top of my head:

Use a vector graphics path representation for storing the outline of the destructible "land". When a destruction event occurs (e.g., a grenade goes off), the blast area, represented as a circle, would be removed from the the land path via a boolean subtraction operation. The resulting path represents the new "land" for ground collision detection, and also possibly a mask for drawing the land.
> 6 votes

# Answer
All the answers above talk about implementing the simplest case, as in worms. That is, when area of impact is destroyed and everything else is untouched. Did you consider, that your landscape may eventually be split in two? Say, there's a mountain, and players cut the bottom of it with a rocket launcher. Now, shouldn't the mountain fall? Also, it would be natural for a landscape to be a little bit elastic. At the times of Worms (at least as I remember them, I didn't play Worms for, like, many years) computers weren't just strong enough to do it right. But they are now.

Of course, it totally depends on ambitions of your project. But if you want it to be really awesome, maybe you should try Box2D as a physics engine. There's a lot you can do with it.
> 5 votes

# Answer
As bummzack said Bitmaps. Although you could use 1 bit transparencies or if you dont have that support use a horrible pink color that you wont use in your game.

The point of impact can be calculated just be checking the pixel color. and when an impact happens change the color (or delete it) of the bitmap.

As for the blast radius my first stop would be Bresenham's circle algorithm, very fast and efficient. Although I'd do a rought delete first with something like a square and put the circle round it to get the edges.
> 3 votes

---
Tags: 2d, terrain
---


# Question
Title: Android collision detection of a 3d object based on a 2d projection
I am writing a game for android. We have an orthographic view setup, but the characters (ships, projectiles, etc). The enemies / characters will be able to rotate about the x axis. The problem is that I want to do the collision detection as if it were in 2d using sprites, meaning that if i have a ship with a top down view of

```
---------
--------------
-----------------
--------------
---------

```

it might rotate to look like

```
-----
--------------
---

```

and i want to do all of the collisions based off of the appearance of a top down view. I was originally thinking of using glReadPixels, until I read that was unbelievably slow. Then I was thinking about using pre-rendered bitmaps, but that seems like a pain and not very great since some of our ships won't be 'normal' enough to just say "Have a bitmap for every 45 degrees of rotation about the X". Does anyone have any suggestions?

# Answer
> 2 votes
Posting an answer in case anyone comes searching for this topic.

Since this is on Android, I believe the assumption is that CPU is scarce, and so the collision algorithms need to be cheap. Based on that assumption, we will construct a system and then discuss optimizations:

1) \[Offline\] Simplify the 3D models into a collision mesh. This is a very typical procedure in any 3D game, and is done in the Content Creation Pipeline.

2) \[Offline\] Calculate a bounding sphere for every 3D collision mesh.

3) \[Run-time\] Project the 3D bounding sphere of each object to a 2D bounding circle.

4) \[Run-time\] Do cheap, simple circle-circle collision checks.

5) \[Conditional Run-time\] If a circle-circle collision occurs, project the full 3D collision meshes for both objects into 2D. This is trivial if you know your Linear Algebra.

6) \[Conditional Run-time\] Now do 2D triangle mesh intersection tests. If this returns True, you have a 2D collision.

Steps 1 and 2 are cheap, because you do them offline or at startup.

Step 3 is fairly cheap. For extra speed, only re-project a sphere if its projected size will change. This depends on your Projection matrix. In a top-down view, for example, this will only occur if the camera changes height, the objects change height, or the camera zooms in/out.

Step 4 is dirt cheap. Calculate the distance between the objects:

```
float total_radius = a.bounding_radius + b.bounding_radius;
if(DotProduct(a.2D_position - b.2D_position) < total_radius*total_radius)
    // Possible Intersection Detected!

```

Step 5 may be expensive, depending on your collision mesh complexity, matrix library speed, and the Android device. Luckily its hidden behind the circle-circle test. Step 5 can be optimized by caching the 3D projections. So, after you've projected a 3D model into 2D triangles, store that in the object's data. Only re-do that projection if the object has rotated, or moved closer/further to the camera. Also, don't forget back-face culling!

Step 6 is, again, expensive, but hidden behind the circle-circle test. At the cost of intersection quality, you can simplify the triangle-triangle intersection test to ignore triangle-within-triangle tests. This depends on your game, but I think most games would be fine without that test.

Both step 5 and step 6 can be optimized by sacrificing collision quality with respect to time. While the game may be rendering at 30 or 60fps, you can perform collision checks at 10fps, or at a rate adjustable based on current rendering performance.

Other optimizations depend entirely on your specific game. Collision meshes can be made quite simple, and thanks to back-face culling your final mesh-mesh collision check shouldn't be too complex. You can even do bounding circle-circle intersection tests on the triangles to cull them further (i.e., if a triangle isn't inside the other object's bounding circle, don't test it).

The FPS optimization suggested above can be taken half-way. You can re-project 2D meshes at 10FPS, but do the mesh-mesh intersections at a full 30fps.

# Answer
> 1 votes
I've since decided to go 2d, however, @ Tetrad and @Robert, there is something *very* wrong with that. The problem is that I want to do collisions based off of how it appeared to be in 2d. I would basically need to flatten all of my poly data so that it would lie on a single plane. In the simplest of terms, I needed to get rid of 1 dimension. If I have 2 ships that look like they collide, looking at them from above, I need to make sure they collide.

```
The overhead projection
      __________
______|_        |
|     | |       |
|     |_|_______|
|       |
|       |
---------

The same ships from a different perspective.
         _____________
_________ \           |
|        | |          |
|________| |          |
          /___________|

```

I want this to be a collision because it looks like it would be from a top down perspective. Bounding box collision detection would also not be sufficient in this case. The best I could come up with was rendering and using glReadPixels, but I heard that was unbearably slow.

Like I said, I've since decided to go 2d. I was only doing this in 3d so a friend who has a hard-on for OpenGL would work on this with me, but he bolted. Still, it's an interesting problem.

Thanks for your suggestions.

# Answer
> 0 votes
Well, you went with 2D eventually so this is purely theoretical at this point :) This is how I'd go about, as you put it, getting rid of one dimension :)

First, you need to project 3d mesh onto a 2d plane. I see two ways of doing that:

* if your projection is exactly aligned with either angle you just ignore that coordinate
* if it's not you can set up a projection matrix and use it to 'project to screen', ignoring the depth coordinate (this of course would work for the above case as well)

Then, you'd need to build a shape outline while going through all the faces. Working with faces allows you to have a concave outline by constructing a CSG sum of all projected triangles (this would be slow but then you'd be doing that on startu or it can even be preprocessed offline). If a convex outline would be OK then you need to build a convex hull. Last, optional step, would be to simplify the silhouette to make the collision detection faster.

Once you have your outline it's a simple matter of seeing if any of the edges intersect or one object is contained within the other.

---
Tags: 2d, 3d, android, collision-detection
---


# Question
Title: Playing Sounds and removing instances once they have played -- Android
I am playing sounds in my application I have the following code

```
sounds = new HashMap<String, MediaPlayer>();

```

Then when guys are created on screen they are given a sound.

```
sounds.put("sounds"+Integer.toString(ncount), MediaPlayer.create(this, R.raw.hit));

```

I want to remove the MediaPlayer from the hashmap like I do the enemies when they die

```
sounds.get("sounds"+Integer.toString(ncount)).setOnCompletionListener( new MediaPlayer.OnCompletionListener() {

    public void onCompletion(MediaPlayer mp) {

        sounds.remove("sounds"+Integer.toString(ncount));
    }

});

```

This errors out... how would I reference the sounds hashmap to remove the associated MediaPlayer when sound is complete?

Thanks!

# Answer
> 1 votes
Use a SoundPool

# Answer
> 0 votes
Is `ncount` a static variable? If that's the case it is very likely that `ncount` has changed when `onCompletion` gets called (because `ncount` was modified during playing of the sound). You should probably use another method to build that identifier...

---
Tags: android, sound
---


title: Realistic damage

text:
# Question
Title: Realistic damage
I'm looking for a good way to simulate damage, for example a weapon firing at a ship it would calculate the damage depending on layer type, weapon type, angle and similar what i need is a way to to represent the damage to a certain layer. I'm thinking of using matrices for keeping track of damage and also the appearance of the model.

What the problem is for flat surfaces its not a problem but for curved surfaces calculating the angle, at least no way that i know of.

For example its a curved hull with 3 armor layers, so we have 4 matrices 3 for the integrity of the armor and a 4th for the height map there is also a density variable(increasing the armor matrix size and then assigning more values in the heightmap/location map to the coresponding layer surface.

Is there a better way to do this?

# Answer
If you have the equation of the curve in question - or even just an approximation - then you can work out the tangent of the curve at the point where the projectile contacts it. You can then treat that tangent as if it was a flat surface that has been hit and work out the angle of incidence accordingly.
> 4 votes

---
Tags: mathematics, game-mechanics, matrix
---


# Question
Title: Why doesn't the y Axis work with SuperBible frame reference or GluLookAt
I'm currently trying to understand how to use the GLFrame Class in the superbible book, and acording to the 4th edition of the book, the camera matrix derived from the Frame of reference class should work the same as GluLookAt

When I add these lines

```
cameraFrame.SetForwardVector(-0.5f, 0.0f,-0.5f);
cameraFrame.Normalize();

```

The camera looks in the correct direction, yaw at 45 Degrees (Am I doing that right!)

However when I add this

```
cameraFrame.SetForwardVector(0.0f, 0.5f,-0.5f);

```

The camera just looks as if it was set to (0.0f, 0.0f, 1.0f)

Why is this! It's been driving me mad for three days. Maybe I'm not passing in the vectors correctly, but I'm not sure how to pass in x,y 360 degrees for the look at (forward) location/vector. Do the vectors have to be normalized before passing them in?

Eventually I hope to do full mouse look (FPS style) , but for now just understanding why I can't make the camera simply pitch up would be a good start.

Thansk!

Here is the code in situ.

```
// Called to draw scene
void RenderScene(void)
{
// Color values
static GLfloat vFloorColor[] = { 0.0f, 1.0f, 0.0f, 1.0f};
static GLfloat vTorusColor[] = { 1.0f, 0.0f, 0.0f, 1.0f };
static GLfloat vSphereColor[] = { 0.0f, 0.0f, 1.0f, 1.0f };

// Time Based animation
static CStopWatch   rotTimer;
float yRot = rotTimer.GetElapsedSeconds() * 60.0f;

// Clear the color and depth buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Save the current modelview matrix (the identity matrix)
modelViewMatrix.PushMatrix();

M3DMatrix44f mCamera;

/////////
///////// My Code

cameraFrame.SetForwardVector(-0.5f,-0.5f,-0.5f);
cameraFrame.Normalize();

///////// End of my code
cameraFrame.GetCameraMatrix(mCamera);
modelViewMatrix.PushMatrix(mCamera);

// Transform the light position into eye coordinates
M3DVector4f vLightPos = { 0.0f, 10.0f, 5.0f, 1.0f };
M3DVector4f vLightEyePos;
m3dTransformVector4(vLightEyePos, vLightPos, mCamera);

// Draw the ground
shaderManager.UseStockShader(GLT_SHADER_FLAT,
                             transformPipeline.GetModelViewProjectionMatrix(),
                             vFloorColor);
floorBatch.Draw();

for(int i = 0; i < NUM_SPHERES; i++) {
    modelViewMatrix.PushMatrix();
    modelViewMatrix.MultMatrix(spheres[i]);
    shaderManager.UseStockShader(GLT_SHADER_POINT_LIGHT_DIFF,     transformPipeline.GetModelViewMatrix(),
                            transformPipeline.GetProjectionMatrix(), vLightEyePos, vSphereColor);
    sphereBatch.Draw();
    modelViewMatrix.PopMatrix();
    }

// Draw the spinning Torus
modelViewMatrix.Translate(0.0f, 0.0f, -2.5f);

// Save the Translation
modelViewMatrix.PushMatrix();

    // Apply a rotation and draw the torus
    modelViewMatrix.Rotate(yRot, 0.0f, 1.0f, 0.0f);
    shaderManager.UseStockShader(GLT_SHADER_POINT_LIGHT_DIFF, transformPipeline.GetModelViewMatrix(),
                                 transformPipeline.GetProjectionMatrix(), vLightEyePos, vTorusColor);
    torusBatch.Draw();
modelViewMatrix.PopMatrix(); // "Erase" the Rotation from before

// Apply another rotation, followed by a translation, then draw the sphere
modelViewMatrix.Rotate(yRot * -2.0f, 0.0f, 1.0f, 0.0f);
modelViewMatrix.Translate(0.8f, 0.0f, 0.0f);
shaderManager.UseStockShader(GLT_SHADER_POINT_LIGHT_DIFF, transformPipeline.GetModelViewMatrix(),
                            transformPipeline.GetProjectionMatrix(), vLightEyePos, vSphereColor);
sphereBatch.Draw();

// Restore the previous modleview matrix (the identity matrix)
modelViewMatrix.PopMatrix();
modelViewMatrix.PopMatrix();
// Do the buffer Swap
glutSwapBuffers();

// Tell GLUT to do it again
glutPostRedisplay();

```

}

# Answer
> 1 votes
> Do the vectors have to be normalized before passing them in?

That's highly probable. Many computations require normalized vectors to work, and many functions do *not* normalize vectors they receive as parameters as it's quite expensive.

---
Tags: opengl, 3d, camera, matrix
---


# Question
Title: C++ game-programming; What would be the "next step"?
I'm reading C++ Primer Plus 5th Edition. I'm over at Chapter 8 exercises, which is more than half of the book to go but I was wondering ***what would be the "next step" after I'm through with the book?***

I want to use SDL/OpenGL and whatever cross-platform open source api's and libs there are available for other components of game development.

# Answer
> 18 votes
Quite simply you should put what you've learned to the test and start making a simple game.

# Answer
> 4 votes
As a side note, I would highly recommend using SFML instead of SDL. Since you've been hitting on **C++** books, how SFML is organized will make a lot more sense that SDL. SFML is *very* object oriented.

Although SDL has been around longer and has a CRAP LOAD of existing resources and tutorials, SFML is worth the investment. I've worked with both, and I can tell you SFML is just *nicer*. An added bonus is that 2D rendering is hardware accelerated in SFML. So it's faster too.

End of shameless SFML propaganda.

# Answer
> 1 votes
Books are often not the best of resources when it comes to learning programming. Especially in a language as complex as C++. If this is your first language I strongly suggest starting out with another language such as Java or C#/XNA which are both easy to learn and give you a good understanding of whats involved in building a game. Simply diving into SDL/OpenGL and expecting to build a game without having much understanding of how things work is a big mistake, one that many people make which results in them disliking programming.

The book should only be used as a reference. You need to personally think of problems which you can solve and then solve them. Then begin writing more complex programs such as, for example Battleships in a console environment. The more programming you do the better you get. Furthermore, books don't teach you how to design your code, you get that from experience. Designing a good structure for your program is a difficult task but the more your practice the better you will get.

Just as a side note. 3D programming is a lot more complicated than 2D programming (I'm assuming you want to build 3D games). Try building console games first then go to 2D. Once you learn more only then you will have the skills to attempt 3D and graphics programming.

# Answer
> 1 votes
Go build something, anything and then after two hours of trying to get it to compile go back and read the book again.

You will now understand why x was called before y and what the purpose was.

This will allow you to use the knowledge from the book instead of just copying the code.

---
Tags: c++
---


title: Tilesets with two dimensions

text:
# Question
Title: Tilesets with two dimensions
I have done tiled maps and tile sets quite often, but in a rather simplified way. My tile sets were linear images of the size `(tile_width * num_tiles) * tile_height`, so I could find an index easily by using `val src_pos = (index * tile_width, 0)`.

But in reality, I've come to notice, tile sets are actually fully sized images of two dimensions. That has some advantages, clearly, it's easier to draw. So I wanted to support that. The problem would be just to turn the index to the right source position. Failed a bit, so I wanted to ask here.

I've had two ideas dealing with it:

Turn the index into two values with

```
src_x = index modulo num_tiles_x
src_y = index div num_tiles_y

```

which lead me to some quite weird results. The tiles are correctly cut, but they're the wrong ones for the position.

The other idea is to take the image and turn it into a 1D-tile set by cutting it up. But I am afraid that would not be an option, as I am using Textures.

How is this solved in 'professional' applications?

# Answer
> 14 votes
The formula you are using to convert from a 1d position to a 2d position is almost correct (and I'm sure the same method is used professionally)

> src\_x = index modulo num\_tiles\_x
>
> src\_y = index div **num\_tiles\_x**

Where num\_tiles\_x is the number of tiles in a single row.

# Answer
> 0 votes
//used to find tile on sheet sourceY = (ScreenMap\[count\]/10)\*60; sourceX = ((ScreenMap\[count\]%10)-1)\*60;

my tiles are 60x60 pixel squares. ScreenMap\[count\] is an array of tiles but in your case it would be the number of the tile for example 14 for the fourth tile on the second row.

the only problem is you cannot read 1 or 10 due to a mathmatical error so you tile sheets are ten tiles wide but the first and last tile cannot be read so you only get eight per row.

this method works great and I have many tile sheets working in this way.

one other thing, you mentioned 'professional' so you might be interested in this. In commercial games a tile sheet is always limited to a maximum of 256 tiles per sheet, this is so each tile can be assigned a binary value.

hope this helps.

---
Tags: tiles
---


# Question
Title: Getting Started with 2d Game Dev (C++): DirectX or OpenGL?
So, i'm a student looking to get my foot in the door of game development and im looking to do something 2D, maybe a tetris/space invaders/something-with-a-little-mouse-interaction clone.

I pointed my searches in the direction of C++ and 2d and was eventually lead to DirectX/OpenGL

Now as i understand it, all these packages will do for me is draw stuff on a screen. And thats all i really care about at this point. Sound isn't necessary. Input can be handled with stdlib probably.

So, for a beginner trying to create a basic game in C++, would you recommend DirectX or OpenGL? Why? What are some key feature differences between the two? Which is more usable?

# Answer
> 16 votes
I'd recommend SDL (http://www.libsdl.org/) for 2D, it was where I first started with graphics stuff and it was pretty easy to use, even though I barely knew C++ at the time.

This (mirror) is the set of tutorials that I started with and found very useful (they were a bit dated even ~4 years ago when I worked through them, but I don't think SDL has changed much and they should still be relevant).

SDL also does input handling and SDL\_Mixer can do basic audio.

I've never worked with DirectDraw or OpenGL for 2D stuff, so I can't comment there, but I can definitely recommend SDL.

# Answer
> 7 votes
I used both SDL and SFML for my game projects. I used SDL for a finished game, a tetris game, and I mostly used SFML as a windowing layer for shader experiments. From my experience, I'd have to say that SDL is what it says. It's a simple direct-media layer, which abstracts the data your media (sound and video) works with to a level you can interact with accross different platforms. That's "all" it does.

Because of that, you generally have to mix it with a few other libraries, most notably SDL\_mixer, SDL\_gfx, and SDL\_image, which provide functionality everyone needs to create games.

All of these libraries are also meant for the C programming language, and they follow it's conventions. Not that there is anything wrong with that, but if you want an object oriented approach to how you interact with io, then you basically have to build that layer yourself.

SFML comes with everything right out of the box. It has sound, it has video, it has mixing, it has frame-capping, and it is object oriented. If that's what you want, I'd recommend you go for that. SFML also has an abstraction layer for some of the basic functionality in opengl (specifically beginShape/EndShape and pixel shaders). I don't think SDL has anything like that, just a method to merge with it.

P.S. Not to drive away the conversation from C/C++, but if you're not using that language for any particular reason, and want an easier one, there's always pygame. Which is basically SDL+ for Python.

# Answer
> 6 votes
http://www.gamedev.net/community/forums/mod/journal/journal.asp?jn=263140&reply\_id=3598844

I agree with these remarks and think it is a stellar discussion of why DirectX is better than OpenGL.

That journal is in response to David at Wolfire.

I hope that serves to balance it out a bit. ;)

But in general, if you're using a cross-platform, cross-API framework:

Use DirectX on Windows and OpenGL on \*nix.

# Answer
> 4 votes
http://blog.wolfire.com/2010/01/Why-you-should-use-OpenGL-and-not-DirectX

I agree with these remarks and think it is a stellar discussion of why OpenGL is better than DirectX.

However, this question is absolutely a matter of opinion, and DirectX absolutely has its benefits over OpenGL, especially 10 and 11 and especially in the context of game development.

Also, should you choose to go with OpenGL, SDL is a wonderful and very popular library, and there are plenty of resources for learning OpenGL (NeHe, etc.) - but that's the place for another question perhaps.

# Answer
> 1 votes
If you're just starting out it's probably better to use an existing 2D engine or framework such as SFML.

# Answer
> 1 votes
I like Direct X and have been using it for several years on many projects but if your learning do watch out for version issues.

I found that the majority of direct x code will not compile under a different version and this can be hell if you are trying to follow a tutorial.

I recommend Direct X as there are features for everything that make it easier when you are first beginning and then more advanced ways of manipulating things as you advance.

# Answer
> 1 votes
Haaf's Game Engine

I don't know how up-to-date it is (i mean it's not, but i don't think there's any reason that it shouldn't be usable), but i used it a while ago (C++) and i really enjoyed it. HGE wasn't updated since 05.08, but again, i remember it being pretty simple to learn, and fast. It also comes with all sorts of tools and helper like a particle system.

Anyway, if what you want is to create an actualy -game-, as opposed to learning the stuff that's going on "under the hood" in the processes of drawing and such, i'd recommend using something higher level then openGL or DirectX, or you're going to spend your time drawing stuff on the screen as opposed to creating an actual game. And HGE is definitly worth checking out.

http://hge.relishgames.com/

# Answer
> 0 votes
Im in the same position as you are, having just begun working on game development myself (on the iPhone platform) a few months ago. Coming from a C background, I would actually suggest you use a framework (Particularly Cocos2d).

The advantages of a framework are more then can be discussed in this post - but mainly it handles most of the low level processing with OpenGL and provides you methods to deal with the what your most likely going to require for game dev. They have a great community, are open source, and hence if you need to access the core code of the framework / modify any bit of it to suit your needs / go to the low level OpenGL if necessary - you are still given that choice.

You can go the route of direct OpenGL but to me it just seems like overkill.

You will most likely also want to look into various different physics libraries that exist out there - Google Chipmunk and Box2D for more information.

cheers!

---
Tags: c++, opengl, directx
---


# Question
Title: Loading textures in OpenGL makes everything look darker
I don't know what I'm doing wrong but I'm having a big a problem with GL\_TEXTURE\_MIN\_FILTER when loading textures for my scene.

I'm doing a skybox, but that's irrelevant because the problem exists even if I just load the textures and don't do anything with them. Meaning, the code to draw the skybox and attach the textures to the box quads is disabled.

My current code to load textures is the following:

```
typedef struct sGameTextures {
    unsigned int skybox[6];
} GameTextures;

GameTextures gameTextures;

unsigned int loadImageTexture(const char *filepath, int glFormat, int pWrap, int pFilter) {
    int texDimension, texWidth, texHeight, texPixelSize;
    unsigned int texID, texImage;
    unsigned char *texPixels;
    unsigned int ilFormat;

    switch(glFormat) {
        case GL_LUMINANCE:
            ilFormat = IL_LUMINANCE;
            break;
        case GL_RGB:
            ilFormat = IL_RGB;
            break;
        case GL_RGBA:
            ilFormat = IL_RGBA;
            break;
        default:
            return -1;
    }

    ilGenImages(1, &texImage);
    ilBindImage(texImage);

    if(!ilLoadImage((ILstring)filepath)) {
        ilDeleteImages(1, &texImage);
        return -1;
    }

    texWidth = ilGetInteger(IL_IMAGE_HEIGHT);
    texHeight = ilGetInteger(IL_IMAGE_WIDTH);
    texPixelSize = ilGetInteger(IL_IMAGE_BPP);

    // stop if image width or height is not power of 2
    if(!texWidth & (texWidth - 1) || !texHeight & (texHeight -1)) {
        ilDeleteImages(1, &texImage);
        return -1;
    }

    texDimension = texWidth * texHeight * texPixelSize;
    texPixels = new unsigned char[texDimension];

    ilCopyPixels(0, 0, 0, texWidth, texHeight, 1, ilFormat, IL_UNSIGNED_BYTE, texPixels);
    ilDeleteImages(1, &texImage);

    if((texPixelSize * texWidth) % 4 == 0) {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
    } else {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    }

    glGenTextures(1, &texID);
    glBindTexture(GL_TEXTURE_2D, texID);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, pWrap);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, pWrap);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, pFilter);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, pFilter);

    glTexImage2D(GL_TEXTURE_2D, 0, glFormat, texWidth, texHeight, 0, glFormat, GL_UNSIGNED_BYTE, texPixels);

    return texID;
}

void loadGameTextures(void) {
    char *boxFace[] = { "front", "back", "left", "right", "top", "bottom" };
    char boxTexture[FILENAME_MAX];

    for(int i = 0; i < 6; i++) {
        sprintf_s(boxTexture, "Resources/Textures/Skybox/Set%d/%s.jpg", 1, boxFace[i]);
        gameTextures.skybox[i] = loadImageTexture(boxTexture, GL_RGB, GL_CLAMP, GL_LINEAR);
    }
}

void main(int argc, char **argv) {

    (...)

    ilInit();
    ilEnable(IL_ORIGIN_SET);
    ilOriginFunc(IL_ORIGIN_LOWER_LEFT);

    loadGameTextures();

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);
    glEnable(GL_TEXTURE_2D);

    glutMainLoop();
}

```

This is how my scene looks like when I don't load any textures (ie: `loadGameTextures()` is never called): https://i.stack.imgur.com/1cCZp.png. Look how the floor is light green and now compare to the following which is much darker: https://i.stack.imgur.com/NYeqD.png.

At first I pinpointed the problem to `glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, pFilter);` more exactly when `pFilter = GL_LINEAR`. When I commented this line, or replaced `pFilter` with `GL_LINEAR_MIPMAP_LINEAR` the floor was light green again. However, this was without using the textures, I was just loading them. When I tried to use them, it didn't work, it looked like this: https://i.stack.imgur.com/JRAFJ.png.

The sky now looks white because that's the clear color I use when drawing the skybox quads. We only see white because the textures are not properly working. They are loaded but that option I selected for `GL_TEXTURE_MIN_FILTER`, helps on the darkening issue but doesn't display any textures.

Another thing I noticed is that I'm enabling `GL_TEXTURE_2D` globally and if I only enable it when I need it (drawing the skybox) and disable it when finished, it will work. The scene won't be dark anymore. But the skybox is just an example, I'll be using textures all over the place and it's a pain to keep enabling/disabling `GL_TEXTURE_2D` every time I need to draw some texture. Surely there must be another way around this problem?

# Answer
> 3 votes
You can try to 'unbind' any texture if you want to keep GL\_TEXTURE\_2D enabled (which is fine).

```
glBindTexture(GL_TEXTURE_2D, 0); // Bind the default (empty) texture

```

---
Tags: opengl, textures, lighting
---


title: Sprites as Actors

text:
# Question
Title: Sprites as Actors
I'm not experienced in Game Development questions, but as a programmer. In the language Scala, you can have scalable multi-tasking with Actors, very stable, as I hear. You can even have hundreds of thousands of them running at once without a problem.

So I thought, maybe you can use these as a base class for 2D-Sprites, to break out of the game-loop thing that requires to go through all the sprites and move them. They'd basically move themselves, event-driven.

Would that make sense for a game? Having it multitasked like that? After all, it will run on the JVM, though that should not be much of a problem nowadays.

EDIT:

After dabbling for a while, I noticed there is only one real advantage to this idea: Multicore Support. A simple game loop will only run on one core and will work through everything sequentially.

Since modern computers, even at home, nowadays have two or more cores built-in, I think it is a good idea to enable game programmers to efficiently use the other cores. After all, I think usually the player will only have just the game running on his eight-core machine, so why not.

The other advantage I see is that in Scala, you can have `RemoteActors`, which can be treated the very same way but run on another computer. So maybe this can simplify network gaming as well.

I intend to build that into my Scala 2D engine as soon as I can.

# Answer
> 7 votes
I didn't try, but I'm a Scala programmer, and I would say that this isn't the best approach. Sprites need to be animated synchronously. Actors have no guarantees that they will be executed fairly - some sprites may thus be faster than others, which is not what you want. You might want to use a barrier to synchronize them, but then - why use actors. If you rely only on message passing , implementing this kind of synchronization (implementing a barrier for 1000+ actors) is an overkill.

Another issue is - what would you use message-passing for? Do you need your sprites to communicate? You could send a message by the master actor, telling each sprite to move to the next frame, but in terms of performance, that's magnitudes and magnitudes more than invoking methods directly and iterating through a set of sprites.

Seems to me that what you need here is some kind of a very lightweight multitasking, and no message passing at all. Rolling in your own actor-like implementation which ensures fairness is probably the best way to go if you want to ensure this, but that's too much work for too little gain. Another thing to look is functional reactive programming and `scala.react`, I believe that is a better match for this use case.

I've implemented a 2d isometric game engine in Scala. I've only used 1 global actor to update visible sprites which were animated.

You might want to implement your game logic using actors - for instance, to distribute computations on different parts of your game map to different actors, so that they update game state in parallel - and gain a performance gain. I would not use a single actor per game object, rather, an actor per region. If you go too fine grained, performance suffers.

Still, if I were you, I'd try it, just to see what happens.

# Answer
> 1 votes
> So I thought, maybe you can use these as a base class for 2D-Sprites, to break out of the game-loop thing that requires to go through all the sprites and move them. They'd basically move themselves, event-driven.

What would the event be that moves them?

Would it be an event you emit once per frame?

And if so, how has this changed the system in any practical way?

When originally studying object-orientation in the context of C++, I learned that some people liked to think of a statement such as `xyz.doThis(x)` as meaning 'send the doThis message to xyz (with payload of x) and wait for an immediate response\`. When viewed on this level, there's no intrinsic difference between an event or message based system and a normal procedural one.

# Answer
> 0 votes
Well, I'm not that much of a programmer either, but I don't see any problem on your proposal. I didn't even think of such a way of developing actors.

It may be quite a challenge, since the IA has to be very accurate, to avoid unespected behavior, but besides that, I see it's quite a good proposal

# Answer
> 0 votes
That's a cool approach to thinking about updating your game objects. I don't know Scala, but I say give it a shot and see how it turns out, and even better post your results!

The main questions that spring to my mind are: How do you manage how frequently some game objects update versus others? Will you need to worry about the sprite actors taking up too many cycles such that rendering system doesn't have time to draw a frame every 1/60th|30th|24th of a second?

Another thing to consider is how this will affect resolution of player vs. AI interactions that rely on the order of a sequence of very quick events. Depending on the type of game, this may not probably won't matter much.

# Answer
> 0 votes
If by *sprite* you mean *game entity* then sure.

Game entities should never draw themselves. They should update a graphic handle that describes where and how they need to be drawn. The render system or scene graph or whatever does the actual drawing. There is one graphic card, further that graphics card must be synchronized every 16ms. A set up like that just doesn't work well for distributed asynchronous processing.

The render system should be one actor (or possibly a couple if you're tricky). When game entities update the graphics handle it sends messages to the render system. The render system, can them make all sorts of decisions and/or optimizations, e.g. batch rendering, occlusion, physics jitter smoothing, etc.

I am not a Scala developer, but I've done quite a bit with Erlang. So if some of my Scala terminology is incorrect, please forgive me.

---
Tags: java, sprites, multithreading
---