# Question
Title: Is there a simple way to draw only the tiles I need?
I am working on a platformer that is going to have a map that is randomly generated and infinite in 3 directions: left, right, and down.

I've figured out that I will need to separate this world into chunks, as otherwise it will be impossible to pull off. Each chunk currently consists of 512x512 tiles. (This may change in the future.) There will be set points on each chunk where the game will check whether or not a chunk exists in the direction the player is heading. If there isn't, one (or a few more) will be generated. If there is, it will be loaded into memory.

Now, my problem is, say I have a chunk and I am near the bottom left corner of it. If the camera moves diagonally down and to the left, I will be intersecting 3 additional chunks. Is my only option to calculate the tiles from each chunk and determine where they need to be drawn on screen? It seems like this will be a little nuisance of a problem to deal with. If this is the only way to do it, I guess I will have no choice but to tackle it, but I'm wondering if there's an alternative solution to this.

# Answer
> Is my only option to calculate the tiles from each chunk and determine where they need to be drawn on screen? It seems like this will be a little nuisance of a problem to deal with.

If that seems hard, then you should change how you do it so that it's easy. It's not clear from your question what makes the case problematic, but I suspect that it's that you're trying to load chunks based on *how the player/camera is moving*. This is a bad idea, as it's much simpler to do something which works independently of movement.

First, if you don't have it already, you should have a data structure which stores *loaded chunks* keyed on their *chunk coordinates*. Example of chunk coordinates: The chunk containing the "middle" of your world is at coordinates `(0, 0)`. Then the chunk immediately to the right of that one is `(1, 0)`, and the one below that one is `(1, 1)`, and so on. Then you can use those coordinates as keys in a hash-table or similar to keep references to the chunks you've loaded.

Every frame, do the following:

1. Figure out the coordinates of the chunk which should be visible in *the upper left corner of the screen*. For example, if the upper left corner has screen coordinates `(0, 0)`, and your camera position is expressed in pixels (likely in a sprite-based game), then divide the camera position by the tile size, and the chunk size, to obtain chunk coordinates. On the other hand, if you're using 3D-style graphics and the tile size is just 1, then you just divide by the chunk size.
2. Do the same for the bottom-right corner of the screen (same computation but offset by the screen size). You now have **four chunk coordinates** which can be interpreted as the corners of a **rectangle of chunks** which will be always at least the size of the screen.
3. Loop over the coordinates of each chunk in the rectangle (just two nested loops). Look it up in the table of loaded chunks; if not found, load/generate it. Draw the chunk, positioning it according to its coordinates and the camera position.
4. Each chunk which is loaded but was *not* drawn in the previous step (you can use a "was drawn" flag on each chunk to figure this out) **may be unloaded** (but you probably want to keep some around as a cache in case the player is moving back and forth near a boundary).

This is a general algorithm for 2D rectangular chunks and a 2D rectangular camera view. It sounds like in your case your chunks are larger than the camera, so you always have at at most four chunks visible; this *could* simplify things, but I recommend using this algorithm which avoids having any special cases until you're more confident in how to tweak things.

Note that this algorithm **does not care how the camera is moving, or when it crosses a boundary**. It only makes sure that the *current frame* is drawn correctly, regardless of what happened before. (I suspect trying to make use of the previous position/movement is part of your original problem.) This also means that it can handle arbitrary movement like teleporting or respawning.
> 1 votes

---
Tags: tiles, platformer
---


title: Convert int to Color

text:
# Question
Title: Convert int to Color
I am right now developing paint application in andengine because some features are only possible with andengine.

For this I have used color dialog box to use user selected color but that dialog box return int value. But my sprite use Color class for setting color.

Reverse thing is possible using,

```
getColor().getABGRPackedInt()

```

Using this I provide source color but after choosing I can't able to receive chosen color.

At present I use following dialog box.

Android Color Picker

So I need to convert int value return by the dialog in Color class object. So members please help me in this.

# Answer
> 6 votes
Color value basically consists of 4 single byte channel values, these 4 value represent R, G, B and transparency(A) of that color. An integer value is also a 4 byte value, so these two types are used interchangeably. Based on the name of the function you are using I'm guessing the R is packed as the byte with lowest value, and A is the highest value byte. so to convert a color into packed integer format that function is basically computing

```
result = R + G * 256 + B * 256 * 256 + A * 256 * 256 * 256

```

this means the inverse function would be something like this:

```
R = packedValue % 256;
G = (packedValue / 256) % 256;
B = (packedValue / 256 / 256) % 256;
A = (packedValue / 256 / 256 / 256);

```

I might be wrong about the packing order but the idea behind that function is what I explained.

# Answer
> 1 votes
You will need to use Java's bitwise operators to separate the color channels from the int value. Have a look at this: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

---
Tags: andengine
---


# Question
Title: Do I have to keep textures in Android games smaller than 1024^2?
I have read tips in books and article that point out, if you are making a game for Android, make sure your textures are =\< 1024^2, or you'll not reach all your potential customers.

I have never found a concrete statistic that proves this claim. What are we talking about, here, 5% of Android devices only support 1024? 10%? 80%?

# Answer
> 3 votes
take a look at these stats http://stats.unity3d.com/mobile/gpu.html

scroll down to gpu model start google ing each gpu and see max texture size for each one

i'll do the first one for mali 400 is 4096x4096

now assuming all drivers that have this gpu support this size you're in luck you already have 30% of the market

Good luck with your game.

---
Tags: graphics, gpu
---


# Question
Title: Best 2D graphics API when the only functionality needed is writing individual pixels to the framebuffer
I have been dreaming for years about programming a relatively simple, but from the standpoint of the game engine, a very unusual 2D game engine for the PC platform. I am planning to use either C or C++ for the core engine, and maybe later expose the engine to a scripting language such as ruby, python or lua (for higher level programming of the content of the game). Not having ever programmed any noteworthy GUI applications let alone games, i am not really sure about which API:s to select for the task.

The requirements for the API:s are unlike other 2D games, since instead of drawing sprites, glows etc. using OpenGL, Allegro or SDL, i only need to be able to open a window instance, clear the framebuffer, write individual pixels to it, and then draw everything to the screen. Thus the API needs to be really really fast, and no additional functionality is needed from the API.

Additionally i need user input and sound output, through an additional API if necessary. Do you have any suggestions for the best course of action?

# Answer
> 0 votes
Well I think that using SDL (yes I read your question to the end : you do not need all the extra API stuff from SDL) is still a viable option for what you want to do, because SDL is fast and reliable.

If you don't want to use the rest of the API, then fine, just leave it where it is. But SDL will be fast enough for you I believe. It has pixel manipulation and sound (through the use of sdl\_mixer).

Now, you can go even deeper by using directX I guess, but isn't that too much harasment for what you want to do?

EDIT:

There's also SFML that also has pixel manipulation & sound. It is "like SDL" (very roughly) but more object oriented.

EDIT 2:

Forgot about user input, I find SFML better for that (it's just personal taste though), though the recent SDL2.0 simplified this task a bit.

# Answer
> 0 votes
I would recommend just using OpenGL. There's a few ways I could see you going about doing this

1. Use a stream VBO with render mode set to points
2. Use glDrawPixels
3. Put your pixels in a texture and render it on a quad
4. Draw a screen sized textured quad and do all your drawing via a fragment shader (probably a bad idea)

The list goes on. I would highly recommend OpenGL over SDL or DirectX

EDIT

I should clarify that I don't mean using only OpenGL. Add in a framework like GLFW or use OpenGL for QT to handle your window creation. Don't use GLUT. Really. Additionally, GLEW will handle platform specific extensions quite nicely

---
Tags: 2d
---


# Question
Title: Grouping entities of the same component set into linear memory
We start from the basic systems-components-entities approach.

Let's create **assemblages** (term derived from this article) merely out of information about **types of components**. It is done dynamically at runtime, just like we would add/remove components to an entity one by one, but let's just name it more precisely since it is only about type information.

Then we construct **entities** specifying **assemblage** for every of them. Once we create the entity, its assemblage is immutable which means we cannot directly modify it in place, but still we can obtain existing entity's signature to a local copy (along with contents), make proper changes to it, and create a new entity out of it.

Now for the key concept: whenever an entity is created, it is assigned to an object called **assemblage bucket**, which means that all entities of the same **signature** will be in the same container (e.g. in std::vector).

Now the **systems** just iterate through every bucket of their interest and do their job.

This approach has some advantages:

* components are stored in a few (precisely: number of buckets) contiguous memory chunks - this improves memory friendliness and it is easier to dump whole game state
* systems process components in a linear manner, which means improved cache coherency - bye bye dictionaries and random memory jumps
* creating a new entity is as easy as mapping an assemblage to bucket and pushing back needed components to its vector
* deleting an entity is as easy as one call to std::move to swap the last element with the deleted one, because order doesn't matter at this moment

If we have a lot of entities with completely different signatures, benefits of cache coherency kind of diminish, but I don't think it would happen in most applications.

There is also a problem with pointer invalidation once vectors are reallocated - this could be solved by introducing a structure like:

```
struct assemblage_bucket {
    struct entity_watcher {
        assemblage_bucket* owner;
        entity_id real_index_in_vector;
    };

    std::unordered_map<entity_id, std::vector<entity_watcher*>> subscribers;

    //...
};

```

So whenever for some reason in our game logic we want to keep track of a newly created entity, inside the bucket we register an **entity\_watcher**, and once the entity has to be std::move'd during removal, we lookup its watchers and update their `real_index_in_vector` to new values. Most of the time this imposes just a single dictionary lookup for every entity deletion.

**Are there any more disadvantages to this approach?**

Why is the solution nowhere mentioned, despite being pretty obvious?

**EDIT**: I'm editing the question to "answer the answers", since comments are insufficient.

> you lose the dynamic nature of pluggable components, which was created specifically to get away from static class construction.

I don't. Maybe I did not explain it clearly enough:

```
auto signature = world.get_signature(entity_id); // this would just return entity_id.bucket_owner->bucket_signature or so
signature.add(foo_component);
signature.remove(bar_component);
world.delete_entity(entity_id); // entity_id would hold information about its bucket owner
world.create_entity(signature); // automatically assigns new entity to an existing or a new bucket

```

It's as simple as just taking existing entity's signature, modifying it and uploading again as a new entity. *Pluggable, dynamic nature*? Of course. Here I'd like to emphasize that **there is only one "assemblage" and one "bucket" class. Buckets are data-driven and created at runtime in an optimal quantity.**

> you'd need to go through all buckets that might contain a valid target. Without an external data structure, collision detection could be equally as difficult.

Well, this is why we have the aforementioned *external data structures*. The workaround is as simple as introducing an iterator in System class that detects when to jump to next bucket. The *jumping* would be purely transparent to the logic.

# Answer
> 7 votes
You have essentially designed a static object system with a pool allocator and with dynamic classes.

I wrote an object system that works almost identically to your "assemblages" system back in my school days, though I always tend to call "assemblages" either "blueprints" or "archetypes" in my own designs. The architecture was more of a pain in the butt than naive object systems and had no measurable performance advantages over some of the more flexible designs I compared it to. The ability to dynamically modify an object without needing to reify it or reallocate it is hugely important when you are working on a game editor. Designers will want to drag-n-drop components onto your object definitions. Runtime code might even have need to modify components efficiently in some designs, though I personally dislike that. Depending on how you link up object references in your editor, simply being able to add and remove components to existing objects with zero extra shenanigans will come in handy.

You're going to get worse cache coherency than you think in most non-trivial cases. Your AI system for instance doesn't care about `Render` components but ends up being stuck iterating over them as part of each entity. The objects being iterated over are larger, and cacheline requests end up pulling in unnecessary data, and fewer whole objects are returned with each request). It'll still be better than the naive method, and the naive method object composition is used even in big AAA engines, so you probably don't *need* better, but at least don't go thinking you can't improve it further.

