# Question
Title: How to use caching to increase render performance?
First of all I am going to cover the basic design of my 2d tile-based engine written with SDL in C++, then I will point out what I am up to and where I need some hints.

---

# Concept of my engine

My engine uses the concept of `GameScreen`s which are stored on a stack in the main game class. The main methods of a screen are usually `LoadContent`, `Render`, `Update` and `InitMultithreading`. (I use the last one because I am using v8 as a JavaScript bridge to the engine.

The main game loop then renders the top screen on the stack (if there is one; otherwise, it exits the game) - actually it calls the render methods, but stores all items to be rendered in a list. After gathering all this information the methods like `SDL_BlitSurface` are called by my `GameUIRenderer` which draws the enqueued content and then draws some overlay. The code looks like this:

```
while(Game is running) {
    Handle input
    if(Screens on stack == 0) exit

    Update timer etc.
    Clear the screen

    Peek the screen on the stack and collect information on what to render

    Actually render the enqueue screen stuff and some overlay etc.

    Flip the screen
}

```

The `GameUIRenderer` uses as hinted a `std::vector<std::shared_ptr<ImageToRender>>` to hold all necessary information described by this class:

```
class ImageToRender {
private:
    SDL_Surface* image;
    int x, y, w, h, xOffset, yOffset;
};

```

This bunch of attributes is usually needed if I have a texture atlas with all tiles in one `SDL_Surface` and then the engine should crop one specific area and draw this to the screen.

The `GameUIRenderer::Render()` method then just iterates over all elements and renders them something like this:

```
std::for_each(
    this->m_vImageVector.begin(),
    this->m_vImageVector.end(),
    [this](std::shared_ptr<ImageToRender> pCurrentImage) {
        SDL_Rect rc = { pCurrentImage->x, pCurrentImage->y, 0, 0 };
        // For the sake of simplicity ignore offsets...
        SDL_Rect srcRect = { 0, 0, pCurrentImage->w, pCurrentImage->h };
        SDL_BlitSurface(pCurrentImage->pImage, &srcRect, g_pFramework->GetScreen(), &rc);
    }
);
this->m_vImageVector.clear();

```

---

# Current ideas which need to be reviewed

The specified approach works really good and IMHO it is really has a good structure, however the performance could be definitely increased. **I would like to know what do you suggest, how to implement efficient caching of surfaces etc so that there is no need to redraw the same scene over and over again?**

The map itself would be almost static, only when the player moves, we would need to move the map. Furthermore animated entities would either require updates of the whole map or updates of only the specific areas the entities are currently moving in. My first approaches were to include a flag `IsTainted` which should be used by the `GameUIRenderer` to decide whether to redraw everything or use cached version (or to not render anything so that we do not have to `Clear` the screen and let the last frame persist). However this seems to be quite messy if I have to manually handle in my `Render` method of the screen class if something has changed or not.

---

### Edit: Possible optimizations I was reminded of

I have been rendering every frame all tiles of the map one by one which became... yeah quite some heavy work to do for both CPU and GPU. Currently I am working on drawing all layers into one surface for each layer which holds all static tiles. In my current test it is much easier to draw n surfaces (where n is the number of layers) rather than about n\*3600 small 16x16 tiles.

Though I am not thinking right now of culling this could be worth some thoughts. However I have to find out how to efficiently render entities, like items to interact with (signs, doors, ...) and NPCs which actually can walk on their own - but that is another problem and not really linked to this one.

# Answer
> 2 votes
Profile, profile, profile. Use AMD CodeAnalyst to inspect CPU bottlenecks and gDEBugger to inspect GPU bottlenecks.

However, there are some general tips I can give you.

* Don't loop over iterators.

Instead, opt for direct access. Here's how I would rewrite your code:

```
for (size_t i = 0; i < this->m_vImageVector.size(); i++)
{
    std::shared_ptr<ImageToRender> pCurrentImage = this->m_vImageVector[i];

    SDL_Rect rc = { pCurrentImage->x, pCurrentImage->y, 0, 0 };
    // For the sake of simplicity ignore offsets...
    SDL_Rect srcRect = { 0, 0, pCurrentImage->w, pCurrentImage->h };
    SDL_BlitSurface(pCurrentImage->pImage, &srcRect, g_pFramework->GetScreen(), &rc);
}
this->m_vImageVector.clear();

```

This has to with Microsoft's silly implementation of iterator dereferencing. Every time you dereference an iterator, a check is made to see if it's still in bounds.

* Dive into the source for `SDL_BlitSurface`.

Check what it's actually doing. Is it copying while constantly checking the boundaries of both the source and destination rectangle? Try implementing an "unsafe" version which doesn't have such checks.

* Group by type

Instead of having an unordered list of images to render, order the list by image id. This way, you can render multiple sprites at once. Let's say you want three instances of a Tree sprite. Instead of rendering the whole image, we render it per pixel. In code:

```
// let's assume we can read and write directly to and from a pixel surface
unsigned int* dst_pixels = g_pFramework->GetScreen()->pixels;
unsigned int* src_pixels = pCurrentImage->pImage->pixels;

// pitch is the amount of bytes to skip to go to the next line
// if the width is 640 and the image is 4 bytes per pixel, then the pitch is 2560
unsigned int dst_pitch = g_pFramework->GetScreenWidth();
unsigned int src_pitch = pCurrentImage->w;

std::vector<SDL_Rect> src_rect;

// this offset is a pointer directly to the pixel we want to start drawing at
std::vector<unsigned int*> src_rect_offset;
for (size_t i = 0; i < src_rect.size(); i++)
{
    src_rect_offset.push_back(dst_pixels + (src_rect.y * dst_pitch) + src_rect.x);
}

// write multiple images at once
for (unsigned int y = 0; y < pCurrentImage->h; y++)
{
    for (size_t i = 0; i < src_rect.size(); i++)
    {
        unsigned int* dst_pixels_write = src_rect_offset[i];

        for (unsigned int x = 0; x < pCurrentImage->w; x++)
        {
            dst_pixels_write[x] = src_pixels[x];
        }

        src_rect_offset[i] += dst_pitch;
    }

    src_pixels += src_pitch;
}

```

However, great care must be taken that you don't write outside of your screen! For example, if a sprite is clamped by the bottom border, this algorithm will write outside the destination surface's memory and cause a heap corruption.

---
Tags: c++, rendering, tiles, performance, sdl
---


# Question
Title: How to offset particles from point of origin
Hi I'm having troubles off setting particles from a point of origin. I want my particles to spread out after a certain radius from a the point of origin. For example, this is what I have right now:

All particles emitted from a point of origin. What I want is this:

Particles are offset from the point of origin by some amount, i.e after the circle. What is the best way to achieve this? At the moment, I have the point of origin, the position of each particle and its rotation angle. Sorry for the poor illustrations.

---

Edit: I was mistaken, when a particle is created, I have only the point of origin. When the particle is created I am able to calculate the rotation of the particle in the update method after it has moved to a new location using atan2() method.

This is how I create/manage particles: Created new particle at enemy ship death location, for every new particle which is added to the list, call Update and Draw to update its position, calculate new angle and draw it.

# Answer
First convert the angle to a normalized direction vector. You could try using the following method (taken from here). I think the order of the `Sin` and `Cos` and the signs might depend on how your `angle` is defined (e.g. what direction 0 represents), so play around with them if the result seems wrong:

```
Vector2 AngleToVector(float angle)
{
    return new Vector2((float)Math.Sin(angle), -(float)Math.Cos(angle));
}

```

Then multiply it by the radius of the circle and add it to the point of origin to get the starting position of the particle. In other words:

```
Vector2 origin; // center of the circle
float radius; // radius of the circle
float angle; // random value from 0 to 2PI
Vector2 startPosition = origin + AngleToVector(angle) * radius;

```
> 2 votes

# Answer
Alternatively, you could leave your code unchanged from your 1st example where they all start from a common origin (enemy ship location).

Then add a toggle that simply sets (renders) them transparent until they are a set distance from that origin.
> 0 votes

---
Tags: xna, c#, mathematics, particles
---


# Question
Title: SDL - Getting a single keypress event instead of a keystate?
Right now I'm working on a simple SDL project, but I've hit an issue when trying to get a single keypress event to skip past a splash screen. Right now, there are 4 start-up splash screens that I would like to be able to skip with a **single keypress** (of any key). My issue is that, as of now, if I **hold down** a key, it skips through each splash screen to the very last one immediately.

The splash screens are stored as an array of SDL surfaces which are all loaded at the initialization of the state. I have an variable called currentSplashImage that controls which element of the array is being rendered on the screen. I've set it up so that whenever there's a SDL\_KEYDOWN event, it triggers a single incrementation of the currentSplashImage variable.

So, I'm really not sure why my code isn't working correctly. For some reason, when I hold down a button, it seems to be treating the held button as a new key press event every time it ticks through the code. Does anyone know how I can go about fixing this issue?

\[Here's a snippet of code that I've been using...\]

```
void SplashScreenState::handleEvents()
{
    SDL_PollEvent( &localEvent );

    if ( localEvent.type == SDL_KEYDOWN )
    {
        if ( currentSplashImage < 3 && currentSplashImage >= 0)
        { currentSplashImage++; }
    }
    else if ( localEvent.type == SDL_QUIT )
    {
        smgaEngine.setRunning(false);
    }
}

```

I should also mention that the SDL\_Event 'localEvent' is part of the GameState parent class, while this event handling code is part of a SplashScreenState subclass.

If anyone knows why this is happening, or if there is any way to improve my code, It'd be helpful to me! :D I'm still a very new programmer, trying to learn.

UPDATE:

I added a std::cout line to that the code runs multiple times with a single KEYDOWN event. I also tried disabling SDL\_EnableKeyRepeat, but it didn't fix the issue.

```
void SplashScreenState::handleEvents()
{
    SDL_PollEvent( &localEvent );

    if ( localEvent.type == SDL_KEYDOWN )
    {
        if ( currentSplashImage < 3 && currentSplashImage >= 0)
        {
            currentSplashImage++;
            std::cout << "KEYDOWN.."; //<---- test cout line
        }
    }
    else if ( localEvent.type == SDL_QUIT )
    {
        smgaEngine.setRunning(false);
    }
}

```

This prints out "KEYDOWN..KEYDOWN..KEYDOWN.." in the cout stream when a button is held.

# Answer
> 6 votes
`SDL_PollEvent` will not change the content of the event you pass through if there is no new event to report. This means that `type == SDL_KEYDOWN` will stay true until some other event arrives.

You need to check the value returned from `SDL_PollEvent` and only continue on to your event handling code when there is a new event to handle.

eg.

```
if (SDL_PollEvent( &localEvent ) == 1)
{
    if ( localEvent.type == SDL_KEYDOWN )
    {
        if ( currentSplashImage < 3 && currentSplashImage >= 0)
        {
            currentSplashImage++;
        }
    }
    else if ( localEvent.type == SDL_QUIT )
    {
        smgaEngine.setRunning(false);
    }
}

```

You may also consider using `SDL_WaitEvent` instead, which pauses the app until another event is available.

# Answer
> 4 votes
Does simply checking for an `SDL_KEYUP` not work? You can't have an `SDL_KEYUP` before an `SDL_KEYDOWN`.

If `SDL_EnableKeyRepeat(0, 0);` is not working for you, then you should assume it is not reliable and not use it. Build your own key-repeat handling logic like lionesmiz hinted at.

If I were you I'd build an abstraction layer on top of this. Polling for SDL events is an app-wide thing, and you should be asking an input module (something like `Input::WasKeyReleasedThisFrame(SDLKey somekey);`) about the state of the keyboard. Keep a `std::map` that maps `SDLKey` values to some sort of `KeyState` value so you poll once every frame, then all the rest of your code just goes to this input module for this information.

But however you do it, just provide some sort of sensible API for your state classes to use. Why keep it wrapped up inside this `SDL_Event` nonsense? You want INPUT dammit!

# Answer
> 2 votes
Something like this should work:

```
void SplashScreenState::handleEvents()
{
    SDL_PollEvent( &localEvent );

    if ( localEvent.type == SDL_KEYDOWN )
    {
        if(!keyIsAlreadyPressed)//member variable--should be initialized to false
        {
            if ( currentSplashImage < 3 && currentSplashImage >= 0)
            { currentSplashImage++; }
        }
        keyIsAlreadyPressed=true;
    }
    else if ( localEvent.type == SDL_KEYUP )
    {
       keyIsAlreadyPressed=false;
    }
    else if ( localEvent.type == SDL_QUIT )
    {
        smgaEngine.setRunning(false);
    }
}

```

# Answer
> 1 votes
You are witnessing the "Key Repeat" feature. It's common to repeat the key press if it is hold for a longer amount of time. You can disable it with SDL\_EnableKeyRepeat.

---
Tags: c++, architecture, sdl, events, keyboard
---


# Question
Title: Action-oriented AI: evasion-algorithm takes much time
Evasion, the process of evading, is the opposite of chasing. Instead of trying to decrease the distance to the target we try to maximize it.

It takes much time while evading multiple objects simultaneously. I use BFS here. To make it faster what algorithms should I use?

# Answer
I suggest you use Steering Behaviors to simulate these types of behaviour. See this page for an example of evasive behaviour implemented in this way.

The basic idea is you only consider simple properties like the position and velocity vectors of your prey and predators to compute the desired change in these properties in linear time. This results in responsive yet realistic behaviour.

However, this comes at the cost of not taking other factors in consideration, like more high-level goals (the position of power-ups for example) or the position of static obstacles, as you would in pathfinding. These can be taken into account by combining the Steering Behaviors approach with, for example, potential fields (see Using Potential Fields in a Real-time Strategy Game Scenario (Tutorial)) or pathfinding (e.g. Corridor Map Method). In the case of the latter you want to decrease the update frequency (and trust the Steering Behaviors to compensate for any errors that might occur because of this) or do partial replanning, possibly combined with a more hierarchical approach (e.g. Near-Optimal Hierarchical Pathfinding (HPA\*).

*If you want a more specific answer, improve your question with more details about your problem. For example, consider describing what your game is about and the number of NPCs we're talking about.*
> 12 votes

---
Tags: algorithm, ai, game-mechanics
---


# Question
Title: How do you create a cbuffer or global variable that is gpu modifiable?
I'm implementing tonemapping in a pixel shader, for hdr lighting.

The vertex shader outputs vertices with colors. I need to find the max color and save it in a global.

However when I try and write the global in my hlsl code,

```
//clamp the max color below by this color
clamp( maxColor, output.color, float4( 1e6,1e6,1e6,1e6 ) ) ;

```

I see:

> error X3025: global variables are implicitly constant, enable compatibility mode to allow modification

What is the correct way to declare a shader global in d3d11 that the vertex shader can write to, and the pixel shader can read?

I realize this is a bit tough since the vertex shaders are supposed to run in parallel, and introducing a shader global that they all write to means a lock..

# Answer
This is not possible with 11.0.
> 2 votes

---
Tags: shaders, directx11, hlsl
---


title: 2D game world creation (libGdx, java)

text:
# Question
Title: 2D game world creation (libGdx, java)
I'am starting to develop a 2D game with motorbikes.

My Question now is: When my bike reaches the right edge the world should move. (Like in that game: Game example) My first thought was to implement a camera and to create a huge image for the world. (e.g 4096 x 512). So I only have to move the camera to solve the problem.

Is that a good solution?!

Thank your.

Regards, Matthias

# Answer
What you can do (And what i think many others do) is to split that 4096 into X number of widths (Lets say thats 8 segments of 512.) Then when one of your current background is almost at the end, you can get the next segment ready and position it right next to the previous one.

To add a little more to that, you can also prepare more than just the next segment. So for example, you can keep 3 loaded at one time to keep any edges from showing. So you would have the previous segment, the current one and the next segment loaded.

This is a fairly good way to help reduce the large size of that background. Hope this isn't too confusing. I can whip up some images or code snippets to help if you need.
> 4 votes

---
Tags: java, libgdx
---


# Question
Title: Hide individual regions on a territory map
I have a map of adjacent irregularly-shaped territories. It happens to be a county map, but that's not important. In the game, the player only sees a few to start, and as he progresses to new territories, the ones adjacent to it are revealed. It's a territory-scale fog-of-war.

I'm using Unity3D, and my inclination is to make a set of planes, each of which has an image of a single territory on it, and then arrange them manually like a jigsaw puzzle. It then is fairly easy to respond to a click on each region and also to mark the planes as visible or invisible, or even do clever things like fade or zoom on individual regions.

This sounds like an arduous task, and if we need to change the visual design of the territories, we'd have to cut up the main map all over again into each of the individual pieces.

Does anyone have a more elegant solution to this problem?

# Answer
Maybe you could use a second texture, hidden from the player, with a color mask where every color corresponds to a certain region? Then you could do a lookup againts the coordinates of a user click on your main map against that colormaskmap.

Also you could have a graph storing which counties are adjacent to which and decide which ones should be visible that way. Nodes could of course also store other info as center of region which you might want to zoom to etc.

I don't know if this is how others do it though, just an idea on the top of my head.
> 3 votes

# Answer
I think your basic approach is correct — as you noted, there are several really useful things that you can do with a bitmask for your countries, and especially for things like picking there really aren't substantially better ways. But it sounds like you're looking at the construction of these masks backwards; rather than building individual masks and carefully fitting them together jigsaw-style, I would go the other way: start with a bitmap of the map as a whole, either a single black-and-white layer where the black pixels represent boundaries or a full-color image that has a specialized 'boundary color' for doing the same thing. It should be easy to tweak your pipeline to make sure you can generate an image like this; it's almost a necessary piece of building the full-scale worldmap, and should be at worst be an easy by-product of the art generation process.

I'd suggest building a small tool that can take this 'map layer' and create the bitmasks you're talking about: do a linear search through the bitmap for a non-boundary pixel, then floodfill from that point with respect to the boundary pixels, marking off each pixel that you fill in a second bitmap. Once you're done, that second bitmap will be the mask for one territory; you can clip it to its minimum size (keeping track of where it came from in your original image), fill its pixels in your original image so they aren't considered again, and then do another scan to look for non-boundary (and non-filled) pixels. Continuing like this will eventually give you all of your territories, along with their positions in the original map, and from there everything should work like you were outlining.

Note that the key to this process is really the *tool* — having a mechanical process that can work from a relatively easy-to-produce asset (in this case, the overall map) and give you the assets you really need.
> 0 votes

---
Tags: unity, maps, interface
---


# Question
Title: Best way to create neon glow line effect in AS3?
What's the best way to create a neon glow line effect in Flash AS3? Say similar to what's going on in the game gravitron360 on the xbox 360?

Would it be a good idea to create movieclips with plain lines drawn in them and then apply a glow filter to them? or perhaps just apply the glow filter to the entire movieclip layer the movieclips are on? or just draw them manually and create a glow effect by converting the lines to fills and then softening edges? (wouldn't blend as well but would be the fastest CPU wise?)

Thanks for any help

# Answer
I was looking for a solution to this too, but I found a easier, and performance-wise better one. Just draw everything in your graphics object again, but with a slightly fatter linestyle, wich is white and has an opacity of let's say 0.2.

It gives you a nice little glow effect, and you probably won't even notice the difference until you zoom in (or if the outline is too fat).

And I know your question is 9 months old, but I reckon that anyone who reads this will be thankful :3
> 3 votes

# Answer
The most flexible approach is to use the graphics object of the `Shape`, `Sprite` or `MovieClip` class and paint your lines dynamically. Then (as you suggested), apply a Glow effect to this display object.

With the graphics object, you can paint many lines in a single `Sprite` (or `MovieClip`), so it's a good idea to do that and have the filter applied to the Sprite, so that all lines will get the same filter effect. If you're drawing lines over a huge area, you should know that the glow filter is limited to certain size. From the docs:

> A filter is not applied if the resulting image exceeds the maximum dimensions. In AIR 1.5 and Flash Player 10, the maximum is 8,191 pixels in width or height, and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an image is 8,191 pixels wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, the limitation is 2,880 pixels in height and 2,880 pixels in width. For example, if you zoom in on a large movie clip with a filter applied, the filter is turned off if the resulting image exceeds the maximum dimensions.

I don't know how your background looks like, but with a dark background and bright lines, I suggest you additionally set the `blendMode` of your Sprite to `OVERLAY` or `SCREEN` (see BlendMode). With dark lines on a bright background, `MULTIPLY` could be a good blend-mode.

**Update:** In terms of performance, the fastest approach is probably a simple image of a blurred line. But that's not very flexible, as you would need an image for every possible line-length. A vector-based approach (with gradients or different fills) is going to be slower than the glow-filter. These filters are very fast and optimized and will outperform the drawing of lots of complex vector shapes.
> 1 votes

---
Tags: actionscript-3
---


# Question
Title: Lost transparency in SDL surfaces drawn manually
I want to create `SDL_Surface` objects for each layer of my 2d tile-based map so that I have to render only one surface per layer rather than too many tiles. With normal tiles which do not have transparent areas this works well, however I am not able to create a `SDL_Surface` with transparent pixels everywhere to be able to draw some tiles on specific parts which should be visible (I do **NOT** want the whole surface to appear with a specific opacity - I want to create overlaying tiles where one can look through).

Currently I am creating my layers like this to draw with `SDL_BlitSurface` on them:

```
SDL_Surface* layer =
    SDL_CreateRGBSurface(
        SDL_HWSURFACE | SDL_SRCALPHA,
        layerWidth, layerHeight, 32, 0, 0, 0, 0);

```

If you have a look at this screenshot I have provided here

you can see that the bottom layer with no transparent parts gets rendered correctly. However the overlay with the tree tile (which is transparent in the top left corner) is drawn own its own surface which is black and not transparent as expected. The expected result (concerning the transparency) can be seen here

**Can anyone explain me how to handle surfaces which are actually transparent rather than drawing all my overlay tiles separately?**

# Answer
> 1 votes
After trying a few things in desperation I was able to fix this issue! First of all I have filled the `SDL_Surface` objects with magenta

```
SDL_FillRect(layer, NULL, SDL_MapRGB(layer->format, 255, 0, 255));

```

then I noticed I have tried to handle alpha while drawing to the layer but I forgot to think about the `SDL_BlitSurface` call to the screen! Just one line above this call I had to add

```
SDL_SetColorKey(layer, SDL_SRCCOLORKEY, SDL_MapRGB(layer->format, 255, 0, 255));

```

and that did it!

---
Tags: rendering, sdl, image, transparency
---


# Question
Title: Andengine. Put bullet to pool, when it leaves screen
i'm creating a bullet with physics body. Bullet class (extends Sprite class) has `die()` method, which unregister physics connector, hide sprite and put it in pool

```
public void die() {
    Log.d("bulletDie", "See you in hell!");
    if (this.isVisible()) {
        this.setVisible(false);

        mPhysicsWorld.unregisterPhysicsConnector(physicsConnector);

        physicsConnector.setUpdatePosition(false);

        body.setActive(false);

        this.setIgnoreUpdate(true);

        bulletsPool.recyclePoolItem(this);
    }

}

```

in `onUpdate` method of PhysicsConnector i executes die method, when sprite leaves screen

```
physicsConnector = new PhysicsConnector(this,body,true,false)
    {
        @Override
        public void onUpdate(final float pSecondsElapsed) {

            super.onUpdate(pSecondsElapsed);

            if (!camera.isRectangularShapeVisible(_bullet)) {
                Log.d("bulletDie","Dead?");
                _bullet.die();
            }

        }
    };

```

it works as i expected, but `_bullet.die()` executes TWICE. what i\`m doing wrong and is it right way to hide sprites?

here is full code of Bullet class (it is inner class of class that represents player)

```
private class Bullet extends Sprite implements PhysicsConstants {
    private final Body body;

    private final PhysicsConnector physicsConnector;

    private final Bullet _bullet;

    private int id;

    public Bullet(float x, float y, ITextureRegion texture, VertexBufferObjectManager vertexBufferObjectManager) {
        super(x,y,texture,vertexBufferObjectManager);

        _bullet = this;

        id = bulletId++;

        body = PhysicsFactory.createCircleBody(mPhysicsWorld, this, BodyDef.BodyType.DynamicBody, bulletFixture);

        physicsConnector = new PhysicsConnector(this,body,true,false)
        {
            @Override
            public void onUpdate(final float pSecondsElapsed) {

                super.onUpdate(pSecondsElapsed);

                if (!camera.isRectangularShapeVisible(_bullet)) {
                    Log.d("bulletDie","Dead?");
                    Log.d("bulletDie",id+"");
                    _bullet.die();
                }

            }
        };

        mPhysicsWorld.registerPhysicsConnector(physicsConnector);

        $this.getParent().attachChild(this);
    }

    public void reset() {

        final float angle = canon.getRotation();

        final float x = (float) ((Math.cos(MathUtils.degToRad(angle))*radius) + centerX) / PIXEL_TO_METER_RATIO_DEFAULT;
        final float y = (float) ((Math.sin(MathUtils.degToRad(angle))*radius) + centerY) / PIXEL_TO_METER_RATIO_DEFAULT;

        this.setVisible(true);
        this.setIgnoreUpdate(false);

        body.setActive(true);
        mPhysicsWorld.registerPhysicsConnector(physicsConnector);
        body.setTransform(new Vector2(x,y),0);

    }

    public Body getBody() {
        return body;
    }

    public void setLinearVelocity(Vector2 velocity) {
        body.setLinearVelocity(velocity);
    }

    public void die() {
        Log.d("bulletDie", "See you in hell!");
        if (this.isVisible()) {
            this.setVisible(false);

            mPhysicsWorld.unregisterPhysicsConnector(physicsConnector);

            physicsConnector.setUpdatePosition(false);

            body.setActive(false);

            this.setIgnoreUpdate(true);

            bulletsPool.recyclePoolItem(this);
        }

    }

}

```

# Answer
additional condition to check visibility of sprite prevented second executions of die method

```
physicsConnector = new PhysicsConnector(this,body,true,false)
{
    @Override
    public void onUpdate(final float pSecondsElapsed) {

        super.onUpdate(pSecondsElapsed);

        if (!camera.isRectangularShapeVisible(_bullet) && _bullet.isVisible()) {
            Log.d("bulletDie","Dead?");
            _bullet.die();
        }

    }
};

```
> 4 votes

---
Tags: java, android, box2d, andengine
---


# Question
Title: Possible / How to render to multiple back buffers, using one as a shader resource when rendering to the other, and vice versa?
I'm making a game in Direct3D10. For several of my rendering passes, I need to change the behavior of the pass depending on what is already rendered on the back buffer. (For example, I'd like to do some custom blending- when the destination color is dark, do one thing; when it is light, do another).

It looks like I'll need to create multiple render targets and render back and forth between them. What's the best way to do this?

* Create my own render textures, use them, and then copy the final result into the back buffer.
* Create multiple back buffers, render between them, and then present the last one that was rendered to.
* Create one render texture, and one back buffer, render between them, and just ensure that the back buffer is the final target rendered to

I'm not sure which of these is possible, and if there are any performance issues that aren't obvious. Clearly my preference would be to have 2 rather than 3 default render targets, if possible.

# Answer
> 2 votes
Something like #2 is probably your best bet. Create two `ID3D10Texture2D` surfaces, and ensure that the `D3D10_TEXTURE2D_DESC.BindFlags` field includes both `D3D10_BIND_SHADER_RESOURCE` and `D3D10_BIND_RENDER_TARGET`. That will let you use each surface as a shader resource and as a render target -- not as both in the same draw call, though! Then just ping-pong between the two of them -- use surface A as in input to target B in pass 2\*N, and then use surface B as an input to target A for pass 2\*N+1.

---
Tags: directx, directx10, rendertargets
---


title: LOD in modern games

text:
# Question
Title: LOD in modern games
I'm currently working on my master's thesis about LOD and mesh simplification, and I've been reading many academic papers and articles about the subject. However, I can't find enough information about how LOD is being used in modern games. I know many games use some sort of dynamic LOD for terrain, but what about elsewhere?

Level of Detail for 3D Graphics for example points out that discrete LOD (where artists prepare several models in advance) is widely used because of the performance overhead of continuous LOD. That book was published in 2002 however, and I'm wondering if things are different now. There has been some research in performing dynamic LOD using the geometry shader (this paper for example, with its implementation in ShaderX6), would that be used in a modern game?

To summarize, my question is about the state of LOD in modern video games, what algorithms are used and why? In particular, is view dependent continuous simplification used or does the runtime overhead make using discrete models with proper blending and impostors a more attractive solution? If discrete models are used, is an algorithm used (e.g. vertex clustering) to generate them offline, do artists manually create the models, or perhaps a combination of both methods is used?

# Answer
> 9 votes
For now it seems that discrete LOD is still preferred, but it remains to be seen if this will change with the next generation of console hardware.

For what it's worth Tom Forsyth has written a lot about continuous LOD, which he calls "progressive meshing". Game Programming Gems 2 purports to have one of these articles, but it appears to be mirrored here.

I believe one of Tom's games shipped using progressive meshing on last-gen console hardware. I don't think it's the computation overhead people are worried about with continuous LOD. I think it's more that discrete LOD is easier. Continuous LOD does heavier lifting in the tools pipeline and does not have enough clear advantages.

As for generation of discrete LODs, we use a combination of automatic tools and artist creation. The DirectX SDK comes with some stuff to auto-reduce geometry and I believe we use that as a first pass, if the quality is not good enough then artists generate the discrete LODs by hand or using additional tools in Maya.

# Answer
> 7 votes
* Supreme Commander (1&2) - this RTS prides itself in the fact that you can smoothly zoom out all the way to see a map of the battlefield, and then zoom all the way in on an area and manage it. It uses LOD very well as you zoom in and out to keep from overloading the graphics card, and at a certain zoom out level the meshes are replaced by 2D images of what type of unit they are, so that the map of the battlefield can clearly show where things are (since obviously a really low-detail 3D mesh at 20,000 ft would be indistinguishable). You can see the 2D replacement effect pretty clearly in the first few seconds of this video.
* RollerCoaster Tycoon 3 \- Similar to Supreme Commander, this game allows you to zoom in and out at will, viewing your entire theme park or managing a single coaster. It does not use 2D image replacement but due to LOD everything remains smooth; not only do the big meshes reduce in quality, but small details like the people walking around disappear when you zoom out far enough.
* Legend of Zelda: Wind Waker \- As you're sailing the open sea you can look around and see the closest islands to you; they are only silhouettes of the islands, however, and the actual 3D models don't load until you approach an island. Other features of the island load as well, such as enemies and typhoons in the nearby waters; unfortunately the player can see them "pop" into existence as he gets close, but overall it's a good technique that prevents from overloading the Nintendo GameCube hardware while giving the player a pretty accurate feeling of sailing the seas and being able to distinguish landmark islands in the distance.
* Elder Scrolls IV: Oblivion \- I haven't played this game in a long time but I know it does use either silhouetting or really low-detail models for distant landmark structures, such as the tall tower of one of the cities, and distant mountains.

**LOD is not only used for terrain, but also for silhouettes of distant structures and for eagle's eye views of strategy/simulation games.** I don't know the details of the algorithms, and I guess that's the main part of your question, but I wanted to give you some examples of the state of LOD in modern video games.

# Answer
> 5 votes
Here is an alternative suggestion, just to keep it interesting. Convex decomposition can create approximate geometries quite quickly, and is usually for collision meshes. These meshes work well as LOD and it is plausible as a real time decimation for speeding up a pipeline.

http://codesuppository.blogspot.com/2009/11/convex-decomposition-library-now.html

# Answer
> 4 votes
One modern approach to continuous LOD is hardware tessellation. Hardware tessellation was implemented in DirectX 11 and essentially provides programmable subdivision of surfaces. Because this is implemented on the GPU, it allows for much higher detail than provided by CPU-generated tessellation. By subdividing surfaces based on the view distance, for example, you can provide a form of continuous LOD.

Hardware tessellation is a very new feature of GPUs and there are not a lot of games that utilize it. I suspect that the games that do use it mostly as a drop-in for bump mapping - rather than bump map in the pixel shader, you can modify the actual geometry. There is probably a lot of room for further research into mesh simplification and improvement using hardware tessellation.

Some more resources:

# Answer
> 3 votes
LOD is about trying to keep the amount of processing constant over time. Hierarchical level of detail is the only way of doing this for scenes of considerable detail. If you are near enough to an object, it decomposes into multiple objects. This recursive LOD provides not only a simple mechanism for handling the transition points for switching in new levels of detail but also allows the render call count to stay about the same no matter how far / near you get to your world objects.

It's all very well having great LODs for your meshes and textures, but in at least one game I shipped on the PS2, the way I saved time was just to clump together all the foliage in sectors into single draw calls. This larger draw call took nearly 90% less time than rendering all the low lod variants, even with carefully ordered material transitions and batch rendering each type of mesh. So, consider LOD with care. It's not just about individual objects. It's about the whole render phase.

# Answer
> 1 votes
Another subject to consider discussing in your paper (though an entire thesis could easily be written on just this subject alone) is procedural terrain generation.

Many modern projects are starting to use real-time procedural terrain generation to produce massive expanses of terrain (Outerra, Infinity (INovae), to name some of the most prominent). Discrete LOD is simply not an option, because of the procedural nature of the meshes.

These terrains often use heirarchical partitioning structures such as quadtrees to determine LOD, and generate a mesh of the appropriate resolution based upon the depth of the tree's node.

Without the use of continuos LOD, these awesome projects would simply be impossible.

---
Tags: rendering, models, graphics-programming, level-of-detail
---


title: C++ Database vs Reading Files

text:
# Question
Title: C++ Database vs Reading Files
Ive been programing a C++ game/server for the past year. I have been using MYSQL for character logins, items, monsters, etc, etc. (im on windows). My question is, what are some of the databases that some big time developers use. IE. Battle.net, Diablo II, Diablo III, mythos, hellgate , etc, etc, etc. Do they have their own database they built? Or do they use an existing framework for logins, and character transfers.

I do know that in diablo II, they use character files to to transfer characters into the game world. But what about the login into battle.net.

Would it be wiser for me to stick with MYSQL, or is there something out there faster and more stable, or should I create a login type of system that looks through a file to see if you provided the correct password.

Can't wait to get some replies. Thanks!

PS. Currently the framework is much like battle.net, where you login into a lobby, create, and join games. The game server/lobby server are different servers too. So im just wondering about the lobby server for logins because I'm expecting several hundred thousand connections/logins.

# Answer
> 3 votes
Although not an exact duplicate, you are basically asking this question: What kind of databases are usually used in an MMORPG. There are several good answers there and the overall summary is "all of them" - ie. some use off-the-shelf DBs (relational or NoSQL), some make their own, some use traditional databases but treat them just as places to store binary blobs of data, and some use a mixture of the above.

MySQL is likely to be good enough for your needs. If it has worked for the last year, it's unlikely to stop working now.

# Answer
> 2 votes
There's not much use reinventing the wheel, you're likely able to use an off the shelf database for pretty much anything you need and the time you save instead of developing your own is invaluable.

I think that perhaps sticking to one database is less than optimal, MySQL is good for things like user logins, and such interactions, but I'd personally store character profiles in something a little more dynamic, the various nosql implementations in particular, as it's not likely you'll be doing much relational work with them.

Internally, an SQLite database for weapons may make more sense, as you can pack it in a file, and not have to worry about setting up servers and so on with the client's machine.

None of this is set in stone, but I don't think looking for a one-size-fits all solution is the answer.

---
Tags: c++, server, databases
---


# Question
Title: How can you represent equip-able items in a 2d game?
I've been working on an item system for a post-apocalyptic RPG, with diablo as inspiration, and it would be awesome if I could visually represent an item that can be equipped on the player sprite. I was thinking you could have a player sprite with certain animations, then the equipped item would be drawn as if it was on the player with the same animations, so it syncs with the player animations but that couldn't work very smoothly, I imagine there's a better system.

How can you graphically represent an item worn on the player, which moves like he does, and looks as if he's wearing it? I'm not asking you how to do it in framework X or platform X (altho if you REALLY need it, I'm using Allegro 5 with codeblocks on win XP) but instead I'm asking you how to generally program such an idea.

# Answer
(I assume you're talking 2D here since you talk about sprites)

One solution would be to use 2D skeletal animations. You define animations not by successive frames in a sprite but by chopping up the character in bones and then you express how each bone should move in a certain animation. Each bone has it's own sprite that moves with the bone (note that you can still animate these sprites).

Wearable items could be implemented as a new sprite for one or several bones. Or you could attach multiple sprites to a bone. For example you have a thigh bone and a sprite for the thigh. You now want to add a holster. Create a new holster sprite and attach it somewhere at the the thigh bone. In the game you first draw the thigh-sprite based on the position of the thigh-bone and then you draw the holster, also transformed with respect to the thigh-bone over the thigh-sprite. You now have a layering/attachment system that should be easy to work with. Note that when you change your animations all you have to do is change the movements of the bones, all sprites will just stick on and work like before. This makes changing animations easy. Don't go for a solution where changing an animation would cause you to have to update dozens of sprites.

I also did some googling to see if there are some useful references out there. It seems some people have made a few skeletal animation samples for Allegro here and there even seems to be a very nice editor for skeletal animations in allegro.
> 4 votes

---
Tags: c++, animation, sprites
---


# Question
Title: C# - separate sprite for 2d character and arms
I'm making a 2D action platformer in C# (not using XNA).

So far I have the character drawn on the screen, animating and moving. The sprite sheets provided by the artist have the character and arms in two different sheets. And this is my problem.

How would I go about adding the arms to the character? I have a general idea that I would draw the 1st hand (one further away from screen) then character and then the other hand (the one closer to the screen). What I have an issue with is, how could I combine them into one object in order to make coding the movement and actions easier? Also I guess I should use anchor points to make positioning of individual parts easier, and also to make my life easier when I start adding weapons.

The actual case becomes a bit more complex as the arms sprites have to be changed depending on the type of the weapon the character is using. Also the hand on the arm closer to the screen is missing a thumb which is so that it could be animated during a reload with certain weapons.

I guess I'm looking for a way to construct a player object from the separate sheets in order to keep that full character easily drawable, since in some cases, the whole object should be switched, like a climbing animation or acrobatic move animation have arms on the character already.

Thank you in advance.

# Answer
> 3 votes
You need to build an object graph for your character. Have the basic player object contain a master sprite, such as the torso. In the master sprite, have Joints(which have an offset, translation, from the parent sprite), which then contain child objects(such as an arm, or two) with rotations. The children are the same as type the master, having joints of their own, and then child objects(such as a hand), with a rotation. Continue until you've built a graph containing all the parts of your character.

When you render it, call a render function on your master, then translate to a joint, render all its children, pop your translation and continue to the next joint. If you're not sure on how to do this, take a look at Recursion.

---
Tags: 2d, animation, character
---


title: Unity custom shaders and z-fighting

text:
# Question
Title: Unity custom shaders and z-fighting
I've just readed a chapter of **Unity iOS Essential** by Robert Wiebe.

It shows a solution for handling `z-figthing` problem occuring while rendering a street on a plane with the same y offset.

Basically it modified Normal-Diffuse shader provided by Unity, specifing the (texture?) offset in -1, -1.

Here's basically what the shader looks like:

```
Shader "Custom/ModifiedNormalDiffuse" {
    Properties {
        _Color ("Main Color", Color) = (1,1,1,1)
        _MainTex ("Base (RGB)", 2D) = "white" {}
    }
    SubShader {
        Offset -1,-1   //THIS IS THE ADDED LINE
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Lambert

        sampler2D _MainTex;
        fixed4 _Color;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            half4 c = tex2D (_MainTex, IN.uv_MainTex) *_Color;
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

Ok. That's simple and it works. The author says about it:

> ...we could use a copy of the shader that draw the road at an Offset of -1, -1 so that whenever the two textures are drawn, the road is always drawn last.

I don't know `CG` nor `GLSL`, but I've a little bit of experience with `HLSL`. Anyway I can't figure out what exactly is going on.

Could anyone explain me what exactly `Offset` directly does, and how is solves z-fighting problems?

# Answer
> 5 votes
It appears to be a slightly misleading book. Offset does not change drawing order or even the 3D position of pixels. It simply adds some numbers to the Z value (the one that's going to the Z tests and Z-buffer) of a pixel (hence the term "offset"), making it appear above or below other triangles. This is generally used to prioritize visibility of triangles with (nearly) coincident surface planes.

To find out, what exactly is it that the parameters change, refer to the Unity ShaderLab documentation.

As for Z-fighting... in this case, offset would shift the odds of having more visible pixels towards your road plane.

---
Tags: unity, shaders, cg
---


# Question
Title: Changing gamma values in video settings screen?
So I am trying to change the gamma values and brightness in my game. I think it has something to do with IDirect3DDevice9::SetGammaRamp function but I am not exactly sure how to use it. Anyone has any input on this?

# Answer
In this answer is this link, but it work only in fullscreen mode. ( use IDirect3DDevice9::SetGammaRamp() )

Another approach is using HDR, you can found examples in Directx SDK Samples Directory + look at this example and this.
> 1 votes

# Answer
The Win32 SetDeviceGammaRamp and GetDeviceGammaRamp calls are also options for you; they will work in windowed modes (but will affect the entire screen rather than just the game window) and are somewhat better documented than the D3D versions.

You can also use render to texture and just brighten the texture while drawing.
> 1 votes

---
Tags: video
---


title: Achieving more fluent movement

text:
# Question
Title: Achieving more fluent movement
I'm working on my first *OpenGL 2D* game and I've just locked the framerate of my game. However, the way objects move is far from satisfying: they tend to **lag**, which is shown in this video. I've thought how more fluent animation can be achieved and started getting *segmentation faults* due to accessing the same object by two different threads. I've tried the following threads' setting:

1. Drawing, creating new objects
2. Moving player, moving objects, deleting objects

Currently my application uses this setting:

1. Drawing, creating new objects, moving objects, deleting object
2. Moving player

Any ideas would be appreciated.

EDIT: I've tried increasing the FPS limit but lags are noticeable even at 200 fps.

# Answer
Sounds like something is causing your update loop to run in uneven intervals. Try implementing a fixed timestep loop and your problem should go away.
> 4 votes

---
Tags: c++, opengl, movement
---


title: Stencyl or flash limitation?

text:
# Question
Title: Stencyl or flash limitation?
I have found that Stencyl doesn't seem to be very good at handling very many actors in a game. I had been trying to implement some basic AI at the moment all the behaviours were: wander (pick a random point and move directly to it) and wrap around screen (if it goes off the top of the screen it appears at the bottom). Even with these simple behaviours and calculations the frame rate dropped dramatically when there were more then 50 actors on screen:

10 actors: 60fps

50 actors: 30-50fps

75 actors: ~30fps

100 actors: 15-20fps

200 actors: 8-10fps

I had planned on having a maximum of around 200 actors but I see that's no longer an option and implementing a more complicated AI system with flocking behaviour, looking at creating a game in a similar vein to flOw.

I understand that a game is perfectly playable at 30fps but this is a super simple test with ultra simple graphics, no animations and no sounds is child's play in terms of calculations to be made.

Is this a limitation with Stencyl or is it flash? Should I simply scale the scope of the game down or is there a better game engine that exports to .swf that I should look into?

# Answer
> 3 votes
I crunched the numbers you posted to see where the bottleneck is. To do this I converted FPS to frame time (the time in milliseconds that it takes to render one frame) then I divided the frame time by the number of actors drawn.

```
Actors  Time per actor
10      0.001666667
50      0.0005
75      0.000444444
100     0.0005
200     0.0005

```

It turns out that it doesn't matter if you're drawing 50 or 200 actors, each actor takes roughly 0.0005 seconds to render so there isn't a hardware/software bottleneck that you're running in to, apparently the way you (or stencyl) draws/updates actors at this moment takes that amount of time. So the only option you have is making drawing of actors more efficient. Either by trying to optimize your code, use tricks that Stencyl provides (unfortunately I don't know anything about Stencyl) or by using a more efficient framework.

(note that the 'time per actor' for 10 actors is much higher, probably because the game is limited at 60fps)

---
Tags: flash
---


# Question
Title: What forms of non-interactive RPG battle systems exist?
I am interested in systems that allow players to develop a battle plan or setup strategy for the party or characters prior to entering battle. During the battle the player either cannot input commands or can choose not to.

**Rule Based**
In this system the player can setup a list of rules in the form of \[Condition -\> Action\] that are then ordered by priority.

* Gambits in Final Fantasy XII
* Tactics in Dragon Age Origin & II

# Answer
> 1 votes
Ogre Battle (SNES) does this, with the player having the option to cast powerful spells which are of limited quantity.

# Answer
> 1 votes
In Tales of Symphonia, Phantasia and I believe most other Tales games, you control one main character and your other characters are AI-controlled.

If you're not familiar with Tales RPGs, the battles are carried out in real-time, so the option to have other characters be AI-controlled makes battles easier to manage. In Symphonia, you can set them individually to "Auto", "Semi-Auto" and "Manual" in the battle settings (which you can also change during battle).

It is possible to set all characters to Auto and just see the AI plan itself out. It has a semi-strategy RPG feel if you periodically adjust these settings so the AI can react defensively or offensively.

# Answer
> 1 votes
## Tom Clancy's Rainbow Six (1998)

While a somewhat isolated case, Tom Clancy's Rainbox Six is a first-person military shooter that strived for high-levels of realism as a counter-terrorism simulation. If inclined, a battle plan can be formed before embarking on a mission. During the briefing, you are given a map on which you can plan routes, identify doors to be breached with charges and flashbangs, and complete mission objectives, such as escorting hostages. Completing a mission entirely by AI support is possible. Doing so without losing any members of your team is a real challenge.

# Answer
> 1 votes
The PBM/PBEM Duel2 (formerly known as Duelmasters) has a detailed 1v1 combat system where all tactics are prepared before the battle.

# Answer
> 0 votes
For non-interactive battles taken to the extreme, I can't help but mention the original 1970s RobotWar and its numerous successors such as Robocode.

They're not RPGs, and you probably don't want to go quite that far if you want your game to appeal to a broader audience than just hard-core programmers, but at least they show what's possible.

# Answer
> 0 votes
Progress Quest has completely automated gameplay :)

---
Tags: rpg, strategy
---


title: Drawing graphics in Java game

text:
# Question
Title: Drawing graphics in Java game
I am quite new to game development, so here is a question (maybe a stupid one):

In my sidescroller i have a bunch of different graphics objects that i need to draw (player, background tiles, creatures, projectiles etc). Most tutorials i've read so far show that each object has its own draw method, which is then called from some other method.

What if I had one method that does all the drawing? Lets say i keep all my objects in an array or queue (or multiple arrays) and then go through each of them, get an image and draw it.

So basically would it be better (and why) to have each object have its own draw method or one method that does all the drawing? Or does it matter at all? I feel like the second option is more comfortable, because then all the stuff to do with drawing would be in one place...

# Answer
I like to create an interface that defines a "Draw" method. Whenever a class implements that interface, it means that regardless of what else the class can do, it MUST provide the exact "Draw" method as specified in the interface.

Therefore, even if you have a bunch of different objects - a ball, a player, a field - so long as each of them implement the "Drawable" interface, you can iterate through each one of them and call "Draw".

Of course, each class will have to specify *what* exactly that draw call will do - the interface does not provide this information.

From there, I make a large list of all of my drawable game objects, iterate through it, and call "Draw" on each object.

Quick code example:

Drawable.java:

```
interface Drawable{
    public void Draw(Graphics g);
}

```

Ball.java:

```
class Ball implements Drawable{
    int positionX;
    int positionY;

    public void Draw(Graphics g){
        g.drawOval(positionX, positionY, 5, 5);
    }
}

```

In your application (main class, likely), have the following:

```
DrawableStuff = new ArrayList<Drawable>();
DrawableStuff.add(new Ball());
DrawableStuff.add(new Ball());
DrawableStuff.add(new Ball());
DrawableStuff.add(new Duck());
DrawableStuff.add(new Cloud());

```

Then, in your Component or Canvas' draw function (this depends on your exact implementation, of course):

```
public void paint(Graphics g){
    for (Drawable d : DrawableStuff){
        d.Draw(g);
    }
}

```

Now, all of the drawing is called from a single place in your application.

**EDIT:** One benefit to using this approach is that Draw calls aren't scattered about. Another (more important) benefit is that each class handles the drawing of its instances. So your main application doesn't need to know (or care) how a ball is drawn - all it knows is that (because of the Drawable interface) a ball CAN be drawn (by calling ballObject.Draw(g)). Instead, the Ball class is the only file that holds the code which specifically describes how a ball is drawn. So if you want to change this later on, you only have to modify that one function in the Ball class, nowhere else.

It can also be convenient to maintain several different lists of objects based upon their type, so for example, one list of all the ducks, one of all the turtles, and one of all the clouds, but the reasons for this are likely beyond the scope of this question (one example: to minimize the amount of graphics state that must be changed between 'batches'). This approach is a little more flexible later on down the road.

Wheather you maintain one unified list of Drawables, or multiple lists of objects, you absolutely should define a "Draw" function in the specific class, for the above-mentioned reasons. It might seem like it's adding more code right now while the drawing routines are simple, but once you start having drawing lines that consume pages and pages of code, you'll be very glad that that code is sequestered away in a specific place, not littered about your main game loop with everything else.

This is a very broad topic, but hopefully that gives you an idea of where you can start.
> 5 votes

# Answer
A typical "Draw" interface that all the graphics object in your game would implement would be something like

public void draw(Graphics gc, int x, int y, double scale) ..

where the Graphics was from the canvas or backing array where the drawing is actually accumulating. x y would mark the center of where the object should go, and scale would be a parameter to scale the object up or down from some arbitrary "normal" size.

Of course, there are many ways to refactor and decorate this with other options, it all depends on what you need for your application.
> 1 votes

# Answer
What I would do is keep a public `Image` reference to every object and draw them in the `paint()` method of the component.

```
public class MyObject {

    public Image img;
    public float x, y;

    .....

}

public class MyGame extends JPanel {

    MyObject mo;

    public void paint(Graphics g){
        g.drawImage(mo.img, mo.x, mo.y);
    }

}

```

It is so easy to make this. And first try using a game engine. You can learn deeper later which takes time.
> 1 votes

---
Tags: java, rendering, graphics-programming
---


title: Collision Detection fails with AI cars

text:
# Question
Title: Collision Detection fails with AI cars
I am making a car parking game in flash and AS3 wherein I drive my car along with other AI traffic cars moving along a specified path using Guidelines.

I am using CDK for collision detection.

The collision detection works fine with few AI cars, but doesn't seems to be working as required for few AI cars.

When an AI car is moving on a path in a straight line it works fine.... but when the AI Car turns at 90 degress..... my car goes into the AI car (Overlapping) and it hits at the center of that AI car and then collision is Detected.... .....

I made a New path and used a new Sprite for AI car... but still the problem pursues....

---

I have attached the png of collision. https://dl.dropbox.com/u/53998590/Collision.png

The AI traffic comes from Top Left corner and moves down towards bottom right corner.

The problem persist with this kind of movement.

when I change the movement of same AI cars from bottom right corner and moves up to top left corner then the problem does not exist.

I had used CDK for collision detection.

my code is as follows.

```
addCollisonItem(mcAICars);

public function addCollisionItem(mc:MovieClip)
    {
        collisionlist.addItem(mc);
    }

var collArray:Array;
collArray = collisionFunction();

if (collArray.length > 0 && isCarCollided==false && game.stopCar ==false)
        {

            trace("Car Collided");

            isCarCollided = true;
            game.stopCar = true;

            if (speed >= 2) {
                speed = 1.5;
            }

            speed = -speed;

            if (accelerate && isCarCollided)
            {
                //reverse = false;
                speed = -1.5;
                //  return;
            }
            else if (reverse && isCarCollided)
            {
                //accelerate = false;
                speed = 2;
                //  return;
            }

            reduceLife();

            setTimeout(startCar, 500);

        }

```

Regards, Amit

# Answer
> -1 votes
Then you must be using a linear-collision-detection. You should add a 5-point derivative system to find the next speed&position of the next iteration for both X and Y directions.

http://en.wikipedia.org/wiki/Numerical\_differentiation

---
Tags: collision-detection, actionscript-3, flash-cs5
---


title: animate a drawn 2D image to move

text:
# Question
Title: animate a drawn 2D image to move
I am trying to make a game where the person can create their own character, but instead of using a character builder, i want the person to be able to draw their character. how do i code that in c# so that they only have to draw their character once, and the code can animate that character without the player having to do very much except draw their character on the screen?

# Answer
> 5 votes
One way to do it would be to make the character consist of different parts. I'm currently working on a 3D game, and I have written an exporter for Blender in Python that takes the currently active (selected) object and exports it's data and then goes recursively through all of the object's children and their children and so on, so I end up with a sort of a file with a tree like structure where there's one root object (the first one written) and the other ones are laid down after it, and they all have number of children written as part of their data so the parser (written in C) knows how to reconstruct the entire model tree so I can translate/rotate/scale any part and all it's children will have the same transformation applied.

So, I'd suggest doing a similar thing, just making things fixed. For example:

* You have an interface where a user can draw a torso. Besides actual pixel data, you can also let them put where the head and extremities will be attached, sort of a pointer that they can drag around and place where they want. Then, when the user goes to draw the head of the character, he should be able to see the point where the head connects to the torso and draw around it. Same thing for legs and arms.
* Then you can load that data (pixel values and joint positions) and draw them accordingly.
* Animate them relative to their respecting marker's positions.
* Something like this:

---
Tags: xna, animation, character
---


# Question
Title: How to use batch rendering with an entity component system?
I have an entity component system and a 2D rendering engine. Because I have a lot of repeating sprites (the entities are non-animated, the background is tile based) I would really like to use batch rendering to reduce calls to the drawing routine. What would be the best way to integrate this with an engtity system?

I thought about creating and populating the sprite batche every frame update, but that will probably be very slow. A better way would be to add a reference to an entity's quad to the sprite batch at initialization, but that would mean that the entity factory has to be aware of the Rendering System or that the sprite batch has to be a component of some Cache entity. One case violates encapsulation pretty heavily, while the other forces a non-game object entity in the entity system, which I am not sure I like a lot.

As for engine, I am using Love2D (Love2D website) and FEZ ( FEZ website) as entity system(so everything is in Lua). I am more interested in a generic pattern of how to properly implement that rather than a language/library specific solution.

Thanks in advance!

# Answer
> that would mean that the entity factory has to be aware of the Rendering System

If your entity factory function has to create objects for/from the rendering system, the obviously your entity factory function *needs to create objects for/from the rendering system*. There's no avoiding that; it's a part of what you need to do.

A component system is not supposed to eliminate dependencies. It's supposed to minimize them and focus them on the *necessary* dependencies, not the unimportant ones.

Users of your entity class shouldn't need to specifically know about the rendering system, unless they are dealing with the visual representation of an entity. Users of your entity *creation* functions may need to because, as code responsible for building entities, they need to know about all of the things that entities depend on. Thus, the dependency is focused on where it is *needed*.

Doing this doesn't violate encapsulation; the entity creation process needs to create rendering system objects (as well as possibly sound objects and other such things). It needs to know about these things in order to do its job.

To create an entity, the entity factory code must either be given some kind of rendering system object to create the visual representation from, or it must go out and find it. One of these things has to happen. You can create abstraction after abstraction, and it *still* will need to happen somewhere. If an entity needs a visual representation, then some piece of code *somewhere* is going to have to know about both entities and visual representations.
> 4 votes

# Answer
Make a sprite factory (preferably inside another rendering-related structure, like the renderer). It can internally be capable of ordering and grouping sprite data as required for batching.
> 2 votes

---
Tags: entity-system, spritebatch, love2d
---


# Question
Title: Adding sub-entities to existing entities. Should it be done in the Entity and Component classes?
I'm in a situation where a player can be given the control of small parts of an entity (i.e. Left missile battery). Therefore I started implementing sub entities as follow.

Entities are Objects with 3 arrays:

* pointers to components
* pointers to sub entities
* communication subscribers (temporary implementation)

Now when an entity is built it has a few components as you might expect and also I can attach sub entities which are handled with some dedicated code in the Entity and Component classes.

I noticed sub entities are sharing data in 3 parts:

* position: the sub entities are using the parent's position and their own as an offset.
* scrips: sub entities are draining ammo and energy from the parent.
* physics: sub entities add weight to the parent

I made this to quickly go forward, but as I'm slowly fixing current implementations I wonder if this wasn't a mistake.

Is my current implementation something commonly done? Will this implementation put me in a corner?

---

I thought it might be a better thing to create some sort of SubEntityComponent where sub entities are attached and handled.

But before changing anything I wanted to seek the community's wisdom.

# Answer
> 2 votes
We use a Child Component which has a list of templates to spawn when the owner of the child component is spawned. A template is a defined set of components that make up a given entity. So our AIs can have multiple weapon entities where each weapon entity has different components, effects, etc. The behaviors on the parent AI would then figure out which weapon to use based off other rules at runtime. If setup incorrectly this certainly can have un-needed complexity. I think it works out ok since we have specific standards and formatting to the data.

The children entities don't know about their parent and don't need too beyond a possible scene-graph based parenting relationship.

# Answer
> 1 votes
I'm no expert in entity system but your case seems unnecessary complicated. I will instinctively say that making sub-entities sounds like a mistake, using a wrong system to solve that problem.

Lets explore why...

Components for me are basic building blocks. If you need something to be damageable, you add DamageableComponent, if you need it to move you add MoveableComponent ... and so on. If you add sub-entities, the whole thing becomes unclear.. do sub-entities inherit components of parent? Would be logical on first thought, but then again if they are almost the same as parents, why have them divided into smaller parts at all with all that duplication going around? On the other hand, if they don't share parent's components, they are drastically changing what the parent entity is about, because how can it be "Damageable" if it has parts that are not "Damageable". I find it easy to look at them as basic building blocks, no smaller divisions.

I can propose 2 solutions:

1. If you really need parts of entity to be controllable and it will be used often, not just as exception to the rule on a single object but as a system that will appear often in the game: Make a component that describes that the entity object has parts, like "PartsComponent". The component will contain data about various parts that entity has, their name and specifics that don't belong to parent entity. This will probably be more complex as you'll need to modify ControlComponent to manage parts also, or make a new component for that.
2. if you need an exception just for few times: screw it, make a single component "LeftMissleBatteryControllable" and code directly dependent on the class :)

Again, I'm not expert by any means, just worked with entity systems in games, I'm open to suggestions and criticism :)

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


# Question
Title: Method for spawning enemies according to player score and game time
I'm making a top-down shooter and want to scale the difficulty of the game according to what the score is and how much time has Passed. Along with this, I want to spawn enemies in different patterns and increase the intervals at which these enemies are shown. I'm going for a similar effect to Geometry wars. However, I can think of a to do this other than have multiple if-else statments, e.g. :

```
        if (score > 1000) {
    //spawn x amount if enemies
        }
        else if (score > 10000) {
    //spawn x amount of enemy type 1 & 2
        }
        else if (score > 15000) {
       //spawn x amount of enemy type 1 & 2 & 3
        }
        else if (score > 25000) {
       //spawn x amount of enemy type 1 & 2 & 3
       //create patterns with enemies
        }
       ...etc

```

What would be a better method of spawning enemies as I have described?

# Answer
Here are some ideas that come to my mind:

* Calculate the score per minute ratio. For example, weaker enemies give 25 points, stronger ones 100 and the badasses, let's say 250. Use that value (score/min) to adjust the number of enemies that spawn. For example, determine the average score/min of a casual player and use something like numEnemies = currentSPM/averageSPM * 100. Adjustments are needed if player simply avoids enemies -\> numEnemies approaches 0 and he wins the game easily. You can control WHEN there will be a change in the number of enemies - for example if currentSPM / averageSPM \>= 0.5 (that way the game will not drop the number of enemies being generated below 50%).
* Calculate aforementioned spm for each type of enemy. For example, if the player is successfully killing the weaker enemies but avoiding the stronger ones, increase the number of stronger ones also: e1\_numEnemies = e1\_curSPM/e1\_avgSPM\*100; e2\_numEnemies = (e2\_curSPM/e2\_avgSPM + e1\_curSPM/e1\_curSPM\*0.25)\*50 (...) this adds more type 2 (stronger) enemies the more player kills type 1 enemies (the weaker ones) - but the SPM ratio for e1 contributes with just 25% to the number of type 2 enemies.
* Divide the play area into quadrants. Let's say it's a 4 x 8 field (it's a top down shooter, right?). Detect in which quadrants the enemies are most likely to die and make new enemies come at player from that ones more likely.
* Alternatively, determine in which part of the playfield the player's ship is the most. Also make enemies spawn there more often (if they're at the left corner of the screen for example most of the time, that means the other parts of the screen are to hostile, and that one is not, so you want to make it more hostile).
* Detect which weapon the player uses most successfully and make the enemies a little more resistant to that type of weapon.
> 5 votes

# Answer
For endless games like Geometry Wars your approach is a bit too static. I would calculate the wanted difficulty from multiple factors, then randomize it. With the following example harder enemies would get more probable while weaker enemies get less probable the more advanced you are into the game. Using random numbers increases the dynamics of your game, however can create "unfair" situations. Which is more important depends on your target audience.

```
bool spawnEnemies(float spawnLevel)
{
  // After 2 minutes, only spawn patterns of the smaller enemies anymore
  if(getTime() > 120.f)
    if(spawnLevel < 2000)
      spawnLevel = 2000;
  // Spawn a small amount of weak enemies
  if(spawnLevel < 500)
    [...]
  // Spawn single normal enemies
  else if(spawnLevel < 1000)
    [...]
  // Spawn patterns of weak or normal enemies
  else if(spawnLevel < 2000)
  {
    float temp=randomFloat(1.f);
    if(temp < 0.2f)
      [... spawn pattern 1 ...]
    else if(temp < 0.4f)
      [... spawn pattern 2 ...]
    else
      [... spawn pattern 3 ...]
  }
  // Harder enemy
  else if(spawnLevel < 20000)
      [...]
  // Bosslike enemy
  else if(spawnLevel < 200000)
      [...]
  [...]
}
[...]
float timeFactor=difficultyLevel*5.f;
float scoreFactor=1.f/difficultyLevel;
float spawnLevel=getTime()*timeFactor+getScore()*scoreFactor;
if([...]) spawnEnemies(randomFloat(spawnLevel));
[...]

```
> 2 votes

# Answer
One route I might take is to implement some sort of level class and level manager that allows me to determine when a level has been beaten and to move onto the next one when it has. The following is a rather crude example and should be implemented in a way to fit whatever engine design you are working towards:

```
//LevelManager levelManager = new LevelManager(); //Queue up your levels wherever you instantiate the LevelManager maybe

//If the level has been beaten
//Could be a score check, game time check, boss beaten check, etc.
if (!LevelManager.ActiveLevel.IsActive)
{
    //Queue up next level
    LevelManager.NextLevel();
}

Level.Update(); //Execute your spawning here

```

So your LevelManager will keep track of what levels are coming up and the Level will manage itself as far as when to spawn units, what types of AI should the units have, and when has the player beaten this level.
> 0 votes

---
Tags: xna, c#, game-design
---


# Question
Title: Custom extensible file format for 2d tiled maps
I have implemented much of my game logic right now, but still create my maps with nasty for-loops on-the-fly to be able to work with something. Now I wanted to move on and to do some research on how to (un)serialize this data. (I do not search for a map editor - I am speaking of the map file itself)

For now I am looking for suggestions and resources, how to implement a custom file format for my maps which should provide the following functionality (based on MoSCoW method):

* *Must have*
    + Extensibility and backward compatibility
    + Handling of different layers
    + Metadata on whether a tile is solid or can be passed through
    + Special serialization of entities/triggers with associated properties/metadata
* *Could have*
    + Some kind of inclusion of the tileset to prevent having scattered files/tilesets

I am developing with C++ (using SDL) and targetting only Windows. Any useful help, tips, suggestions, ... would be appreciated!

---

## Result of the discussion below

I have been designing my map file format the last few hours and came up with a skeleton (contains only layers for now - I'll leave the rest to everyone designing his/her own format) which I wanted to share with everyone interested - if you have the same intentions you can get some kind of inspiration. The full-size screenshot can be downloaded at Imgur.

# Answer
Personally, I'm more of a fan of binary formats with sections (like Windows PE, just much simpler). They are also easier to parse (but that's just my opinion.... I did work with XML enough to give me headaches, checking whether getElementByName has returned a single value or a list of values... ugh). So, if I were you, I'd make it something like this:

```
".MMF\0" // magic value at the start, null-terminated string. stands for My Map Format :)
    char header_length // useful when parsing. char is a byte, of course, an unsigned one
    char version // version of the map file. (you don't really need ints here, because you probably won't be needing more than 255 versions for example, but you can also use them)
    char* map_name // null terminated string describing the name of the level/map
    char* author_name // if you are going to have a map editor for the general public, it would be nice to credit the person who made the map
    int width // it's probably wise to plan ahead and expect an int here when you're parsing the file
    int height
    ".layer\0" // we begin another subsection
        char header_length
        char type // type of the layer. for example, you can put 1 there if you want this to be a layer describing different tiles/block in a Terraria like game
        ".data\0" // yet another subsection. this will hold the data for the tiles
                  // in a hypothetical terraria 2d game, you would lay down tiles from
                  // the top-right corner (0,0) and then begin writing row after row
                  // write(1,0); write(2,0); write(3,0); ... then write(0,1); write(1,1);
                  // write(2,1); write(3,1); and so on..
            char t1 // tile at (0,0). for example, value 0 is empty, or passable tile
            char t2 // tile at (1,0). this might be a dirt block - value 1
            char t3 // tile at (2,0). a rock, perhaps? value 3
            (...)
            char tn // tile at (width-1, height-1) or the bottom-left tile
    ".layer\0" // another layer.
        char header_length
        char type // let this on be of value 2, and let it describe portals.
                  // putting portals in a game makes it instantly 20% cooler
        ".data\0"
            char t1  // 0, no portal here at tile (0,0)
            char t2  // still nothing
            char t3  // nope, try again
            (...)
            char t47 // at some location, you made a red portal. let's put 1 here so we can read it in our engine
            (...)
            char t86 // looke here, another 1! you can exit here from location corresponding to t47
            (...)
            char t99 // value 2. hm, a green portal?
            (...)
            char tn  // bottom-left tile, at (width-1, height-1)
    ".layer\0" // another layer
        char header_length
        char type // value 3, player&enemies spawn points
        char something // you don't have to have header len fixed. you can add stuff later
                       // and because you were smart enough to put header length
                       // older versions can know where the stuff of interest lays
                       // i.e. version one of the parser can read only the type of layer
                       // in version two, you add more meta-data  and the old parser
                       // just skips it, and goes straight to the .data section
            ".data\0"
                char t1  // zero
                char t2  // zero
                char t3  // zero
                (...)
                char t42 // a 1 - maybe the player spawn point. 5 tiles to the right
                         // there's a red portal
                (...)
                char t77 // a 2: some enemy spawn point
                (...)
                char tn  // last tile

```

,

Advantages:

* Looks cool.
* Makes you think you know something about programming, doing stuff the old fashion way.
* You can manually write your levels in a hex editor:
* Generally faster than INIs and XMLs, both from writing and reading perspective
* It's a long stream of byte data, really. No need to spend time on making it look pretty, indentation wise (like what you'd want to do with XML).
* It's easy to add stuff in the headers. If a piece of data comes at the bottom of the header, old versions of parsers can be instructed to avoid it and jump to the part of the file they understand.

Disadvantages:

* You have to take good care of data placement.
    + Data fields must be ordered.
    + You must know their type in parser - like I said, it's just a long stream of bytes.
    + Moving data by one location (for example, you forget to write the type of the layer; the parser expects a byte there and it finds the value of '.' - that's not good) messes up the entire data array from that point onward.
* Harder to jump right into - there is no API, no function like getLayerWidth() - you have to implement all of that yourself.
* There's potentially a lot of wasted space. Take the third layer for example. It will certainly be packed with a lot of zeros. This can be circumvented though if you use some sort of compression. But again, that's messing with low-level stuff yet again...

But the best thing in this approach in my opinion is - you get to do it all by yourself. Lots of trial-and-errors, but at the end, you end up learning a lot.
> 6 votes

# Answer
You could use the TMX map format used by the Tiled editor (as well as several other map editors).

Even if you don't use Tiled yourself, the TMX format supports all the functionality you mentioned and it has several existing loaders/parsers for a variety of languages. It's also very easy to understand the format and extend it for your own game.
> 9 votes

---
Tags: c++, maps, sdl, data-structure, file-format
---


# Question
Title: How can I generate a 3d model via a series of transforms?
Is it possible to generate 3D models using some sort of object transformation (like it's shown here), using PovRay or any other tool, and import them into Blender / Unity?

For example starting with a primitive sphere:

And applying a series of transforms/noise to generate something like:

Then baking them in, resulting in a 3D model of an asteroid that can be used in game.

# Answer
Yes, you should actually be able to do this within Blender using a Python scripting. There are plenty of functions available for modifying meshes. You should be able to follow the tutorial you provided, converting the methods into Python and adapting them to modify a mesh of your choosing.

Alternatively, you could write a application in your language of choice. Perform the operations described in the tutorial on an array of vertices. Finally, output the vertices into one of the popular formats that Blender imports and import the mesh into Blender for further manipulation or whatever you end goal is.

It does appear you can go from PovRay to Blender if your scene is made entirely of meshes. I don't know much about PovRay, but I don't see any indicator that the tutorial uses meshes, so you may be out of luck there.
> 4 votes

---
Tags: 3d, unity, models, blender
---


# Question
Title: Is there a browser game engine with options of payments?
I would like to make some browser game, where you can buy stuff for real money. Is there any engine I could use? Or should I implement it by myself?

# Answer
> 1 votes
Something like that (very probably) doesn't exist. I recommend using a framework/engine for the game itself and a library that allows payment via credit card or Paypal.

---
Tags: browser
---


# Question
Title: How do I find out which functions are deprecated for specific OpenGL profiles?
I would like to get the list of functions that are part of a certain OpenGL profile and the list of the ones that are deprecated so that I can avoid those.

# Answer
> 9 votes
The true source of this information is in the various OpenGL specifications. They contain a list of what functions there are, what their definitions are, what enumerators those functions take, and so forth. For each OpenGL version.

If you want what was ***removed*** (deprecated means "present but not advised to use". When something is removed, it is *removed*), the 3.1 spec section E.2.2 has a list of the removed functionality.

However, if you simply want to avoid non-core functions, you should use an OpenGL loading library that has headers that exclude removed functions. GL3w can work in this capacity, but it doesn't load extensions. The only one I know of that does this is my own (which is why I wrote it; to get rid of the non-core cruft).

# Answer
> 2 votes
As an alternative to navigating the registry PDFs.

The quickest/easiest way I have found is to do a search in the raw gl.spec file. It's the file from which the other stuff is generated, not designed to be human readable but isn't bad.

Just remove the leading prefixes, gl or GL\_ from the name. The entries have a deprecated property as well as adding them to a deprecated category. It also tells you at what version it was introduced so you know when it's been made available.

You could also process them using a simple script to extract the information and put it into a list.

# Answer
> 1 votes
You have all this information in he OpenGL Registry. There you can check the current OpenGL API, OpenGL Shading Language and GLX Specifications and Reference Pages, as well as the old versions'.

---
Tags: opengl
---


title: Android, how important is deltaTime?

text:
# Question
Title: Android, how important is deltaTime?
Im making a game that is getting pretty big and sometimes my thread has to skip a frame, so far I'm not using deltaTime for setting the speed of my different objects in the game because it's still not a big enough game for it to matter imo. But its getting bigger then I planned, so my question is, how important is delta Time?

If I should use delta time there is a problem, since `speedX` and `speedY` are integers(they have to be for eclipse to let you make a rectangle of them), I cant add delta time very functionally as far as I understand, but might be wrong? Ive tried adding deltaTime to the code below, and sometimes my enemies just not move after spawn, they just stand there and run in the same place

Will add an some code for how I set / use speed:

```
     public void update(int dx, int dy) {
        double theta = 180.0 / Math.PI * Math.atan2(-(y - controls.pointerPosition.y), controls.pointerPosition.x - x);

        x +=dx * Math.cos(Math.toRadians(theta));
        y +=dy * Math.sin(Math.toRadians(theta));
    currentFrame = ++currentFrame % BMP_COLUMNS;
}

     public void draw(Canvas canvas) {
    int srcX = currentFrame * width;
    int srcY = 1 * height;
    Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
    Rect dst = new Rect(x, y, x + width, y + height);
    canvas.drawBitmap(bitmap, src, dst, null);
}

```

So if someone with some experience with this has any thoughts, please share. Thank you!

Changed code:

```
    public void update(int dx, int dy, float delta) {
        double theta = 180.0 / Math.PI * Math.atan2(-(y - controls.pointerPosition.y), controls.pointerPosition.x - x);
        double speedX = delta * dx * Math.cos(Math.toRadians(theta));
        double speedY = delta * dy * Math.sin(Math.toRadians(theta));
        x += speedX;
        y += speedY;
    currentFrame = ++currentFrame % BMP_COLUMNS;
}

     public void draw(Canvas canvas) {
    int srcX = currentFrame * width;
    int srcY = 1 * height;
    Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
    Rect dst = new Rect(x, y, x + width, y + height);
    canvas.drawBitmap(bitmap, src, dst, null);
}

```

with this code my enemies move like before, except they wont move to the right (wont increment `x`), all other directions work.

# Answer
Delta Time is used to make your game speed constant, independently of framerate. If your game starts to get "heavier", it will start to slow down in framerate on less powerful android systems. For example, if you made it to run on 60 FPS, an Android cellphone that can run it at 30FPS will have the game slowed down by 50%!

By including the DeltaTime in the game, you assure that the game speed remains constant, even when the FPS is low or keeps changing.

So yeah, unless you are 100% sure your game will run at full FPS on every system, I'd say DeltaTime is pretty damn important.

Also, about how to use DeltaTime properly:

To use it properly, you have to multiply it by a value that is being updated on every frame. For example, if you have your speed being increased by 10 units per second, you'd use something like this:

```
Speed += 10 * DeltaTime // Must be inside a function that is called every frame

```

You don't need delta time if the instruction is only going to be called once, only if it's something that is being called at every frame. DeltaTime is the ammount of time passed since the last frame (in seconds) and is usually a very small value, so multiplying it by something that is called only once will just make that value very close to zero.
> 8 votes

# Answer
> with this code my enemies move like before, except they wont move to the right (wont increment x), all other directions work.

add a Log trace after your speedX affectation:

```
double speedX = delta * dx * Math.cos(Math.toRadians(theta));
Log.e("","speedX: "+speedX);

```

and check if speedX is \>0 when enemies are supposed to move to the right
> 0 votes

# Answer
If you start to notice the frame skips, especially as you're one of the people testing it and know it really well, then you should add deltaTime.

But if you don't notice the frame skips, then you don't need deltaTime.
> -4 votes

---
Tags: 2d, android, html-canvas, game-loop, frame-rate
---


# Question
Title: How much does it cost to produce a major video game?
I asked this same question here, but was closed and told to ask it on this site instead.

How much would it cost to develop a video game. I mean like a major PS3/360 video game. I know there really is no set price; but there has to be a pall bark, 100 grand, 10 mil, etc.

I am asking how much the games cost to make, (studio cost, developer salaries, etc.)

Examples would be nice.

# Answer
Somewhere between $20M and $100M would be reasonable depending on genre for a AAA game. XBLA/PSN downloadable games often cost much less, and people have made XBLIG games for a few hundred dollars in their spare time. As a recent example, APB was rumored to have cost $100M (MMOs are among the most expensive games to produce).
> 17 votes

# Answer
Depending on your location and how awesome an office and benefits you're looking at, (in the US) you can count on $8,000 to $15,000 per developer per month. This is the fully loaded cost and includes IT and HR costs as well as equipment and other infrastructure.

For $8000 per person-month, though, you're going to be in a pretty crappy warehouse on the wrong side of the tracks in the middle of nowhere. In Southern California the range is more like 11-15k per person-month, although some studios may go even higher than that.

**Edit:** It's worth reiterating even though it's probably obvious. The above costs do not reflect the salaries alone. While there are a few people in the US game industry making $150k+, it is rare. The above numbers are salary plus benefits plus taxes plus facilities and all that jazz. Health insurance is huge, social security is 7.5% of your salary out of the company's pocket (and another 7.5% comes out of your paycheck), etc., etc.
> 10 votes

# Answer
It varies widely. Ballpark is 8 figures for a big-budget ("AAA") title these days... i.e. 10 to 100 Million (US $). But a lot depends on how you count, and there are tons of exceptions.

Here's a good way to guesstimate:

1) How many people on the team? A small team is around 20-30 people, large team would be several hundred. Look at the credits of a few games you own (either on the Credits screen from main menu if there is one, or in the back of the instruction book... or just check www.mobygames.com).

2) What was the length of development? Typical range for AAA development is 2-5 years.

3) Where was it developed? Games made in San Francisco are going to cost more in payroll than those made in Denver. Look up the IGDA Salary Survey, adjust for cost-of-living of the area, and cut it by a small amount because the Salary Survey is slightly inflated.

If you have a particular kind of game in mind, find some similar games (same genre, comparable production values) and you can probably research all three of the above things for a similar title.

Then, multiply: size of team (number of people) X length of development (years) X average annual developer salary ($/year). That gives you the baseline development cost in payroll.

Example for a small game: 20 people X 2 years X $40K/year = $1.6M Example for a large game: 200 people X 5 years X $60K/year = $60M

What about other "operations" costs (office space, computer hardware and software, electricity, payroll services, etc.)? Ballpark, estimate those as 25% of the total dev cost, with payroll being the other 75%. So multiply the above figure by an extra 4/3 to get the final dev cost estimate.

If you want to include publisher costs (manufacturing, distribution, advertising), ballpark that as equal to the dev cost, so multiply your figure by 2 to get the final total cost of a game.

Hint: next time you hear someone complain about how video games are so expensive because they cost $60, remind them that the little package in their hand cost a lot more than $60 to develop :)
> 5 votes

# Answer
Game development costs are something developers tend to keep pretty close to the vest, so it can be difficult to find examples.

In 2009, Ubisoft CEO Yves Guillemot is quoted as saying the cost for creating a major title for PS3 or Xbox 360 is typically between $20 million and $30 million.

Nintendo's Reggie Fils-Aime is quoted as saying costs can be $20 million up to a staggering $50 million with sales of 1.3 to 1.5 million units to make money.

Obviously, MMOs and games built in tandem with their engines, cost significantly more.
> 4 votes

# Answer
There is a list of most expensive games and their costs here.

Some items from the list:

* Grand Theft Auto IV - $100 million
* Gran Turismo 5 - $80 million
* Shenmue - $70 million
* Final Fantasy VII - $45 million, plus $100 million marketing

Interestingly also on the list are some old games, like Dragon's Lair, costing $1.3 million in 1883.
> 4 votes

# Answer
You would need some serious cash upfront to fund the development of a game, and the people who lend you the money would need some strong evidence that you have the potential to make the game and profit from it, otherwise they wouldn't invest.
> 2 votes

# Answer
You could probably make a cheap AAA console title for $2 or $3 million, but that would be with quite a small team using existing technology. Anything content-rich would require more artists and/or designers and hence cost more. Most of the money goes on salaries, in any case.
> 1 votes

# Answer
There was a cool video game (PC and XBOX360) released a year ago by a big polish gamedev team. It's called The Witcher 2. It took them 30 milion zloty. It's something around 7 milion euros (9 milion dollars). A team of 100 people created 40+ hours of gameplay in 11 language versions.

Source (in Polish) http://www.nowiny24.pl/apps/pbcs.dll/article?AID=/20110222/GRY/744199752
> 0 votes

---
Tags: xbox360, playstation3, costs
---


title: What kind of shader is this?

text:
# Question
Title: What kind of shader is this?
Cube World uses a pretty good looking shader, I especially like the shading of the characters:

Is this soft shading? I'd like to achieve this effect in Unity 3D Free, but since the free version doesn't support dynamic shadows, guess I have to code it myself, so an article on this or the algorithm would be great.

# Answer
I don't see any special shaders there, just some vertex colors that are generated with an ambient occlusion (or similar) calculation algorithm and perhaps some differently calculated vertex normals. The results remind me of a demo I've seen some time ago which simulated global illumination by "bending" vertex normals and generating occlusion values for vertices.

The only thing one might call a special shader could be a hemisphere/SH (spherical harmonics) light that appears to be used in there.
> 4 votes

---
Tags: unity, algorithm, shaders, shadows, cg
---