Your approach does make most sense for *some* components, but not all. I dislike ECS strongly because it advocates always putting each component in a separate container, which makes sense for physics or graphics or whatnot but no sense at all if you allow multiple script components or composable AI. If you let the component system be used for more than just built-in objects but also as a way for designers and gameplay programmers to compose object behavior then it can make sense to group together all AI components (which will often interact) or all script components (since you want to update them all in one batch). If you want the most performant system then you're going to need a mix of component allocation and storage schemes and put in the time to figure out conclusively which is best for each particular type of component.

# Answer
> 4 votes
What you've done is re-engineered C++ objects. The reason why this feels obvious is that if you replace the word "entity" with "class" and "component" with "member" this is a standard OOP design using mixins.

1) you lose the dynamic nature of pluggable components, which was created specifically to get away from static class construction.

2) memory coherence is most important within a data type, not within an object unifying multiple data types in one place. This is one of the reasons that component+systems were created, to get away from the class+object memory fragmenting.

3) this design also reverts to C++ class style because you are thinking of the entity as a coherent object when, in a component+system design, the entity is merely a tag/ID to make the inner workings understandable to humans.

4) it is just as easy for a component to serialize itself than a complex object to serialize multiple components within itself, if not actually easier to keep track of as a programmer.

5) the next logical step down this path is to remove Systems and put that code directly into the entity, where it has all the data it needs to work. We can all see what that implies =)

# Answer
> 3 votes
Keeping like entities together isn't as important as you might think, which is why it's hard to think of a valid reason other than "because it's a unit". But since you are really doing this for cache coherency as opposed to logical coherency, it might make sense.

One difficulty you could have is interactions between components in different buckets. It's not terribly straight forward to find *something* your AI can shoot at for example, you'd need to go through all buckets that might contain a valid target. Without an external data structure, collision detection could be equally as difficult.

To continue about organizing entities together for logical coherency, the only reason that I could have to keep entities together is for identification purposes in my missions. I need to know if you have just created entity type A or type B, and I get around this by... you guessed it: adding a new component that identifies the assemblage that put this entity together. Even then, I'm not gathering all the components together for a grand task, I just need to know what it is. So I don't think this part is terribly useful.

---
Tags: architecture, performance, entity-system, entity-component
---


title: Voxel Performance

text:
# Question
Title: Voxel Performance
So Im trying to make a minecraft style voxel game to learn OpenGL, but Im running into performance issues. I found this thread : https://stackoverflow.com/questions/4995652/3d-occlusion-culling where the author says he's drawing 250,000 cubes with an okay framerate. However, I can do about 3000 ish with the same framerates. I found another thread in which someone said that you should combine visible faces into a mesh. Does that mean you put all the vertices into one vertex buffer? If so, how do I pass texture data?

# Answer
Yeah, you should try to batch as much as possible, that is, combining the more cubes you can, in the least amount of vertex buffers you can. This is a good resource on the matter of Voxel Meshing. I recomend you to follow the culling algorithm, even older versions of minecraft used it and stood well at good framerates.

To use more than one texture, you can use a texture atlas to fake that. Some devices might even support multi-texturing in a single batch, which would be easier to work with, though the atlas will give you the best performance!
> 3 votes

---
Tags: c++, opengl, performance, minecraft-modding, voxels
---


# Question
Title: LWJGL multiple keyboard/mouse input checks
As in many game libraries such as LWJGL, you can check mouse/keyboard events with Mouse.isButtonDown or Keyboard.IsKeyDown.

I want to check for button/key presses, not if it's currently pressed down (if that makes any sense) so I use Keyboard.next() and Mouse.next(). This works fine, except if you have multiple places where you want to do this check.

So if you do Mouse.next once for all the events in the 'queue', the queue is empty and future Mouse.next's don't return anything.

What would be the solution for this? Create a wrapper around the Keyboard class and save the keystate? If so, how can I save that state? Couldn't find anything in the javadocs.

Thanks in advance.

# Answer
> 5 votes
Accordingly to http://legacy.lwjgl.org/javadoc/org/lwjgl/input/Keyboard.html you can make this like this:

```
while (Keyboard.next())
{
    bool pressed = Keyboard.getEventKeyState();
    int key = Keyboard.getEventKey();
    if(pressed) processKeyPress(key);
    else processKeyRelease(key);
}

```

For more detail, you can google "Buffered input vs Unbuffered input" Buffered is when you receive the events of what happened, and unbuffered is when you have to poll the key state with "isKeyDown" at every frame.

Edit:

For being able to use the events in more than one place, do the following:

```
class KbEvent
{
    public final bool Press;
    public final int KeyID;
    public KbEvent(bool press, int keyID)
    {
        Press = press; KeyID = keyID;
    }
}

//On your game definition
Vector<KbEvent> KeyboardEvents;

//On your game loop
KeyboardEvents.clear();
while (Keyboard.next())
{
    KeyboardEvents.add(new KbEvent(Keyboard.getEventKeyState(), Keyboard.getEventKey()));
}

//Wherever you want to read all keyboard input:
for (KbEvent ev : KeyboardEvents)
{
    if(ev.Press) processKeyPress(ev.KeyID);
    else processKeyRelease(ev.KeyID);
}

```

practically the same extends for mouse, with just more variables.

This way, you'll save the current frame events elsewhere, and the re-use them everywhere you want. I don't know exactly HOW java handles the Vector class, but on C++ this should have no impact on frame rate.

# Answer
> 1 votes
I don't know the details for LWJGL, but in XNA, developers need to create a wrapper that keeps track of the last state of the mouse & keyboard, and the current state. That is the only way to detect a "press" or a "release". I would look for a way to remember what keys/buttons were pressed down, then use that to determine if something has changed.

---
Tags: opengl, lwjgl, input, mouse, keyboard
---


# Question
Title: How is destructable terrain made in SDL?
I'm looking for terrain that gets removed in chunks (like in Worms, of instance). How do you do this in SDL?

# Answer
Something like this usually utilizes simple texture operations. The basic promise: Use a texture as your map. If there's full alpha, you consider a pixel to be air. If there's not full alpha, you consider a pixel to be ground. Different thresholds can be set to achieve things such as transparency.

If you want solid drawn parts that are translucent or have different properties (like ice) you'll most likely want two textures: One to display, one for game logic. The game logic one could be as simple as an array of bytes, where each byte represents one pixel. You can then use bitwise operations to determine terrain attributes like solid, frozen, bouncy, indestructible, etc.

Overall, the whole thing is rather easy to realize:

* Check pixels do determine whether they're solid (are visible).
* For explosions simply draw filled circles of full alpha.
* For gun shots simply draw lines using full alpha.
> 1 votes

---
Tags: physics, sdl, terrain, terrain-rendering
---


# Question
Title: LibGDX Box2D Body and Sprite AND DebugRenderer out of sync
I am having a couple issues with Box2D bodies. I have a GameObject holding a Sprite and Body. I use a ShapeRenderer to draw an outline of the Body's and Sprite's bounding boxes. I also added a Box2DDebugRenderer to make sure everything's lining up properly.

My problem is the Sprite and Body at first overlap perfectly, but as I turn the Body moves a bit off the sprite then comes back when the Car is facing either North or South.

Here's an image of what I mean: (Not sure what that line is, first time to show up) BLUE is the Body, RED is the Sprite, PURPLE is the Box2DDebugRenderer.

Also, you probably noticed a purple square in the top right corner. Well that's the Car drawn by the Box2D Debug Renderer. I thought it might be the camera but I've been playing with the Cameras for hours and nothing seems to work. All give me weird results.

Here's my code:

**Screen:**

```
public void show() {
        // --------------------- SETUP ALL THE CAMERA STUFF ------------------------------ //
    battleStage = new Stage( 720, 480, false );

    // Setup the camera. In Box2D we operate on a meter scale, pixels won't do it. So we use
        // an Orthographic camera with a Viewport of 24 meters in width and 16 meters in height.
    battleStage.setCamera( new OrthographicCamera( CAM_METER_WIDTH, CAM_METER_HEIGHT ) );
    battleStage.getCamera().position.set( CAM_METER_WIDTH / 2, CAM_METER_HEIGHT / 2, 0 );

    // The Box2D Debug Renderer will handle rendering all physics objects for debugging
    debugger = new Box2DDebugRenderer( true, true, true, true );
    //debugCam = new OrthographicCamera( CAM_METER_WIDTH, CAM_METER_HEIGHT );
}

public void render(float delta) {

    // Update the Physics World, use 1/45 for something around 45 Frames/Second for mobile devices
    physicsWorld.step( 1/45.0f, 8, 3 );     // 1/45 for devices

    // Set the Camera matrices and clear the screen
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    battleStage.getCamera().update();

    // Draw game objects here
    battleStage.act(delta);
    battleStage.draw();

    // Again update the Camera matrices and call the debug renderer
    debugCam.update();
    debugger.render( physicsWorld, debugCam.combined);

    // Vehicle handles its own interaction with the HUD

    // update all Actors movements in the game Stage
    hudStage.act( delta );
    // Draw each Actor onto the Scene at their new positions
    hudStage.draw();
}

```

**Car: (extends Actor)**

```
public Car( Texture texture, float posX, float posY, World world ) {

    super( "Car" );

    mSprite = new Sprite( texture );
    mSprite.setSize( WIDTH * Consts.PIXEL_METER_RATIO, HEIGHT * Consts.PIXEL_METER_RATIO );

    mSprite.setOrigin( mSprite.getWidth()/2, mSprite.getHeight()/2);    // set the origin to be at the center of the body

    mSprite.setPosition( posX * Consts.PIXEL_METER_RATIO, posY * Consts.PIXEL_METER_RATIO );    // place the car in the center of the game map

    FixtureDef carFixtureDef = new FixtureDef();

    mBody = Physics.createBoxBody( BodyType.DynamicBody, carFixtureDef, mSprite );
}

public void draw() {
    mSprite.setPosition( mBody.getPosition().x * Consts.PIXEL_METER_RATIO, mBody.getPosition().y * Consts.PIXEL_METER_RATIO );
    mSprite.setRotation( MathUtils.radiansToDegrees * mBody.getAngle() );
    // draw the sprite
    mSprite.draw( batch );
}

```

**Physics: (Create the Body)**

```
public static Body createBoxBody( final BodyType pBodyType, final FixtureDef pFixtureDef, Sprite pSprite ) {

    float pRotation = 0;
    float pWidth = pSprite.getWidth();
    float pHeight = pSprite.getHeight();

    final BodyDef boxBodyDef = new BodyDef();
    boxBodyDef.type = pBodyType;

    boxBodyDef.position.x = pSprite.getX() / Consts.PIXEL_METER_RATIO;
    boxBodyDef.position.y = pSprite.getY() / Consts.PIXEL_METER_RATIO;

    // Temporary Box shape of the Body
    final PolygonShape boxPoly = new PolygonShape();
    final float halfWidth = pWidth * 0.5f / Consts.PIXEL_METER_RATIO;
    final float halfHeight = pHeight * 0.5f / Consts.PIXEL_METER_RATIO;
    boxPoly.setAsBox( halfWidth, halfHeight );  // set the anchor point to be the center of the sprite

    pFixtureDef.shape = boxPoly;

    final Body boxBody = BattleScreen.getPhysicsWorld().createBody(boxBodyDef);
    boxBody.createFixture(pFixtureDef);

}

```

Sorry for all the code and long description but it's hard to pin down what exactly might be causing the problem.

# Answer
> 1 votes
I've had similar problem. The problem is caused by you convert a body position by a Consts.PIXEL\_METER\_RATIO, but you do not convert a render camera to handle the conversion.

Solution:

debugCam.scale(Consts.METER\_PIXEL\_RATIO, Consts.METER\_PIXEL\_RATIO, 0); debugger.render(physicsWorld, debugCam);

---
Tags: 2d, java, physics, box2d, libgdx
---


# Question
Title: Why are most characters all the same height in games?
In the majority of video games I play, I notice that NPC's are the same height. What's up with that?

It kinda takes me out of the experience, when I see ten people in a row that are 5 foot 8. Anyone else notice this, or am I crazy?

# Answer
> 40 votes
Making all character models the same size has a lot of benefits when doing poses and animations.

* Imagine, for example, a sit-down-on-chair animation. A character with longer legs has a different sitting pose than one with shorter legs.
* Or a character grabbing something. When the characters have different heights, their hands will be on different positions when they do the grabbing animation, so they might not actually touch the item they grab for.
* When walking under an obstacle, a large character would have to bow to avoid their head clipping through the object. But a short character doing the same although they have plenty of head-space would look silly.
* In a shooter, the guns of the characters would be on different heights during the shooting animation, so either the projectile paths wouldn't match the muzzle of the guns, or you would have the odd effect of some characters being able to shoot over a cover and some being unable to do the same, just because they can't be bothered to lift their guns a few cm higher.

You could solve this by having procedural animations (inverted kinematics) or by doing the animations for each character individually, but that would be a lot of additional work.

Another thing to keep in consideration is game balance. This is usually not that relevant for NPCs in a single player game. But in a competitive multiplayer game, selecting a smaller character can give the player an unfair advantage because they are harder to spot and harder to hit. So character size is no longer just an aesthetic factor but also a game balance factor. A good example where this was used intentionally is Team Fortress 2. The Heavy is larger than all other characters, so they can use him as cover. The Scout, on the other hand, is the shortest of all characters, which is great for his playstyle which is designed around avoiding enemy fire through erratic movement.

---
Tags: game-design, 3d-modeling
---


title: re-using objects

text:
# Question
Title: re-using objects
I'm working with openGL ES 2.0 on Android and I've created a custom Quad class.

This allows me to make a sprite object like so:

```
Quad mySprite = new Quad();
mySprite.setSize(w,h);
mySprite.setTexture(myTexture);

```

Then, I can draw it like so:

```
mySprite.draw();

```

The `draw()` method uses mySprite's internal x and y coordinates which are declared within the Quad Class.

I also have another method which allows me to draw the quad specifying other 'external' co-ordinates like so:

```
mySprite.draw(x,y);

```

Now let's say that on one of the levels of my game, I have the need to draw 3 of these sprites at different positions and move them all independently of each other.

At the moment, I think I have 2 options, which are:

1) Create different quad's with the same texture and use them with their internal coordinates or....

2) Use the same object but hold an array of external coordinates and just draw it three times at different places.

My preferred option would be 1 because it's just cleaner to work with but clearly inefficient as I'm having to create multiple objects that are essentially the same (inefficient memory-wise?)

So is there a way of using just one version of the sprite? Maybe using clones or something along those lines so that I can just keep track of each clone's internal position and states rather than using external arrays?

# Answer
Do not draw the same Sprite to represent the image at multiple locations. Holding the coordinates somewhere else - this defeats the purpose of object-oriented programming. The most memory is taken by the texture (or texture region) itself, the overhead of your custom class is negligible. Unless you will be making millions of Quads, do not worry about memory. It will grow as needed.

Premature optimization is the root of all evil, however there is one performance consideration you can make. If you are going to create a lot of objects and immediately throw them away, you can use Object Pool Pattern to reuse these objects, especially if there is any CPU intesive initialization and clean up taking place. The performance is also affected later during garbage collection, which can create peaks in CPU usage. Using Object Pool prevents that, but one must be very careful to recycle the objects properly.

I'd recommend your option 1) and don't bother with the Object Pool unless you hit the CPU usage spikes. Also the modern Java Garbage Collector is very well optimized for short-lived small objects, make use of it.
> 2 votes

---
Tags: android, sprites, opengl-es2
---


# Question
Title: How to set the object's world position in bullet?
In my Ogre3d application I am first changing the parent of a node like this:

```
// save object "Cube" into node*; then ...
Vector3 absPos(node->_getDerivedPosition());
Quaternion absOrient(node->_getDerivedOrientation());
node->getParent()->removeChild(node);
m_pSceneMgr->getRootSceneNode()->getChild("NewParentNode")->addChild(node);
node->_setDerivedPosition(absPos);
node->_setDerivedOrientation(absOrient);

```

The idea is that after the parent node has been changed the object's position and orientation should remain the same. However, even though this is working fine, it seems that afterwards bullet is again overwriting the object's position. If I remove the object's rigid body from bullet, then everything works fine. If not, then as soon as I change the parent the object's position is changed.

So I thought I simply need to update bullet as well:

```
btRigidBody* rigid = getBtRigid(String("Cube"));
btTransform tr = rigid->getWorldTransform();
tr.setOrigin(BtOgre::Convert::toBullet(absPos));
tr.setRotation(BtOgre::Convert::toBullet(absOrient));
rigid->setWorldTransform(tr);

```

However, that doesn't work, the object still jumps to another position after the parent is changed. But it is related to bullet for sure, because as said if I remove the object from bullet physics, then it works.

Any ideas what I am missing here?

# Answer
> 0 votes
Found the problem: I forgot to update the bullet motion state. After removing the rigid from bullet and re-adding it with the updated motion state it works now.

# Answer
> 1 votes
I would try updating the motion state transform as well, since it's a rigid body:

```
btRigidBody* rigid = getBtRigid(String("Cube"));
btTransform tr = rigid->getMotionState()->getWorldTransform();
tr.setOrigin(BtOgre::Convert::toBullet(absPos));
tr.setRotation(BtOgre::Convert::toBullet(absOrient));
rigid->getMotionState()->setWorldTransform(tr);

```

You should check your physics update loop, how are you handling rigid bodies and their corresponding scene nodes? I update mine like so:

```
btVector3 pos = body->getCenterOfMassPosition();
node->setPosition((float)pos[0], (float)pos[1], (float)pos[2]);

btQuaternion orientation = body->getOrientation();
node->setOrientation(Ogre::Quaternion(orientation.w(), orientation.x(), orientation.y(), orientation.z()));

```

Also, if you don't already, you should use the BtOgre debug drawer, it's really helpful for things like this.

---
Tags: ogre, bullet-physics
---


title: 2D sort for inventory items?

text:
# Question
Title: 2D sort for inventory items?
I asked this question some time ago. Now I ended up with just a sorter method that will sort the items based on their bulkiness/nSlotsRequired. Here's what I'm doing:

1. I store all the items I have in a one-dimensional array.
2. Empty the bag.
3. Sort the array.
4. And start putting them back into the bag again.

Now, this is clearly not the best way to sort something, I mean, if I have an array I wouldn't just store its values somewhere else, empty it, sort the other array and then copy them back. Even if I had a 2D array, I would sort it by considering it a 1D array. 1st element's index is 0, 2nd is 1, 3rd is 2, 4th is 3, 5th is 4, etc.

General formula to convert from a 1D index to a 2D:

* row\_index = \_1D\_index % nRows;
* col\_index = \_1D\_index % nCols;

For example the 5th element has the 1D index of 4, to get the row: 4 % 3 = 1, to get the col, 4 % 4 = 0, so your element is at 1,0. What's the point of all this? Now you can just make a function

```
int GetAt(int index)
{
    return array[index % nRows][index % nCols];
}

```

and something along the lines of:

```
void Swap(int index1, int index2)
{
   int r1 = index1 % nRows;
   int c1 = index1 % nCols;
   int r2 = index2 % nRows;
   int c2 = index2 % nCols;
   int temp = array[r1][c1];
   array[r1][c1] = array[r2][c2];
   array[r2][c2] = temp;
}

```

But the problem is: 1- items take more than one slot. 2- Even if I were to just swap them in a way that they're sorted, they still have to get to their positions, I mean, the biggest one would go to the top left, beside it is the smaller, etc.

Taking notice that:

1. I already have an array of the items' indices/places in the bag, so I don't have to look for them.
2. I have an array of the available slots in the bag, that way I don't have to go through all of them to find where items fit. I just start from the next available slot placing the items (I update those arrays everytime I add/remove an item)

is there a more efficient way of doing this? Can I just, sort the items right away without having to empty the bag, store them somewhere else, etc? - It would make more sense. I couldn't think of a way :/ Maybe sort only the items that needs sorting? Thanks for any help.

EDIT: Here's what I have so far (sorting feature @~9:00)

# Answer
@Guys: I indirectly optimized the algorithm (the way I add/remove items, free slots, and stuff like that) and used yield return null in 2 positions (during the loop emptying the bag, and the one filling it) and it seems I'm getting quite good results. I mean, it doesn't happen instantly, but there's no frame drop whatsoever. So it's pretty smooth now, happy with it. Thanks for anyone who helped :)
> 0 votes

---
Tags: c#, unity, algorithm, optimization, inventory
---


title: How to hook into a game written in C++

text:
# Question
Title: How to hook into a game written in C++
Okay, so there is a game I want to mod and it is written in C++. And from what I know you can't just decompile and edit the code like Java else it just decompiles into Assembly. So I was wondering how could you actually go about modding a game entirely written in C++ without having to spend hours looking at Assembly instructions. Thanks in advance

# Answer
> 4 votes
The most common solution is to use a hex editor and decompiled assembly and then poking at various bits of data or code after using the assembly to figure out *which* bits to poke and in which way.

For more complex changes the common "attack" is to hijack a DLL. For example, if the game loads D3D, you could trick the system into loading a different DLL in its place. This is non-trivial as you not only must implement your changes but must also whatever DLL you hijacked (which you might do by passing calls through to the "real" DLL, but this is non-trivial). You can also inject a DLL in place of the application's normal entry point, which is a bit less cumbersome usually but not always.

Even then, all you have done is given yourself the ability to inject code into the game's process. If you actually want to inject hooks into the code, modify data, etc., you have to find places that such is even possible. This is going to go back to reading Assembly code and decoding how the game works. Anything you do is likely to change or break any time the game is updated, of course.

The code to project like NVSE are online and available. If in doubt, see what they did for code injection. Again, actually making the mod you want will require poking around in the guys of the assembly.

For what you're trying to do, it may or may not be simple. Depending on how the server is written, there may just be a hard-coded limit of 4 during login. Or the assumption of only 4 players might be made all throughout the code and various data structures. Increasing the limit might require "only" reading the assembly to find where this limit is imposed to change it with a hex editor, or it might require replacing a large number of non-trivial sections of code which will take you months just to find.

Honestly, your best bet is to just talk to the author of CubeWorld about it. If it makes sense, maybe they'll increase the limit or make it a config option. A proper modding API in a future version might even be on the table.

# Answer
> 0 votes
If a game is written in C++ *but* the code is not provided, things get complicated fast. The easiest way to go about changing the game is usually to attack any resource files. Some games have folders with .bin or .dat files that are all the resources compressed together. Hex editors and creative data munging would be the way to go about looking at those.

---
Tags: c++, modding
---


# Question
Title: Cocos2D SpriteBatchNode vrs. SpriteFrameCache… I do not see any performance difference
I have tried using both ways...

1. adding the .png file on the cache with SpriteFrameCache..
2. adding .plist with spritebatchnode adding the correspoding .png file, I didnt see any performance difference.

In my test I keep adding and adding objects with the same image.. in this case a bullet... eventually the app crashed because it ran out of memory. Same thing happened to both situations with SpriteFrameCache and SpriteBatchNode they both dropped FPS to 30(when its supposed to be 60) and then just crashes...I understand the scenario is not real.And obviously its destiny its to crash if I just keep adding images without destroying objects that are no longer in use...but the question remains.

I saw the same performance issue, however I read that SpriteBatchNode makes only one draw call making it best performance practice. Has anyone tried and can confirm the performance difference and exactly how can you prove this performance difference in code and in the app?

# Answer
Check this blog post of "Master" Steffen :).

It seems to be all about OpenGL draw calls and OpenGL state changes of the images and how large the images are and if they have transparency or not.

Try to use several "big" background images in parallax and compare the fps rate with or without batchnode.

Following I report some extracts from Steffen's post as the content of this answer should belong to him :):

**On number of draw calls:**

> it matters a whole lot how much one sprite differs from the previous one and which OpenGL states it changes (cit. Steffen Itterheim, blog post 8th September 2011)

Using 10 large sprites (with lots of transparency, pixel size: 480×320) and not sprite batching the fps rate went down to 15fps (see details of the article) but

> Once I enabled sprite batching the framerate went up to 60 fps (cit. Steffen Itterheim, blog post 8th September 2011)
>
> (...) for anyone who is composing their background images of multiple images (eg for parallax scrolling), sprite batching can make a huge difference even if you only have 3 or 4 different background images.(cit. Steffen Itterheim, blog post 8th September 2011)
>
> (...) In fact, it’s the larger images that you will want to draw all from the same texture atlas to improve sprite batching performance. (cit. Steffen Itterheim, blog post 8th September 2011)

Hope it helps
> 2 votes

---
Tags: ios, cocos2d
---


title: How not to break licence laws?

text:
# Question
Title: How not to break licence laws?
I have an idea for a game. Also I have almost everything worked out considering coding.

What interests me the most is how can I know if that game can be published.

As it would be for iOS and android, these markets are of the geratest interest for me.

I found on apples store something similair to what I would make and it's published by some big game developer. How can I be sure I am not breaking any laws when publishing the game? Can I make a game like board game 'Risk'?

I don't have any knowledge considering licencing. This game would be avaliable for free, with an option to donate, so money isn't my objective (but it won't hurt) \[:

# Answer
> 7 votes
There are three areas that you must take care of:

1. Copyright
2. Patents
3. Trademarks

Even if you break something, you might get away with it. The company legal department can contact you and ask you nicely to remove the infringement. Or they can directly sue you, especially when the company is making profit by holding and licensing patents.

## Copyright

Every piece of art, source code or documentation is copyrighted by the author or the game studio. By using the original art you not necessarily breaking the copyright. Copyright gives the author exclusive right to allow or disallow anyone else to use the art. In case of commercial games, read the EULA to prevent any infringement. It is safe to assume that you can't use any original media files, but you can contact the authors - they might be willing to make an exception.

## Patents

Copyright protects artwork, patents protect ideas. Even a simple idea like how to treat game achievments on consoles can be (and IS!) patented. You can read about some of the well known game patents here. You can never be sure that you are breaking some patent unless you know all of them. You need a legal department to make sure you are not, it's not an easy job. If there is any patent infringement, the patent holder will most likely contact you and ask you to either license their patent or remove it from your software. I have seen this happen several times, but not in a game. In case you dispute their right, they will most likely sue you. However as stated above, some companies make money by sueing other companies over patent infringement, so they might not even issue a warning.

## Trademarks

Trademarks protect brands and names. You can't use identical or confusingly similar name to the trademarked one. Trademarks are usually limited to one industry, unless the trademark holder broadens (read: pays more) the trademark. E.g. you might be ok with your McDonald's shoe repair, but not with McDoland's fast-food.

---

But even if you really take care of all this, you might run into problems. Depends on how much revenue you are making and how much revenue is the other company losing. As an example, look at the image below. It is from one of the big lawsuits recently, EA vs. Zynga. No original artwork was used, no patents and no trademarks infringements. They settled the suit without anyone winning.

See also: Wikipedia article Video Games Clone

# Answer
> -4 votes
It is true that one is allowed to make games that are similar to others. You are not allowed to use any copyrighted materials though, this includes names, art, music, sounds and any other content. I have a game published on the windows phone marketplace called "Casino Dice" which is similar to a game that is registered to Hasbro. I had the name the same as theirs and received a letter asking me to change the name as they have trademarked the name.

I changed the name and all is well.

---
Tags: legal, licensing, publishing
---


# Question
Title: Effecient finding of long-range spotting targets
I'm creating a top-down 2d strategy game, with a square grid map. So far, I've used Bresenham's line drawing algorithm in a circle to determine what's in LOS of each unit, and then targedt one of the targets in the circle. Now I find that this limits my units to shoot only at targets that they see. I want to extend my targeting algorithm to target any other unit in range of my weapon, even if they're out of sight range of this given unit, if they're "spotted" by another friendly unit. In other words, I want to enable usage of weapons with ranges longer than sight range. Is there a better way than iterating over all sighted units and computing range and LOSto each of them?

# Answer
If you store the units for each side in an quadtree, you can cheaply avoid iterating over enemy units that are beyond range (assuming your units can't shoot over more than half the board!).

If you store your unit list in each quadtree sorted by whether its been seen or not (e.g. just have two lists), you only have to compute the line-of-sight (LoS) between a unit and an enemy if its potentially unspotted.

And if you track who saw each who first, you only have to recompute the LoS when one of the pair moves.

Tangentially related, here's how to efficiently compute the visible *board* for a unit (my blog). If you only want to compute LoS between units, and don't need tile visibility (e.g. fog-of-war), then checking LoS using Bresenhams is likely a better bet.

Small complication: Bresenhams doesn't actually visit all tiles on a line! It will miss some. If you need a precise computation, look at my own question (3D, but the problem is the same in 2D).
> 1 votes

---
Tags: 2d, line-of-sight
---


title: Angle to Vector3?

text:
# Question
Title: Angle to Vector3?
I am working on getting my directional lights to match the sun in my atmospheric scattering shader.

I have a float that ranges from 0 to 6.28 (TwoPi). How would I calculate a vector3 from this angle?

The reason I need an angle is because my light angle is created like this:

```
LookAt(new Vector3(100, 100, 100), Vector3.Zero, Vector3.Forward);

```

Thanks.

# Answer
> 1 votes
The angle is an angle in 2D plane, correct? Then you need simple trigonometry:

```
Vector3 myVector = new Vector3(Math.cos(angleFloat), Math.sin(angleFloat), 0);

```

Look at this image. In your case, V = 1. If you need vector in different plane, just switch the axes.

Note: The code is in Java, but whatever language you use, it should be very similar.

---
Tags: xna, shaders, hlsl, lighting
---


title: Resizing a parallax background (bug)

text:
# Question
Title: Resizing a parallax background (bug)
I'm attempting my first 2D vertical scroller and can't seem to get the background size to work. For some reason, it stays small. I think in the beginning of the parallax scrolling class, I was told to initialize variables and I know which ones I have to change.

```
public Texture2D picture;
public Vector2 position = Vector2.Zero;
public Vector2 offset = Vector2.Zero;
public float depth = 0.0f;
public float moveRate = 0.0f;
public Vector2 pictureSize = Vector2.Zero;
public Color color = Color.White;

```

I think I must change `pictureSize` to make it bigger, as the current sizing I get this:

Finally, how can I remove the whitespace from the ship image?

---

*EDIT*: Here is the code for the rendering of the actual ship:

```
public void Render(SpriteBatch batch)
{
    batch.Begin();
    batch.Draw(shipSprite, position, null, Color.White, 0.0f, spriteOrigin, 1.0f,
    SpriteEffects.None, 0.0f);
    batch.End();
}

```

The whitespace seems to be provided by XNA as I've tried clearing it using Photoshop. Because I can't directly upload to the site, I have put it here

This renders the background:

```
public void Draw()
{
layerList.Sort(CompareDepth);
batch.Begin();
for (int i = 0; i < layerList.Count; i++)
{
   if (!moveLeftRight)
   {
       if (layerList[i].position.Y < windowSize.Y)
       {
           batch.Draw(layerList[i].picture, new Vector2(0.0f,
           layerList[i].position.Y), layerList[i].color);
       }
       if (layerList[i].position.Y > 0.0f)
           batch.Draw(layerList[i].picture, new Vector2(0.0f,
           layerList[i].position.Y - layerList[i].pictureSize.Y),
           layerList[i].color);
       else
           batch.Draw(layerList[i].picture, new Vector2(0.0f,
           layerList[i].position.Y + layerList[i].pictureSize.Y),
           layerList[i].color);
   }
   else
   {
       if (layerList[i].position.X < windowSize.X)
       {
           batch.Draw(layerList[i].picture, new Vector2(layerList[i].position.X,
           0.0f), layerList[i].color);
       }
       if (layerList[i].position.X > 0.0f)
           batch.Draw(layerList[i].picture, new Vector2(layerList[i].position.X -
           layerList[i].pictureSize.X, 0.0f), layerList[i].color);
       else
           batch.Draw(layerList[i].picture, new Vector2(layerList[i].position.X +
       layerList[i].pictureSize.X, 0.0f), layerList[i].color);
       }
   }
   batch.End();
}

```

(It's from a XNA tutorial book I'm reading.)

# Answer
> 0 votes
Microsoft provided a very easy to use class for parallaxing backgrounds that should take care of your problem. I changed it to scroll up to down for you (it originally scrolled right to left):

```
class ParallaxingBackground
    {
        // The image representing the parallaxing background
        Texture2D texture;

        // An array of positions of the parallaxing background
        Vector2[] positions;

        // The speed which the background is moving
        int speed;

        public void Initialize(ContentManager content, String texturePath, int screenHeight, int speed)
        {
            // Load the background texture we will be using
            texture = content.Load<Texture2D>(texturePath);

            // Set the speed of the background
            this.speed = speed;

            // If we divide the screen with the texture width then we can determine the number of tiles need.
            // We add 1 to it so that we won't have a gap in the tiling
            positions = new Vector2[screenHeight / texture.Height + 1];

            // Set the initial positions of the parallaxing background
            for (int i = 0; i < positions.Length; i++)
            {
                // We need the tiles to be side by side to create a tiling effect
                positions[i] = new Vector2(0, i * texture.Height);
            }
        }

        public void Update()
        {
            // Update the positions of the background
            for (int i = 0; i < positions.Length; i++)
            {
                // Update the position of the screen by adding the speed
                positions[i].Y += speed;
                // If the speed has the background moving to the left
                if (speed <= 0)
                {
                    // Check the texture is out of view then put that texture at the end of the screen
                    if (positions[i].Y <= -texture.Height)
                    {
                        positions[i].Y = texture.Height * (positions.Length - 1);
                    }
                }

                // If the speed has the background moving to the right
                else
                {
                    // Check if the texture is out of view then position it to the start of the screen
                    if (positions[i].Y >= texture.Height * (positions.Length - 1))
                    {
                        positions[i].Y = -texture.Height;
                    }
                }
            }
        }

        public void Draw(SpriteBatch spriteBatch, Rectangle viewportRectangle)
        {
            for (int i = 0; i < positions.Length; i++)
            {
                spriteBatch.Draw(texture, viewportRectangle, null, Color.White, 0.0f, positions[i], SpriteEffects.None, 0.0f);
            }
        }
    }

```

You can find the original here:

http://xbox.create.msdn.com/en-US/education/tutorial/2dgame/drawing\_the\_background

I highly recommend going through the entirety of that tutorial if you're just getting started with XNA.

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


# Question
Title: How to avoid the GameManager god object?
I just read an answer to a question about structuring game code. It made me wonder about the ubiquitous `GameManager` class, and how it often becomes an issue in a production environment. Let me describe this.

First, there's prototyping. Nobody cares about writing great code, we just try to get something running to see if the gameplay adds up.

Then there's a greenlight, and in an effort to clean things up, somebody writes a `GameManager`. Probably to hold a bunch of `GameStates`, maybe to store a few `GameObjects`, nothing big, really. A cute, little, manager.

In the peaceful realm of pre-production, the game is shaping up nicely. Coders have proper nights of sleep and plenty of ideas to architecture the thing with Great Design Patterns.

Then production starts and soon, of course, there is crunch time. Balanced diet is long gone, the bug tracker is cracking with issues, people are stressed and the game has to be released yesterday.

At that point, usually, the `GameManager` is a *real big* mess (to stay polite).

The reason for that is simple. After all, when writing a game, well... all the source code is actually here to *manage* the *game*. It's easy to just add this little extra feature or bugfix in the `GameManager`, where everything else is already stored anyway. When time becomes an issue, no way to write a separate class, or to split this giant manager into sub-managers.

Of course this is a classical anti-pattern: the god object. It's a bad thing, a pain to merge, a pain to maintain, a pain to understand, a pain to transform.

What would you suggest to prevent this from happening?

**EDIT**

I know it's tempting to blame the naming. Of course creating a `GameManager` class ain't such a great idea. But the same thing can happen to a clean `GameApplication` or `GameStateMachine` or `GameSystem` that ends up being the duct-tape-favorite by the end of a project. No matter the naming, you have that class somewhere in your game code, it's just an embryo for now: you just don't know yet what monster it will become. So I'm not expecting "blame the naming" answers. I want a way to prevent this from happening, a coding architure and/or a process a team can follow knowing that this will happen at some point in production. It's just too bad to throw away say, one month of bugfixes and last-minute features, just because all of them are now in one huge unmaintainable manager.

# Answer
> Then there's a greenlight, and in an effort to clean things up, somebody writes a GameManager. Probably to hold a bunch of GameStates, maybe to store a few GameObjects, nothing big, really. A cute, little, manager.

You know, as I was reading this, I had little alarms going off in my head. An object with the name "GameManager" is never going to be cute, or little. And someone did this to clean up the code? What did it look like before? OK, jokes aside: a class's name should be a clear indication of what the class does, and this should be one thing (aka: single responsibility principle).

Also, you may still end up with an object like GameManager, but clearly, it exists at a very high level, and it should concern itself with high level tasks. Maintaining a catalogue of game objects? Perhaps. Facilitating communication between game objects? Sure. Calculating collisions between objects? No! This is also why the name *Manager* is frowned upon - it's too broad, and allows for much abuse under that banner.

A quick rule of thumb on class sizes: if you are running into several hundred lines of code per class, something is starting to go wrong. Without being overzealous, anything over, say, 300 LOC is a code smell to me, and if you are going over 1000, warning bells should be going off. By believing that somehow that 1000 lines of code is simpler to understand than 4 well structured classes of 250 each, you are deluding yourself.

> When time becomes an issue, no way to write a separate class, or to split this giant manager into sub-managers.

I think this is the case only because the problem is allowed to propagate to the point where everything is a complete mess. The practice of refactoring is really what you are looking for - **you need to continuously improve the design of the code in tiny increments**.

> What would you suggest to prevent this from happening?

The problem isn't a technological one, so you shouldn't look for technological fixes for it. The problem is this: there is a tendency in your team to create monolithic pieces of code, and the belief that it's somehow beneficial in the medium / long term to work like this. It also seems that the team is lacking a strong architectural lead, who would steer the architecture of the game (or at least, this person is too busy to perform this task). Basically, the only way out is to have team members recognise that this thinking is wrong. It does nobody favours. The quality of the product will worsen, and the team will only spend even more nights fixing things.

The good news is that the immediate, tangible benefits of writing clean code are so great, that almost all developers realise their benefits very quickly. Convince the team to work this way for a while, the results will do the rest.

The difficult part is that developing a feel for what constitutes bad code (and a talent for quickly coming up with a better design) is one of the more difficult skills to learn in development. My suggestion hinges around the hope that you have someone senior enough in the team who can do this - it is much easier to convince people that way.

Edit - A bit more info:

In general, I don't think your problem is limited to game development. At its core, it's a software engineering problem, hence my comments in that direction. What may be different is the nature of the game development industry, whether its more results and deadline oriented than other types of development, I am not sure.

Specifically for game development though, the accepted answer to this question on StackOverflow regarding "especially game architecture" tips, says:

> Follow the Solid principles of object oriented design....

This is essentially exactly what I am saying. When I'm under pressure, I also find myself writing large pieces of code, but I've drilled it into my head that that is technical debt. What tends to work well for me, is to spend the first half (or three-quarters) of the day producing a large amount of medium-quality code, and then to take a sit back, and think about it for a while; do a bit of design in my head, or on paper / whiteboard, about how to improve the code a bit. Often, I notice repetitive code, and am able to actually reduce the total lines of code by breaking things up, all the while improving readability. This time invested pays for itself so quickly, that calling it an "investment" sounds silly - quite often I'll pick up bugs that might have wasted half my day (a week later), had I allowed it to go on. What I am saying is very simply:

* Fix things on the same day you code them.
* You will be glad you did within hours.

Coming to actually believe the above is difficult; I've managed to do it for my own work only because I've experienced, over and over again, the effects. Even so, it's still difficult for me to justify fixing up code when I could be churning out more... So I definitely understand where you're coming from. Unfortunately, this advice is perhaps too generic, and not easy to do. I strongly believe in it, however! :)

To answer your specific example:

Uncle Bob's Clean Code does an amazing job of summarising what good quality code is like. I happen to agree with almost all of its contents. So, when I think of your example of a 30 000 LOC manager class, I can't really agree with the "good reason" part. I don't want to sound offensive, but thinking that way will lead to the problem. There is no good reason for having that much code in a single file - it's almost 1000 pages of text! Any benefit of locality (execution speed, or design "simplicity") will immediately be nullified by the developers being completely bogged down trying to navigate that monstrosity, and that's even before we discuss merging, etc.

If you aren't convinced, my best suggestion would be to grab a copy of the above book, and have a look through it. Applying that type of thinking to leads to people voluntarily creating clean, self-explanatory code, which is nicely structured.
> 27 votes

# Answer
This is not really an issue with game programming, but with programming in general.

> all the source code is actually here to manage the game.

This is why you should frown at any Object Oriented coder that'll suggest classes with "Manager" in the name. To be fair, I think it's virtually impossible to avoid "semigod" objects in game, but we just call them "system".

Any software tends to get dirty when the deadline is near. That's part of the job. And there is nothing inherently wrong with "duct type programming", particularly when you must ship your product in a few hours. You can't get rid of this problem totally, you can just reduce it.

Though obviously, if you're tempted to put things in the GameManager, it means that you don't have a very healthy code base. There could be two problem :

* Your code is too complex. Too many patterns, premature optimisation, nobody understands the flow anymore. Try to use more TDD when developing if you can, for it's a very good solution to fight complexity.
* Your code is not well structured. You're (ab)using globals variable, the classes are not loosely coupled, there is no interface whatsoever, no event system, and so on.

If the code seems fine, you'll juste have to remember, for each project, "what went wrong" and avoid it next time.

Finally, it could also be a team management issue : was there enough time ? Did everybody know about the architecture you were going for ? Who the hell allowed a commit with a class with the word "Manager" in it ?
> 7 votes

# Answer
So, bringing one possible solution over from the more Enterprise-y world: have you checked out inversion of control/dependency injection?

Basically, you get this framework that is a container for everything else in your game. It, and only it, knows how to wire everything together and what the relationships are between your objects. None of your objects instantiate anything inside their own constructors. Rather than creating what they need, they *ask* for what they need from the IoC framework; upon creation, the IoC framework "knows" what object is needed to satisfy the dependency and fills it. Loose coupling FTW.

When your EnemyTreasure class asks the container for a GameLevel object, the framework knows what instance to give it. How does it know? Maybe it instantiated it earlier, maybe it asks some nearby GameLevelFactory. Point is, the EnemyTreasure doesn't know where the GameLevel instance came from. It only knows that its dependency is now satisfied and it can get on with its life.

Oh, I see your PlayerSprite class implements IUpdateable. Well that's great, because the framework automatically subscribes every IUpdateable object to the Timer, which is where the main game loop is. Every Timer::tick() automatically calls all the IUpdatedable::update() methods. Easy, right?

Realistically, you don't need this bighugeohmygod framework to do this for you: you can do the important bits of it yourself. The point is that if you find yourself making -Manager type objects then, chances are, you are not distributing your responsibilities among your classes correctly or are missing some classes somewhere.
> 5 votes

# Answer
**In the past, I generally end up with a god class if I do the following:**

* sit down at the game editor/IDE/notepad before I've written out a class diagram (or just a sketch of the main objects)
* Start with an very vague idea of the game and immediately code it, then start iterating on new ideas as they come
* create a class file called GameManager when I'm not making a statebased game like a turn based strategy where GameManager is actually a domain object
* don't care about code organization early on

This may be controversial, which I'll laugh if it is, but I can't think of a single time even in prototyping that you shouldn't write a very basic class diagram before writing a playable prototype. I do tend to test tech ideas before planning, but that's about it. So if I wanted to make portal, I would write very basic code to get the portals working, then say ok great time for some minor planning then I can work on the playable prototype.
> 2 votes

# Answer
I know this question is old now, but I thought I'd add my 2 cents.

When designing games, I nearly always have a Game object. However, it is very high level and doesn't really "do anything" itself.

For example, it tells the Graphics class to Render, but has nothing to do with the rendering process. It might ask the LevelManager to load a new level, but has nothing to do with the loading process.

In short, I use a semi-godlike object to orchestrate the use of the other classes.
> 1 votes

---
Tags: architecture, software-engineering, design-patterns
---


# Question
Title: How can I create an efficient bloom shader with GLSL?
I have searched the net for resources related to rendering a bloom effect using GLSL, but haven't found anything. Although the tutorial at Philip Rideout's website is a good one, it performs very poorly on my Nvidia GPU.

Can anyone guide me as to how should I approach this problem and build a fairly efficient implementation of a bloom effect?

# Answer
> 3 votes
As Trevor mentioned in his comment, your only option might be to reduce the size of your kernel or to perform further downsampling .

But did you thoroughly read the tutorial you've linked to? There's a tip about exploiting hardware filtering, that the author calls the "sneaky" version. It's probably the best trick you can use to optimize you bloom effect without affecting its quality.

# Answer
> 0 votes
I solved a very similar problem (blurring, but the bloom filter is bluring) with two passes.

In the first pass i blur in the X direction and in the second pass i blur in the Y direction.

I dunno from where i do have this trick but it lowers the time complexity from n² to 2n.

This works only for kernels which don't have any direction (so you can'T optimize a bokeh kernel this way).

---
Tags: shaders, glsl, bloom
---


title: Serialization of objects problem

text:
# Question
Title: Serialization of objects problem
i have a problem with serialization (saving and loading game variabiles), when i save evreything seems to be saving correctly but when i try to load it only detects first 3 objects i saved and the rest are null. Am i using serialization wrong or am i saving it wrong.

Saving objects with this:

```
FileOutputStream f_out = new
                FileOutputStream("c:\\save.data");

            // Write object with ObjectOutputStream
            ObjectOutputStream obj_out = new
                ObjectOutputStream (f_out);

            // Write object out to disk

                obj_out.writeObject ( player.currentPerson );
                obj_out.writeObject ( player.gold );
                obj_out.writeObject ( Global.currentJob );
                obj_out.writeObject ( Global.currentWifeJob );
                obj_out.writeObject ( Global.currentWife );
                obj_out.writeObject ( Global.currentFood );
                obj_out.writeObject ( Global.currentCity );
                obj_out.writeObject ( Global.childList );
                obj_out.writeObject ( Global.generationList );
                obj_out.writeObject ( Global.currentPortrait );
                obj_out.writeObject ( Global.maxGeneration );
                obj_out.writeObject ( Global.currentGeneration );
                obj_out.writeObject ( Global.bloodlineRanking );
                obj_out.writeObject ( year );

```

Loading objects:

```
  // Read from disk using FileInputStream
                    FileInputStream f_in = new
                        FileInputStream("c:\\save.data");

                    // Read object using ObjectInputStream
                    ObjectInputStream obj_in =
                        new ObjectInputStream (f_in);

                    Object obj = (Object) obj_in.readObject();

                        do{
                            if(obj == null){
                                System.out.println("Skipped" + i);
                                i++;
                                continue;
                            }
                            else{
                                    if(i==0)
                            player.currentPerson  =  (Person) obj;
                        else if(i==1)
                            player.gold = (int) obj;
                        else if(i==2)
                            Global.currentJob = (Job) obj;
                        else if(i==3)
                            Global.currentWifeJob = (Job) obj;
                        else if(i==4)
                            Global.currentWife = (Wife) obj;
                        else if(i==5)
                            Global.currentFood = (Food) obj;
                        else if(i==6)
                            Global.currentCity = (String) obj;
                        else if(i==7)
                            Global.childList = (ArrayList<Child>) obj;
                        else if(i==8)
                            Global.generationList = (ArrayList<Generation>) obj;
                        else if(i==9)
                            Global.currentPortrait = (Portrait) obj;
                        else if(i==10)
                            Global.maxGeneration  = (Integer) obj;
                        else if(i==11)
                            Global.currentGeneration  = (Integer) obj;
                        else if(i==12)
                             Global.bloodlineRanking = (Integer) obj;
                        else if(i==13)
                            world.year = (Integer) obj;

                            }
                            System.out.println(obj.getClass());
                            System.out.println(i);

                            i++;
                            obj = obj_in.readObject();
                        }
                        while(i < 20);

```

Here is the print output

```
class javagame.Father
0
class java.lang.Integer
1
class javagame.Job
2
Skipped3
Skipped4
Skipped5
Skipped6
Skipped7
Skipped8
Skipped9
Skipped10
Skipped11
Skipped12
Skipped13

```

# Answer
There is a mismatch with the objects you write (`currentPerson` thru `year`, 14 objects) and those you read back (`currentPerson` thru `generationList`, 9 objects). And once you've completed a player, you need to reset `i` to zero. You can break the loop, when the object is null.
> 5 votes

# Answer
So my solution for this is that i created a SAVE class that stores all variabiles that i need

```
public class Save implements java.io.Serializable{

    Person person = null;
    int gold = 0;
    Job currentJob = null;
    Job currentWifeJob = null;
    Wife currentWife = null;
    Food currentFood = null;
    String currentCity = null;
    ArrayList<Child> childList = null;
    ArrayList<Generation> generationList = null;
    Portrait currentPortrait = null;
    int maxGeneration = 0;
    int currentGeneration = 0;
    int bloodlineRanking = 0;
    int year = 0;

    public void refresh(Player player,int yearr){
        person = player.currentPerson ;
        gold = player.gold ;
        currentJob = Global.currentJob ;
        currentWifeJob = Global.currentWifeJob ;
        currentWife = Global.currentWife ;
        currentFood = Global.currentFood ;
        currentCity = Global.currentCity ;
        childList = Global.childList ;
        generationList =  Global.generationList ;
        currentPortrait = Global.currentPortrait ;
        maxGeneration = Global.maxGeneration ;
        currentGeneration = Global.currentGeneration ;
        bloodlineRanking =  Global.bloodlineRanking ;
        year = yearr ;
    }

}

```

This is for saving

```
public void save(Player player,Save s){
        s.refresh(player, year);
        try {
            FileOutputStream f_out = new
                FileOutputStream("c:\\save.data");

            // Write object with ObjectOutputStream
            ObjectOutputStream obj_out = new
                ObjectOutputStream (f_out);

            obj_out.writeObject (s);
            // Write object out to disk

            obj_out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

```

This for loading

```
if(Global.loadEnable){
    try {

        // Read from disk using FileInputStream
        FileInputStream f_in = new
            FileInputStream("c:\\save.data");

        // Read object using ObjectInputStream
        ObjectInputStream obj_in =
            new ObjectInputStream (f_in);

        Object obj = (Object) obj_in.readObject();

        save = (Save) obj;

        player.currentPerson = save.person;
        player.gold = save.gold;
        Global.currentJob = save.currentJob;
        Global.currentWifeJob = save.currentWifeJob;
        Global.currentWife = save.currentWife;
        Global.currentFood = save.currentFood;
        Global.currentCity = save.currentCity;
        Global.childList = save.childList;
        Global.generationList = save.generationList;
        Global.currentPortrait = save.currentPortrait;
        Global.maxGeneration = save.maxGeneration;
        Global.currentGeneration = save.currentGeneration;
        Global.bloodlineRanking = save.bloodlineRanking;
        world.year = save.year;

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Read an object
}

```
> 6 votes

# Answer
Instead of using your own class to implement the save/restore, you should do one of the following:

* implement `Serializable` in your classes, and use `transient` to mark fields to be skipped
* implement `Externalizable` and define its `readExternal` and `writeExternal` methods
* use a library, for instance, a JSON parser (Jackson is fairly good java library for that)
> 3 votes

---
Tags: java, game-mechanics, slick
---


# Question
Title: how to implement pvp(text based rpg in php/mySQL)
I'm creating a text based rpg in php/mySQL and I've come up to a dead end in regards implementing the pvp aspect of the game. First off is this even possible in php/mysql? If so, how would I go about implementing it? I was thinking something like having an arena or room where you can go to battle. Then have a list of everyone else in the room who is looking for a fight. You can then make a request to fight someone from the list. Once the request has been accepted, then you can begin the fight. In terms of this mechanic, it seems to me something similar to what I am after is described in the following question: https://stackoverflow.com/questions/8934681/database-design-for-turn-based-game

P.S. The combat system is turn based. So first you attack, then the enemy attacks, and so on until you have a winner.

# Answer
> 1 votes
I'm not all that familiar with PHP and MySQl but this is how I would go about it.

First I would create a datatable for all players in a room and their status (just chillin or looking for a fight).

Then link the room table to another table that contains challenge requests that links the player ids for two players in the room datatable.

You could then query the challenge table every few seconds to see if anyone is trying to pick a fight with the current player and prompt the player with any spending fight requests. If a player accepts the request then you can delete all requests that are linked to the player or if they refuse the request you can just delete the request that you showed the user.

As for the actual fighting, I guess I would create a temporary table that stores player actions (a row would have something like a player id, move id, and random value for determining what the move does (status effect applied, damage done, or whatever just use the random number to figure out what happens playerside, don't store the result of a move in the table because that would just complicate things. The random value should be enough for producing the same result on both players game). As long as you keep querying the table at regular intervals and checking who made the last move it should be pretty simple.

All that being said, I'd have to agree with eBusiness in that PHP/MySQL might not be the best combo for a multiplayer game. You are more than welcome to try and use it as a learning experience if things don't work out well. Just don't beat yourself up if you can't make things work the way you want them to exactly.

# Answer
> 0 votes
It is possible. You could have a list of players in the room in the database, then JavaScript on the clients should once in a while send a request to get an updated list. Any player that hasn't sent such a request for some time should be taken off the list. I guess you'd have to keep the game state in the database as well.

All this said, a common PHP/MySQL setup is in general horrible for game programming. It is slow at runtime and it forces you to run way too many database queries.

Node.js for instance takes a bit more work in order to get a basic website running, but it is way better suited for a game server.

---
Tags: php, mysql
---


title: Pygame Particle Emitter Problems

text:
# Question
Title: Pygame Particle Emitter Problems
so I've been trying to create a basic particle system in pygame which I can later expand upon but I've run into a spot of bother creating the particle emitter. Obviously what's supposed to happen is it's supposed to create a new particle every frame (or a set of particles) but instead it just alters the particle that's created first time round. I understand why this is happening, as far as the game is concerned, every frame I add the same object to the particle list so when I call the update function it calculates the positional and velocity sums multiple times, what I'm having trouble with is fixing it. How would I go about making a new particle every time?

My existing classes for this are as follows:

```
class Particle():
    def __init__(self, pos, vel, accel, image):
        self.pos = pos
        self.vel = vel
        self.accel = accel
        self.life = 255
        self.lifecount = 1
        self.image = image

    def update(self):
        self.vel.add(self.accel)
        self.pos.add(self.vel)
        self.life -= self.lifecount

    def is_dead(self):
        if self.life <= 0:
            return True
        else:
            return False

class Emitter():
    def __init__(self, pos):
        self.pos = PVector(pos[0], pos[1])
        self.particles = []
        self.part_list = [Particle(self.pos, PVector(0,2), PVector(0,0), pygame.image.load("resources/particles/fireball.png"))]

    def update(self):
        self.particles.extend(self.part_list)
        for p in self.particles[:]:
            p.update()
            if p.is_dead():
                self.particles.remove(p)

    def draw(self, surface):
        for p in self.particles:
            x = p.pos.x
            y = p.pos.y
            temp = pygame.Surface((p.image.get_width(), p.image.get_height())).convert()
            temp.blit(surface, (-x, -y))
            temp.blit(p.image, (0, 0))
            temp.set_alpha(p.life)
            surface.blit(temp, (x, y))

```

The positions, velocities and accelerations are all part of a vector class with vector math functions.

# Answer
Just create the particles in the `update` method:

```
# Load the fireball once
fireball = pygame.image.load("resources/particles/fireball.png")

class Emitter():
    def __init__(self, pos):
        self.pos = PVector(pos[0], pos[1])
        self.particles = []
        self.part_list = [] # Create an empty list of particles

    def update(self):
        # Add a new particle
        p_pos = PVector(self.pos.x, self.pos.y)
        p = Particle(p_pos, PVector(0,2), PVector(0,0), fireball)
        self.particles.append(p)

        # Update existing particles
        for p in self.particles[:]:
            p.update()
            if p.is_dead():
                self.particles.remove(p)
    ...

```
> 1 votes

---
Tags: python, pygame, particles
---


title: Refractive blur in XNA?

text:
# Question
Title: Refractive blur in XNA?
I'm writing a 2D hack-and-slash game using XNA. I really want to implement the blur-like, refractive effect of a sword or such moving really quickly, seen in such games as Dust: An Elysian Tail and Vampire Dishwasher. Anyone know the technical name for this effect? For those who aren't sure what I'm talking about:

shows exactly the effect I'm trying to achieve.

# Answer
The XNA education catalog calls it distortion. Kind of a catch-all term, but it fits.

http://xbox.create.msdn.com/en-US/education/catalog/sample/distortion
> 3 votes

# Answer
it remember me to magnifying effect i'm used to do long time ago in vga 13h mode... using the bresenham circle algorithm to get the lines that draw a circle and applying a function to the distance from the pixel to the circle center to peek the color based in the new distance from a backbuffer where the original image was.

Now it can be accomplished with an hlsl postprocess shader easier.... you can google for radiul blur... or pinch effects and it will give you something near to what you are looking for...

Here you have a sample where you can test this kind of effects: http://www.hilva.com/tutorials/
> 0 votes

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


# Question
Title: Calculating projectile velocity from moving object
I'm working on a top down space shooter and am having trouble with calculating/understanding the physics for projectiles launched from the space ship.

The ships have a velocity vector and a turret with rotation independent from the body of the ship. Currently projectiles are launched based on the turrets rotation by making a normalized vector then multiplying each component by a speed. However, this doesn't work when the ship is moving faster than the speed scalar.

Right now if the ship is going faster than the projectile speed scalar and the turret is aimed in the same direction as the ship's velocity, the projectile goes backwards (away) from the ship. Assuming there is no drag/gravity (very deep space), how should I go about handling projectiles?

# Answer
> 5 votes
The velocity of a projectile fired from a moving vehicle should be `vehicleVelocity + projectileVelocity`.

So whatever velocity you would give your projectiles if the ship wasn't moving, should be added to the ship's velocity. This is true regardless of the direction it was fired.

So from the point of view of someone standing still, a projectile fired forward would go faster than a projectile fired behind. However, from the point of view of the ship, they both travel away from the ship at the same speed. (Further reading: Frame of Reference)

This only changes when you get get much closer to the speed of light, but I don't think you'll have that problem :)

---
Tags: vector, projectile-physics
---


title: How to handle a Tile Map Scrolling

text:
# Question
Title: How to handle a Tile Map Scrolling
i'm making a video game, and i'm having, i think, a concept problem. The game will be a platformer which will use tile maps, so to start i will create a mask matrix indicating the tiles to be loaded, and etc..., so my problem is, how to handle the scrolling? should i create a giant mask matrix indicating in each position of the whole level what is supposed to be loaded, and according to the position of the player, change the section to be drawed?? Is this a correct approach to this situation??

# Answer
Using tiles is a great idea first off (for a 2d game), as it allows you to effectively manage memory, loading, etc. and an effective part of using tiles for this reason IS to use a matrix, or map. In combination with a tileset for a given level or area, and with your base reflections (x and y plane) the matrix/map and tileset combo works a treat.

Three things need to be taken into account for this mechanism to be used effectively in a game however:

1. If allowing 4/8 way scrolling, be careful that any actors/enemies/etc in the game are unloaded or carefully frozen/unfrozen in some way at the same time as mapped tiles when they are no longer in your viewport, particularly if you have AI/Pathfinding utilities. (The failure to compensate for this is visible in most, if not all 8 bit platform games where 8 way scrolling was allowed as enemies off screen fell through floors, etc.)
2. Separate the concern's of scrolling/viewing from your concept of tiling. Tiling is a mechanism to deal with art assets prior to and after use by the game engine. I.e. This is a storage and load/unload pattern, rather than a rendering mechanism. Load the tiles you need to display and +100% in the x/y planes (for example) into memory, and create a texture centered around your character. Then scroll around the texture rather than by tile. Reload tiles after x/y has moved by more than (x) from start point. This has some extra benefits at the cost of the extra rendering to texture. I.e. you can apply transformations, blends, etc. to the texture off screen, and it prevents artefact-ing between tiles, which can occur at times.
3. Depending on your target platform and coding abilities you may not wish to use actual tilesets and load individually from a larger palette. I would recommend against this as good practice, but that's me personally. I have seen 2d engines which did lazy loading of tiles as required, but I think loading a tileset with an area or level is a better way to use this pattern.

(Scrolling is handled elsewhere on this site amongst other places.)
> 6 votes

---
Tags: 2d, tilemap, platformer, c++, scrolling
---


title: Object of arrays or array of objects?

text:
# Question
Title: Object of arrays or array of objects?
I'm making a management sim game, something along the lines of Roller Coaster Tycoon. I want to know what the best way to structure my world objects is so to maximise performance.

Let's say I have 5,000 people in my game I could:

Make an object and store them in an array like so;

```
class person() {
    this.x = 0;
    this.y = 0;
    this.thirst = 15;
    this.hunger = 15;
    // etc.. add methods:
    public findPath(int destX, int destY) {
    // and so on
    }

    people = new person[5000];

for (int = 0; i < 5000; i++) {
    people[i] = new person;
    }

```

Or should I make an object of people that contains many byte arrays representing attributes of people like so:

```
class people() {
    this.hunger = new byte[5000]
    this.thirst = new byte[5000]

    getThirst(int i) {
        return this.thirst[i]
        }

 // and so on....

```

Or am I totally off the mark?

# Answer
> 15 votes
The common terminology is "structure of arrays" (SOA) and "array of structures" (AOS) which come from C and is most often seen in terms of SIMD work.

Typically, the AOS approach is faster, if used appropriately, but SOA tends to be easier to work with (and hence optimizes for the more important quality - development time).

SOA, especially in Java, means that your data can remain tightly packed in memory. You can iterate over properties and expect the CPU cache and such to remain happy. With AOS, especially in Java, every object ends up allocated "somewhere" in memory. Iterating over objects could potentially thrash your CPU cache pretty heavily.

In the end, I would take whichever approach you find easiest to use. Your development time is far more valuable than whether your game supports 10 year old PCs or only 9 year old PCs (you're very unlikely to be doing anything htat needs the latest hardware).

# Answer
> 4 votes
There's no reason you can't have both, using the Facade pattern to translate from one interface to the other underlying representation. For example, using Sean's SOA/AOS terms:

**SOA facade**

```
class PeopleFacade {
    Person persons[5000];
    getThirst(int i) { return persons[i].thirst; }
}

```

**AOS facade**

```
class People { int thirsts[5000]; } people;
class PersonFacade {
    int i;
    getThirst() { return people.thirsts[i]; }
}

```

**This way you can freely choose between a form you are comfortable with using**, as a developer interface, vs whatever's best as an implementation for whatever reason, including efficiency/cache reasons.

Another advantage to the facade is that it leads very naturally to the Flyweight pattern, where you use an interface to represent much more persons than are actually in memory. For example, perhaps you have robotic patrons which are never thirsty; then you can put that special case into your `PersonFacade`, and users of that interface never have to know about robots:

```
class People { int nonRobotThirsts[1000]; } people;
class PersonFacade {
    int i;
    bool isRobot;
    getThirst() {
        if (isRobot)
            return 0;
        else
            return people.nonRobotThirsts[i];
    }
}

```

... or using a more OO approach, you'd have a separate `Robot` class which acts exactly like a `Person` except for `getThirst()`.

# Answer
> -1 votes
**Make objects and store them in an array!** Making arrays for *hunger* and *thirst* may save a bit of space and run faster in some simple situations, but it's not OOP. Java and OOP will do a great deal for you if you give them a chance. For a really simple game, your second example might work fine, but even then you *should* be practicing your OO skills. Your first approach will work well for you no matter how large, complex, and hairy your program gets.

Think of all the times it will be handy to get a `Person` object back from a query. *Who* sent this message? for instance. A lot of methods you write will want to know *who* they're dealing with. And you'll have a lot of methods that will fit nicely into a proper `Person` class. If `Person` is static or a singleton, where do you put methods that act on individual people?

Should you ever do multithreading--and with 5000 users you might be pushed into it--you will find the Parent instance for each user a *lot* more practical.

(And that array of people: stick with it for now, but at some point you'll want other storage devices. A Map of some sort so you can find people by name. And maybe several lists with different keys, and probably bunches of lists each short enough to be arrays or linked lists.)

---
Tags: java, architecture, data-structure
---