title: Approaches to 2D Parallax

text:
# Question
Title: Approaches to 2D Parallax
In a 2D scrolling platformer, what is the most efficient way or knowing which things with parallax depth should be drawn?

The approach below describes trying to know which things are nearby so they can be udpated/drawn. The problem with working out which parallax items are nearby is that you don't know where any of them are until you calculate where they are!

**Original Post**

I have a 2D array `Set<Thing>[][]` that I use to store `Thing`s that appear on each screen in a scrolling 2D platformer. I use this to look up only `Thing`s that a near the current location being rendered, so that I don't bother updating irrelevant objects.

I translate the world coordinates, divide them by the screen size (rounding down), and can then look up all the items on that screen. For instance if screens are 320x240px, and I look up world coordinates 400,50 then 400/320 = 1 and 50/240 = 0, so I look up `things[1][0]` and update all the things in that entry. If any object can move, they store themselves in the right slot after moving.

Is there any way to use this same system when `Thing`s have parallax depth? IE, something with a parallax depth of 1 is infinitely far away (and so always appears at the same location in screen coordinates) and something with parallax depth of 0 is pinned to the foreground.

I'm guessing this isn't possible, as something further away than the foreground will be in more than one screen.

What other approaches are there? I've seen an experienced game developer use a 'scroll rate' instead of a parallax depth, and he moved scenery by the inverse of the distance the camera moved multiplied by this rate. In this model I could treat scenery as per any other moving item and have it store itself in adjacent entries in the 2D array when it moves, but how does it get into the 'right' array slot in the first place? IE, if it's very distant, it could be approach from either the left or the right, and I'm not to know that in advance.

I'm very confused!

# Answer
> 1 votes
This depends whether you have:

1. Just a small number of different levels of parallax depth
2. A continuous (i.e. near-infinite) number of different depths

For 1), it will probably be most efficient and simpler to just treat the levels independently and query the appropriate rectangle in each level.

2) is harder. You are effectively querying a subset of a 3D space. If you interpret the parallex depth as "scroll rate" then this shape is actually a highly skewed cuboid (with the back of the cuboid fixed at the same place on the infinte depth = zero scroll rate plane). Strategies for this:

* You could use some form of spatial partitioning algorithm to query this shape efficiently (BSP trees, octrees etc.) but be aware that these algorithms may need some tuning as they aren't typically designed for skewed cuboid queries :-).
* Query only inside the axis-aligned bounding box of the skewed cuboid. This will get inefficient if the cuboid is really skewed / on a diagonal, but is still better than querying everything. You can use your current `Set<Thing>[][]` for this - just query everything in a rectangle from the current screen position to the \[0,0\] screen (which will contain the infinite distance / zero scroll rate background).
* Some hybrid model, where you query subregions that together cover the whole cuboid. This could be a grid-based structure (e.g. a big 3D array where you subdivide the scroll rate dimension into 5-10 different ranges from 0.0 to 1.0). This is like a 3D version of your current approach, i.e. you could have a `Set<Thing>[][][]` as a data structure

Either way, I think "scroll rate" is going to be the most convenient way to this about this rather than "depth". It will make the maths and geometry easier :-)

---
Tags: java, 2d, parallax-scrolling
---


title: Drawing Text on a scene

text:
# Question
Title: Drawing Text on a scene
I am not sure if I am missing something but I was thinking about how text entities are drawn on a scene, are they drawn with an offset depending on the length of the text? I notice that when I add a new `Text` element at say `new Text(10, 20,.....` and the actual text content is 50 words long the text is drawn far over to the right and when I use the same instance with a smaller text content that text is drawn closer to the actual coordinates I need. Should I always recalculate `X` and `Y` vectors with respect to the current portion of the scene being shown on the camera?

```
Words:
      String words = "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here. " +
        "Hello, I see that your new here.";

 //method call
 createSpeech( BodyA.getPosition().x, BodyA.getPosition().y, words );

 //method definition
 private void createSpeech(float xVal, float yVal, String ptext) {

    xVal = xVal * GameConstants.PIXEL_TO_METER_RATIO_DEFAULT;
    yVal = yVal * GameConstants.PIXEL_TO_METER_RATIO_DEFAULT;

    speech = new TickerText( 0, 0, ResourceManager.getInstance().font,
            words, new TickerText.TickerTextOptions( 10 ), ResourceManager.getInstance().vertexManager );

    speech.registerEntityModifier( new AlphaModifier( 5, 0.0f, 1.0f ) );
    speech.setBlendFunction( GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA );
    speech.setScale( 0.5f );
    speech.setHorizontalAlign( HorizontalAlign.CENTER );
    speech.setAutoWrapWidth( 500f );
    speech.setAutoWrap( AutoWrap.WORDS );

    speech.setPosition( xVal, yVal );

```

Screenshots: The Red and orange lines indicate where the text is shown currently, the blue region is where I want the text to be shown. The calculations I used to set the text position and the text itself is shown above

I think the text object itself might have something to do with the offset positioning because when i use a smaller string value the position of the text changes as well

# Answer
> 1 votes
Yes, you need to recalculate position of text entity. The Text entity has its own height and width, and the height/width will be updated automatically after you reassign string for the same text entity. (The height/width is like the orange rectangle showing in your picture)

When you call `text_entity = new Text(10, 20, ...)` and `yourScene.attachChild(text_entity)`, it means you place the "anchor point of text entity" to the "point of your scene" ((10, 20) in this case). Depending on your andengine version, the anchor point of any entity may be on the top-left corner (GLES2 branch) or horizontal/vertical center (GLES2-AnchorCenter branch).

Assume you're using GLES2-AnchorCenter branch, and you need your char\_entity and text\_entity to be left-aligned, and vertical connected. The text\_entity's new x, y as below: (remember the anchor point is in the center of entity)

```
x of text_entity = char_entity.x - char_entity.width * 0.5f + text_entity.width * 0.5f
y of text_entity = char_entity.y + char_entity.height * 0.5f + text_entity.height * 0.5f

```

Hope this help.

**Update** calculation for GLES2 branch (anchor point is located at top-left corner, y decrease up toward)

```
x of text_entity = char_entity.x
y of text_entity = char_entity.y - text_entity.height

```

---
Tags: android, opengl-es2, andengine
---


# Question
Title: OpenGL ES 2 - Developing snowfall particle system
I've recently begun OpenGL ES 2 and I'm trying to implement a snowfall (on Android), but I'm not sure what's the best approach. I would like to develop it myself rather than use a library. It really helps a lot in understanding OpenGL.

What I'm doing at the moment is: I have an array of, say, 1000 particles, each with its own lifetime (=number of frames it will live). It works fine if a particle "dies" and starts all over when it already left the screen, but if it is still on the screen and it has to die, the user will notice that the particle suddenly disappeared. The problem is very noticeable if this happens very often. I need a way to kill a particle only when it left the screen.

Is there a way to improve my approach or maybe I should change it completely?

# Answer
Not OpenGL ES 2 specific, but here's some general ideas to think about:

Sounds like you want to use your camera's view frustum and the position of the particle (plane \<-\> point distance check) to see if the particle is within the bounds of what the camera can see. Here's a paper that describes how to extract these planes. The idea of how it works may not click the first time, but you'll get the hang of it.

As usual, understanding the graphics pipeline goes a looong way to understanding how to do seemingly difficult things easily.

Consider fading the particles out as well, because you rarely want your particles to abruptly vanish from the air.

Finally, you can use a screen-space animation effect that produces good results. It also means that you don't need to create particles, as it's just pre-made animation. Here's a video example of it.
> 1 votes

# Answer
You can use the screen size and check the Y position of the particles. When the particle's Y position becomes less than a 0.1 (float) for example, in the update method of your particle engine remove it from the array.
> 0 votes

# Answer
To avoid sudden change when particle has to die, you can make an effect that the particle is starting to extinguish when it's for example 90% of it's lifetime passed. You can start making him smaller and smaller until it reduce to very small size (then you can shut him down immediately and the user won't notice it) or increase alpha transparency until it reaches 100%. Then it will disappear smoothly and without sudden changes.
> 0 votes

---
Tags: opengl, particles
---


title: Problem in animating polygon

text:
# Question
Title: Problem in animating polygon
Hi I am trying to move my black colored polygon downward. But As soon as I run my application my polygon gets invisible! I think My logic of move function is wrong. Can anyone help me out in figuring this out as i am a newbie in opengl and c++. This is What I have tried:

```
#include <iostream>
#include <fstream>
#include <string>
#include <glut.h>
#include <math.h>
#include <windows.h>
#include "RGBA2.h"
#include <ctime>

using namespace std;
int screenWidth=640;
int screenHeight=480;

float posx = 0.0f;
float posy = 0.0f;
static float prevtime= 0.0f;
float currtime;

void myDisplay(void)
{
glClearColor(1.0f,1.0f,1.0f,0.0);
glClear(GL_COLOR_BUFFER_BIT);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,11,0,11);

glEnable (GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,11);

//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);

glBegin(GL_POLYGON);

glColor3f(1,1,0);
glTexCoord2f(-1,-1);
glVertex2f(1.0,2.0);
glTexCoord2f(1,-1);
glVertex2f(1.0,10.0);
glTexCoord2f(-1,2);
glVertex2f(10.0,10.0);
glTexCoord2f(1,2);
glVertex2f(10.0,2.0);

glEnd();

glBegin(GL_POLYGON);

glColor3f(0,0,0);
glVertex2f(posx+2.0,posy+6.0);
glVertex2f(posx+2.0,posy+8.0);
glVertex2f(posx+2.5,posy+8.0);
glVertex2f(posx+2.5,posy+6.0);

glEnd();

glFlush();

```

}

```
void move(int t)
{
long ltime;
ltime = time(NULL);
srand(ltime);
//currtime=gettime();

//static float movebearing=0.0f;
float dx=2.0;
float dy= 8.0;
 posy -= dy;
if (posy >= 11-9)
{
    posy= 0.0f;
dy= 0.0;
}

glutTimerFunc(1000,move,1);
glutPostRedisplay();
}

float gettime()
{
static __int64 i64Frequency=0;
static __int64 i64BeginCount=0;
if (i64Frequency==0)
{
    QueryPerformanceFrequency ((LARGE_INTEGER*)&i64Frequency);
    QueryPerformanceCounter ((LARGE_INTEGER*)&i64BeginCount);
}
__int64 i64CurrentCount;
QueryPerformanceCounter ((LARGE_INTEGER*)&i64CurrentCount);
return (float)(i64CurrentCount-i64BeginCount)/i64Frequency;
}

void delay(int ms)
{
prevtime =glutGet (GLUT_ELAPSED_TIME);
currtime=glutGet(GLUT_ELAPSED_TIME);

int diff= currtime -prevtime;
while(diff < ms)
{
    currtime=glutGet(GLUT_ELAPSED_TIME);
    diff=currtime - prevtime;
}
}

RGBApixmap pix[6];

int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);

glutInitWindowSize(screenWidth,screenHeight);
glutInitWindowPosition(20,20);

glutCreateWindow("TEXTURING");

glutDisplayFunc(myDisplay);
glutTimerFunc(1000,move,1);

pix[0].readBMPFile("brick.bmp",1);
pix[0].setTexture(11);

glutMainLoop();

return 0;
}

```

# Answer
Because after first call to Move function, posy is decreased by 8.0 =\> posy = -8.

When you draw your rectangle, you put some coordinates, which also become negative and ywhole polygon is out of window.

BTW: And I totally don't understand your Move function:

* why do you have time functions there?
* why is there this weird "if (posy \>= 11-9)" - when posy becomes 3 or higher, you set it to 0? So if you add dy instead of subtracting, it will be still on one place?
> 1 votes

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


title: Calculating trajectory

text:
# Question
Title: Calculating trajectory
I'm just starting with game development and some physics related to that. Basically I want to calculate a trajectory given an initial velocity and as well as an elevation / angle. So I wrote this code in Java (I left out some class related code and such):

```
int v0 = 30; // m/s
int angle = 60;
double dt = 0.5; // s

double vx = v0 * Math.cos(Math.PI / 180 * angle);
double vy = v0 * Math.sin(Math.PI / 180 * angle);

double posx = 1; // m
double posy = 1;  // m
double time = 0; // s

while(posy > 0)
{
   posx +=  vx * dt;
   posy += vy * dt;
   time += dt;

   // change speed in y
   vy -= 9.82 * dt; // gravity
}

```

This seems to work fine. However, is there a better way to do this? Also, is it possible to scale so that 5 meter (in calculation) corresponds to 1 m for the posx and posy variables?

Thanks in advance!

# Answer
> 2 votes
The equations of motion for a projectile are:

```
x(t) = x0 + v0 * t + 0.5g * t^2

```

where `x0` and `v0` are your initial position and velocity respectively (`[posx, posy]` and `[vx, vy]` in your code), `g` is the gravitational *acceleration* (9.82m/s^2 in your code) and `t` is the time, in seconds.

So, instead of looping, you can find your projectile's position at any time `t`.

When you map from physical space to pixel space, you need a single value that scales meters to pixels. You want 5 meters to be 1 pixel, so simply divide your physical quantities related to position by 5.

---
Tags: java, trajectory
---


title: How to structure the code of a game?

text:
# Question
Title: How to structure the code of a game?
I come from a web development background and want to learn game programming. To bridge the gap, I plan on creating a simple one-on-one fighting game in JavaScript. There’s two fighters on a stage, and the fighters can kick and punch until one’s health is depleted.

I get I would need a game loop that has hit detection and also listens for user input (keyboard), but what I *don’t* get is how to link the different components of a game together. I think these would be called “activities”.

For example, what is the usual programming pattern used to go from a character select screen to the actual match? Or a pause menu? Or when a match ends to replay or go back to the character selection screen? I have a good idea of how to program these separate activities, but linking them together into one, flowing game is where I get lost.

# Answer
> 1 votes
There's a nice series of articles called "How we Built an iOS game on PC" on gamedev. It's about what you might think, but also charts the development of their game from absolute start to finish.

They reference a blog, and specifically two entries, one of which is about the idea of "scenes". A scene is essentially a class that encapsulates the data and game loop relating to a single part of the game, like the character select screen. Or more straightforwardly, in a game with 'levels', there could be a scene for each level. Each class implements the same interface, Load, Unload, Update etc. Then you have a class that manages the current scene, i.e. calling Update once a frame, and switches to a new scene, calling the appropriate methods.

One way to think about the pause menu is as just another element of your GUI. If you manage your GUI and scene separately, you can stop updating the scene (while continuing to draw it if required) and update and draw the menu. The second blog entry referenced is about the "GUI Stack", which I thought was a really elegant way to handle GUI elements, updating, drawing, layering etc.

I quite like both of those concepts, though they may not be appropriate for what you're doing.

The scene concept is used in the Unity engine, and it has its own slightly modified version of JavaScript for a scripting language as well. Could be a starting point, if you want to get a feel for what I'm talking about.

# Answer
> 0 votes
It kinda depends on which programming language you are using for the game you are creating ... but from what you have said you are using javascript and you want to know how to link parts i suggest separating things like char selection,replay in files and then called them up in the main game file which should be heavily separated with comment lines like (make something like start regions and end regions) like this :

```
Main Game File:
//********************************
//some other region ....
code
code
code

//******************************
// start region CharSelection Menu

  start.gamemenu();
  other code...

//endregion

```

At least that what i would do for my own games ...There are other methods and probably if you find some source codes of games written in javascript it will help you find which method would suit you better...

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


title: OpenGL resize problems

text:
# Question
Title: OpenGL resize problems
I'm developing a minesweeper game. I'm having a problem with reshaping(resize) the window. I'm using Ubuntu Linux. Following are the code snippets and the entire code is here:

This is my initializing code that I write at the starting of main()

```
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (400, 300);
glutCreateWindow ("MineSweeper");
glClearColor (1.0, 1.0, 1.0, 0.0);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);

```

This is my display() func that I pass into glutDisplayFunc() which actually draws the grid requires for minesweeper game.

```
glClear (GL_COLOR_BUFFER_BIT);

glColor3f (0.0, 0.0, 0.0);
glLineWidth (3);

float i;
for(i = step; i< 1; i+=step) {
    glBegin(GL_LINES);
        glVertex3f(i,0,0);
        glVertex3f(i,1.0,0);
    glEnd();
    glBegin(GL_LINES);
        glVertex3f(0,i,0);
        glVertex3f(1.0,i,0);
    glEnd();
}

glFlush ();

```

I searched many forum and finally tried this code for reshape() function in the glutReshapeFunc()

```
void reshape (int width, int height) {
   glViewport(0, 0, width, height);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glOrtho(0, width, 0, height, -1.0, 1.0);
   glFlush();
}

```

But it didn't work and the output was a plane window.

# Answer
> 2 votes
```
glViewport(0, 0, width, height); // reset the viewport
glMatrixMode(GL_PROJECTION); // modify the projection matrix
glLoadIdentity();            // load an identity matrix into the projection matrix
glOrtho(0, width, 0, height, -1.0, 1.0); // create new projection matrix

/// Important!!! You need to switch back to the model-view matrix
/// or else your OpenGL calls are modifying the projection matrix!
glMatrixMode(GL_MODELVIEW); // return to the model matrix
glLoadIdentity();           // load an identity matrix into the model-view matrix

// OpenGL has now compensated for the resized window, and is ready to draw again.

```

---
Tags: c++, opengl, glut, minesweeper, window-management
---


# Question
Title: What's so different/complicated/useful about vectors?
Forgive me if this isn't considered a real question, but it is something I am genuinely confused about.

I constantly hear other game developers talk about how using vectors are very useful, but also how everyone is intimidated by vector math and vectors can seem daunting. I have never got around to learning about them.

So, finally I looked Vector on Wikipedia, and I was surprised. Unless I am somehow mistaken, a vector(for sake of simplicity, say it's 2D), is *just an x and y coordinate.* If I have misunderstood, please correct me.

So here is my question: doesn't that mean that any representation of two(or three) dimensional coordinates is a vector? If so, then a vectors and coordinates are the same thing. And it's pretty much impossible to create a game *without* using coordinates, so how are vectors confusing or new to someone who has done any amount of game programming?

This is something I could use some clarification on. Any help is appreciated.

# Answer
Don't let a math major hear you calling Vectors points or coordinates!

A 2D vector has an x and y *component*, not coordinate. Vectors do not define a position, they define a direction and a magnitude.

I can't tell you why people are intimidated by them, likely the same reason people are intimidated by math in general, because everyone says it's hard before they know anything about it!

Vectors and coordinates are not the same thing. They do look similar, but they way they're used is very different.

Coordinates define a position in the world. Vectors define a direction and magnitude. The two of them are often used together. As an example:

A character has a position and a velocity. The position is a coordinate and the velocity is a vector. Adding the velocity to the position will move the character in the direction of the vector at a distance defined by the magnitude of the vector (note that the magnitude of the vector is the speed, so this gives us a direction and a speed).

Or in this example:

The two characters have positions and the laser shot is a vector. A vector between the two positions is (3,1). That means it travels +3 along the X axis and +1 along the Y axis. Where the magnitude can be found with Sqrt((X*X) + (Y*Y)).

A good overview of vector math can be found on the Wolfire blog
> 29 votes

# Answer
I think the intimidation factor may arise when you start dealing with more complicated operations such as normalization, dot and cross products, and using multiple coordinate systems with matrices to transform between them. These are not necessarily easy to understand at first, even if you have a strong geometry and algebra background.

Also, at least in the US, people who have gone through the typical high-school math sequence are accustomed to thinking about geometry in terms of lines, slopes, angles, etc. They have to unlearn that stuff to some extent, and learn to think about it in terms of vectors and matrices instead. It's not that the concepts of linear algebra are such a stretch, but that they are a somewhat different set of concepts than the ones used in classical geometry, which people are likely to have learned in school.

---

BTW, the distinction between vectors and points lies in the operations you can perform on them. Although both are represented (in a particular coordinate system) by a list of components, and therefore look "the same", the operations allowed are not the same. For instance, you can add two vectors, or multiply a vector by a scalar. You can't do that with points - or at least, it doesn't make any sense to do so. But you can subtract two points, and the result is a vector from one point to the other. You can also add a point to a vector to get a new point.

Points and vectors also behave differently with respect to transformations. Namely, points are subject to translation, while vectors are not. Consider the example of an object moving with a position (point) and a velocity (vector); if you translate the object to a different place, you alter its position, but not its velocity.

In fact, furthering this line of reasoning, there are not just vectors; there are other entities like covectors and bivectors, which may also "look like" a vector in terms of having a list of components in a coordinate system, but which behave differently in terms of the operations available and the way they react to transformations. These all belong to a field of math called Grassmann algebra. Beyond that, one can be even more general and consider tensor algebra. This is advanced stuff though.
> 9 votes

# Answer
Vectors really aren't that bad. There is just a bit of math that people are unfamiliar with.

First and foremost, a Vector does not represent a position in space. This is conceptually very important. A vector represents a direction, like 'North', and a magnitude. On a map with normal Math X-Y coordinates, 'North' would be the vector (0,1) (up on the Y Axis). This should not be confused with the position (0,1), which is one unit above wherever you put the origin. *A vector is a direction and a magnitude*.

Displacement (movement) is a vector (like move two units up and one unit Right), Position is not.

Vectors, in and of themselves, are not what people have a problem with. Usually it's matrices and operations on vectors.

For example, if you multiply a Vector by special matrix called a 'Rotation Matrix', then the vector is rotated by the amount specified by the matrix. Additionally, some people have issues with Matrix multiplication. Look it up if you're not familiar with it.

Further, you can 'stack' these matrices (or operations) together. Like Rotate 90 degrees around the X axis, then Rotate 90 degrees around the Y axis. If we call the first one Matrix M and the second one matrix N, then the operation would be v\*M\*N. However, Matrix multiplication isn't commutative, so that is not the same as v\*N\*M.

In Graphics programming, you do considerably more complicated operations on vectors and other matrices regularly. Transformations for FoV and to put your coordinates in screen space, etc. It's really not that bad, but it can be intimidating for new people.
> 7 votes

---
Tags: mathematics, vector, coordinates
---


title: How to use GLX from Java?

text:
# Question
Title: How to use GLX from Java?
I am trying to use Clojure to create an opengl window under Linux. Is there a tutorial on how to use GLX and X Window directly. I'd rather learn how to do this directly, which I already know how under Windows with win32 sdk, instead of relying on a wrapper.

# Answer
> 0 votes
Your best bet is probably to call directly into something like LWJGL. Learning new things is fun! :-)

---
Tags: opengl, java
---


# Question
Title: Pixel Perfect Collision Detection in Cocos2dx
I am trying to port the pixel perfect collision detection in Cocos2d-x the original version was made for Cocos2D and can be found here: http://www.cocos2d-iphone.org/forums/topic/pixel-perfect-collision-detection-using-color-blending/

Here is my code for the Cocos2d-x version

```
bool CollisionDetection::areTheSpritesColliding(cocos2d::CCSprite *spr1, cocos2d::CCSprite *spr2, bool pp, CCRenderTexture* _rt) {
    bool isColliding = false;
    CCRect intersection;
    CCRect r1 = spr1->boundingBox();
    CCRect r2 = spr2->boundingBox();
    intersection = CCRectMake(fmax(r1.getMinX(),r2.getMinX()), fmax( r1.getMinY(), r2.getMinY()) ,0,0);
    intersection.size.width = fmin(r1.getMaxX(), r2.getMaxX() - intersection.getMinX());
    intersection.size.height = fmin(r1.getMaxY(), r2.getMaxY() - intersection.getMinY());

    // Look for simple bounding box collision
    if ( (intersection.size.width>0) && (intersection.size.height>0) ) {
        // If we're not checking for pixel perfect collisions, return true
        if (!pp) {
            return true;
        }

        unsigned int x = intersection.origin.x;
        unsigned int y = intersection.origin.y;
        unsigned int w = intersection.size.width;
        unsigned int h = intersection.size.height;
        unsigned int numPixels = w * h;
        //CCLog("Intersection X and Y %d, %d", x, y);
        //CCLog("Number of pixels %d", numPixels);

        // Draw into the RenderTexture
        _rt->beginWithClear( 0, 0, 0, 0);

        // Render both sprites: first one in RED and second one in GREEN
        glColorMask(1, 0, 0, 1);
        spr1->visit();
        glColorMask(0, 1, 0, 1);
        spr2->visit();
        glColorMask(1, 1, 1, 1);

        // Get color values of intersection area
        ccColor4B *buffer = (ccColor4B *)malloc( sizeof(ccColor4B) * numPixels );
        glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

        _rt->end();

        // Read buffer
        unsigned int step = 1;
        for(unsigned int i=0; i 0 && color.g > 0) {
                isColliding = true;
                break;
            }
        }

        // Free buffer memory
        free(buffer);
    }

    return isColliding;
}

```

My code is working perfectly if I send the "pp" parameter as false. That is if I do only a bounding box collision but I am not able to get it working correctly for the case when I need Pixel Perfect collision. I think the opengl masking code is not working as I intended.

Here is the code for "\_rt"

```
_rt = CCRenderTexture::create(visibleSize.width, visibleSize.height);
_rt->setPosition(ccp(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * 0.5f));
this->addChild(_rt, 1000000);
_rt->setVisible(true); //For testing

```

I think I am making a mistake with the implementation of this CCRenderTexture

Can anyone guide me with what I am doing wrong ?

Thank you for your time :)

# Answer
> 1 votes
Solved the problem finally.

Had to use custom openGL shaders for coloring one of the objects completely RED and the other completely BLUE and then looping through all the pixel data collected using glReadPixels to find if a pixel has both RED and BLUE colors.

In depth information and source code can be found in my blog post - http://blog.muditjaju.infiniteeurekas.in/?p=1

---
Tags: c++, collision-detection, cocos2d-iphone, cocos2d, cocos2d-x
---


title: What is a collision shape?

text:
# Question
Title: What is a collision shape?
I am a business developer who is new to game programming. In learning Stencyl, I see that there are things called collision shapes associated with tiles. This seems to be a standard term in game programming. What is a collision shape?

# Answer
A collision shape is the shape of an object as "seen" by the collision/physics engine.

Think of a square box and a circle:

Near the corners, objects will hit or collide with the box but not the circle even though the height and width of the objects are identical.

More complex shapes as also possible. Circles/spheres are the simplest (and fastest) but tend to poorly represent many kinds of objects. Axis-aligned bounding boxes (AABBs) are the next most common/efficient. Capsules (a cylinder with half-spheres on each end) are common for characters. The common collision algorithms all support convex hulls (a polygon/polyhedron with only convex angles), and decent physics engines are typically capable of dealing with objects which have multiple shapes (allowing for objects to incorporate shapes with concave features, even though the collision engines typically can't handle them directly).

Tiles will typically be a simple square AABB fixed to a grid. Specialized collision engines may have direct support for tiles, since a grid-aligned fixed-width AABB is even easier to deal with than arbitrarily positioned/sized AABBs.
> 6 votes

---
Tags: physics
---


# Question
Title: Project location to perspective fake 3D view
I am trying to implement a perspective view in a 2D soccer game, such like Nintendo World Cup. In this case, the soccer pitch will look like a isosceles trapezoid, but not a rectangle in real.

Here is my solution:

1. I separate the game logic location and the final rendering location. In the game logic part, the pitch is still a rectangle, so we can make easy collision detection, player area change, out-of-bound checks, goal check, etc.. Just like an answer to Stack Overflow question *Implement a projectile motion and collision detection - response in a 2D top-down game* said:
2. Then I just project players', ball's location into final screen location, so that player can fit in pitch (because the exact pitch image is a trapezoid like the screenshot)

I tried to do like that post said, but the result is wired, so I am thinking do I need to make a perspective projection like in a 3D game, but I do not know how. A 3D perspective projection needs to know the camera position, camera angle, near plane, but these do not exist in a 2D game.

How do I solve this problem?

# Answer
> 2 votes
The 2D coordinate system that describes your field can be parameterized the same way as your trapezoid.

Think about it this way... First let's label the corners of the field in the unprojected space:

* **TR**: top-right
* **BR**: bottom-right
* **TL**: top-left
* **BL**: bottom-left

Each of these corners has an `x` and `y` value, with **`BL`**`== (0, 0)` most likely. A good sanity check is to make sure that

```
TR.x - TL.x == BR.x - BR.y
TR.y - BR.y == TL.y - BR.y

```

In order to take some coordinate `(x, y)` from the unprojected field into the projected field, the easiest way to do this is to first figure out how far away from the bottom left corner of the field it is. In other words, we would like to find `(t.x, t.y)` such that

```
x == t.x + BL.x
y == t.y + BL.y

```

Ok, once we've figured out our vector `t = (t.x, t.y)` we can write them in the coordinate space of the rectangle itself. In other words imagine that **BL** is at the origin `(0, 0)`, and **TR** is at the point `(1, 1)`, then both t.x and t.y are somewhere in that square and belong to the interval \[0, 1\]. We can use a simple trick to transform our coordinates into this space:

```
tr.x = (t.x - BL.x) / (BR.x - BL.x)
tr.y = (t.y - BL.y) / (TL.y - BL.y)

```

Now, both `tr.x` and `tr.y` should be between `0` and `1`. We call `tr` the parametric representation of the point `(x, y)` in the space of the rectangle, or unprojected soccer field, in this case. We know exactly where any point `(x, y)` is by using two coordinates between `0` and `1`.

I still haven't mentioned how to go to the projected space. Once you have your parameterization, going to any shape that has four corners is easy. You have to map the four corners of your new shape to the four corners of your old shape. In this case, you have the parameterization for your old shape, so you simply need to remap it to the new projected trapezoid.

Let's say that your trapezoid has corners labeled:

* **tTR**: trapezoid top-right
* **tBR**: trapezoid bottom-right
* **tTL**: trapezoid top-left
* **tBL**: trapezoid bottom-left

In order to retrieve the projected coordinate of `(x, y)`, you can simply bilinearly interpolate between each of the corners of the trapezoid:

```
bottom = (tBL)*(1 - tr.x) + (tBR)*tr.x
top = (tTL)*(1 - tr.x) + (tTR)*tr.x
final = bottom*(1 - tr.y) + top*tr.y

```

`final` should be a 2D coordinate within the trapezoid that corresponds to the same point in your logical field.

---
Tags: 2d, cocos2d-x, projection
---


# Question
Title: How is scripting done in games such as Zelda?
How do games implement their triggers and events that make up the plot of the story. For example, to be concrete how would one implement the story of a game such as The Legend of Zelda: A Link to the Past. I'm assuming there is some kind of scripting that somehow hooks into the game world state? I know absolutely nothing about scripting and game development. And have no clue how the underlying code would be architected in terms of classes, data structures, design patterns, etc.

# Answer
In the simplest terms i can put it.

* There will be some kind of "trigger" volume in most cases. When the player steps into this volume it will trigger the "event".
* Volumes will be a cube, or a sphere, or some other 3D primitive.
* The script will either be a pre-animated cutscene, in which case an animation will be played, or the gameplay script will be some kind of finite state machine (FSM).
* Different "states" will be triggered upon in game events, such as retrieving an item, or beating a boss.
* The mission will be "over" when the final state is run, this will usually update the players profile to say that a particular mission has been complete. And most likely cause the next FSM to be loaded.

The FSM may be defined like

1. Get Object A
2. Get Object B
3. Get Object C
4. Play cutscene putting triforce together
5. Boss defeated
6. Play cutscene
7. Load next "mission".

Each "state" within a FSM may contain its *own* FSM. All of this can be defined with data, and doesnt necessarily require its own scripting language.
> 6 votes

# Answer
I want to add some more information to what Matt already mentioned by explaining how the RPG Maker does specific story progression and states. Though one can implement a more complex system the simplified way how the RPG Maker does it should be a good start.

In maps we can find certain triggers or entities. That can be an invisible tile which executes some code when the player steps on it or just a NPC you can talk to. Each one has different properties and provides different ways to interact with. Assume we have a NPC who would send you give you a quest - the first time you talk to him he would say something different than later on. Using pages for entities one can write code for different situations which is only executed under certain conditions. The RPG Maker uses so called switches - just boolean variables which are either on or off. At the beginning of the game a switch `HasAcquiredQuestX` might be `off` and the NPCs page 1 (giving the player the quest and turning on `HasAcquiredQuestX`) would be executed. Speaking to him now would maybe execute page 2 with some text like "Oh did you finish your quest yet?". Once you finish the quest another trigger might turn on a switch `HasFinishedQuestX` which lets our aforementioned NPC execute page 3 which will reward you with glory, gold and items.

This is a very easy way to work with story progression, however the more content the game has the more switches you will have and at a certain point it is definitely better to consider using finite state machines!
> 0 votes

---
Tags: scripting
---


# Question
Title: Can I use jMonkeyEngine to make a closed source game?
Can I just share the jMonkeyEngine code and keep my code closed or would I have to make my game open as well? Sorry if this is a noob question.

# Answer
> 5 votes
As per the about page: http://hub.jmonkeyengine.org/introduction/

"Free, open-source software (under the New BSD license) – Use our free engine for commercial, educational, or hobby game development"

BSD license allows for closed source commercial development of work based on that software. So yes, your game can be closed source.

---
Tags: jmonkeyengine
---


# Question
Title: Render white background with Graphics in Canvas
I am developing a game that I would like the background to be white, and it just sticks to being black. Here is my render method:

```
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

...

private void render() {
    BufferStrategy bs = getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }
    screen.clear();
    screen.render();

    for (int i = 0; i < pixels.length; i++) {
        pixels[i] = screen.pixels[i];
    }

    Graphics g = bs.getDrawGraphics();
    g.setColor(Color.white);
    g.fillRect(0, 0, getWidth(), getHeight());
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);

    g.dispose();
    bs.show();
}

```

I set the graphics color to be white, which I thought that is what got it to render for the background color, but it seems not to be the problem.

I can get the screen to be white until I use `g.drawImage(image, 0, 0, getWidth(), getHeight(), null)`, then the background turns black. There was one method in which it had the option to pick a color for it, but it didn't work. How would I get the background to be white and not black while still being able to use `drawImage`?

# Answer
I figured it out;

For my `BufferedImage`, I used `TYPE_INT_RGB`, when I needed to use `TYPE_INT_ARGB`.
> 0 votes

---
Tags: java, 2d, graphics
---


title: Making a 2D TMX tile map

text:
# Question
Title: Making a 2D TMX tile map
Should there be a specific link between the characters height as well as the tile size for the tile maps? That is if a tile is 32x32 does that mean that a character sprite has to be the same size? Also does the size of tiles I use have any great impact on the game itself?

# Answer
Your characters do not have to be the same size as the tiles, but you need to keep in mind that they need to align on the same axis. For example, if you make your sprite 64x64 then you need to align them between two tiles rather than one. It's all about how you want to design your tile system. My way is not the only way about doing it as well, others may prefer to keep their characters aligned a completely different way. My way is just an example about how you can go about doing it. Also, sprites being the same size as your tile size makes it easier to program, and you don't have to worry about your sprite being mutilated by tiles that render above the character.

The size of tiles is mostly based on preference of what you want the game to feel like, but it does also affect the performance of the game you are making. The bigger the tiles are, the more the below items are increased.

1. Memory required.
2. Slower performance.
3. Work.

The smaller the tiles you use, the slower the game will be. You need to find a suitable size for your tiles, that gives you the flexibility you want while keeping the game running good.
> 2 votes

---
Tags: 2d, box2d, tiles, andengine, tilemap
---


title: Representing a world in memory

text:
# Question
Title: Representing a world in memory
I'm attempting to write a chunk based map system for a game, where as the player moves around chunks are loaded/unloaded, so that the program doesn't run out of memory by having the whole map in memory.

I have this part mostly working, however I've hit a wall regarding how to represent the contents of each chunk in memory because of my so far limited understanding of OOP languages.

The design I have currently has a `ChunkManager` class that uses a .NET `List` type to store instances of `Chunk` classes. The "chunks" consist of "blocks". It's similar to a Minecraft style game.

Inside the `Chunk` classes, I have some information such as the chunk's X/Y coordinate etc, and I also have a three dimensional array of `Block` objects. (Three dimensional because I need XYZ values)

Here's the problem:

The `Block` class has some basic properties, and I had planned on making different types of blocks inherit from this "base" class. So for example, I would have "StoneBlock", "WaterBlock" etc.

So because I have blocks of many different types, I don't know how I would create an array with different object types in each cell.

This is how I currently have the three dimensional array declared in my `Chunk` class:

```
private Block[][][] ArrayOfBlocks;

```

But obviously this will only accept Block objects, not any of the other classes that inherit from Block.

How would I go about creating this? Or am I doing it completely wrong and there's a better way?

# Answer
The problem you're asking about is a non-problem, but the structure you've come up with is very inefficient.

Consider a simple 128x128x128 chunk. That will require 2097152 instances of `Block`. You want `Block` to be as small as possible. One thing that is easy to get rid of is the position. The position is implicit in the array containing the `Block` instance. Nobody can retrieve the block without knowing its position. Hence, the position field of `Block` is redundant and can be removed.

Another thing you want is to keep the structure fast. That's a lot of blocks per chunk you'll be working with for rendering, physics, gameplay, etc. One of the simplest things to keep in mind when working with performance is the CPU cache and memory accesses. Accessing random locations in memory is not free; they usually incur a pipeline stall in the CPU that can be quite a heavy hit on modern CPUs. The easiest way to combat this is to keep all your data *contiguous* in memory. Thankfully, this is what a `List` or arrays do already. However, if you have a `List` or array of *classes*, the data structure is technically only keeping *references* to the objects in its contiguous memory. The actual objects themselves could be strewn all over the place. C# was well-designed and includes the idea of a *struct* as an alternative to a *class* (unlike Java; Minecraft has to jump through more hoops to keep things contiguous in memory). Converting `Block` to a struct will make accessing them faster. However, structs will actually cause the inheritance problem you were originally worried about, since a `List<Block>` (where `Block` is a struct) actually wouldn't be able to hold subclasses.

The final trick then is to simply not use classes and inheritance where they aren't needed, and this is one such place. In general, inheritance is a very, very poor tool for such problems. Use inheritance when you want to model *is-a* relationships, keeping in mind how a computer works/things - the computer has no reason to care that a stone block is a type of block. That's a human taxonomy problem. The computer only cares whether a stone block exposes the behavior of a block. That is, inheritance to a computer is mostly valuable only when you're modeling *interfaces* and *behaviors*.

Furthermore, inheritance starts to cause some serious issues. Say you have an ice block that has sliding behavior and a puzzle block that can be pushed and then want to add an ice puzzle block. Does it inherit from `PuzzleBlock` or `IceBlock`? Do you move all the common functionality up into `Block` and make every single block pay the price for the excess bloat? The concept of *aggregation* solves this nicely. You can make an `IceBlockComponent` and a `PuzzleBlockComponent` and now an individual `BlockType` can contain a list of these components, allowing you to mix-and-match behaviors however you want.

Alternatively, if you don't feel you need the full flexibility (and resulting complexity) of component-based design, move your inheritance structure out of `Block` and into a `BlockType` hierarchy. So you'd have a `BlockTypeStone` or `BlockTypeIce` and still only a single `Block`.

Going back to the data-structure problem, not that each `Block` does not need to contain all the behavior and methods of its type. In such a system, it needs only point back to its `BlockType`. This can be done efficiently by storing all the `BlockTypes` in an array or `List` and then storing a small integer (say a `byte` or a `short`) in the `Block` object. Now you no longer have any need for inheritance in `Block` and you've reduced the size from before (no need for 4-8 byte references in your `Chunk` array of blocks but rather a compact struct containing a small integer... or just the integer itself with no struct!).

The remaining hassle then is data. Thankfully, most data in these games are going to be per type rather than per block instance. That is, your `IceBlockComponent` may have a `slipperiness` attribute which would apply to all blocks of that type. There's no need to store the value on each individual block.

For the few bits of data you do need per block, just use a few bits (or a couple bytes). If your `Block` is just an 8-bit index to a `BlockType`, you could toss in another 8 or 16 bits and still have `Block` stay relatively small and compact. These extra bits of data would be interpreted as needed by the block type (managing the meaning of the bits in a component/aggregation model is a little tricky, but doable).

The end result of all these is that you've got a very compact `Chunk` that uses much less memory and is much faster to process than what you had before. You've also simplified your use of the type system and (if you play your cards right) made the game easier to mod and extend in the future.
> 5 votes

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


title: How to clip textures when drawing?

text:
# Question
Title: How to clip textures when drawing?
How do i draw a texture2D in a specific area (rectangle) where the texture is bigger than the rectangle, and i dont want to draw outside the rectangle. So that means i want to cut the texture so it fits the rectangle area (if its too big).

For example if the rectangle area is 200 x 100 and my texture (the smiley) is 200 x 150 then i want to cut the last 50 off so it only draws 200 x 100

# Answer
> 1 votes
You can use `SpriteBatch.Draw(Texture2D, Rectangle, Nullable<Rectangle>, Color)`

```
public void Draw (
         Texture2D texture,
         Rectangle destinationRectangle,
         Nullable<Rectangle> sourceRectangle,
         Color color
)

```

compare the size of the `destinationRectangle` and the size of the `texture`. Next you need to take the lowest values and using them in `sourceRectangle`

---
Tags: xna
---


title: Hardware instancing for voxel engine

text:
# Question
Title: Hardware instancing for voxel engine
i just did the tutorial on Hardware Instancing from this source: http://www.float4x4.net/index.php/2011/07/hardware-instancing-for-pc-in-xna-4-with-textures/. Somewhere between 900.000 and 1.000.000 draw calls for the cube i get this error "XNA Framework HiDef profile supports a maximum VertexBuffer size of 67108863." while still running smoothly on 900k. That is slightly less then 100x100x100 which are a exactly a million.

Now i have seen voxel engines with very "tiny" voxels, you easily get to 1.000.000 cubes in view with rough terrain and a decent far plane. Obviously i can optimize a lot in the geometry buffer method, like rendering only visible faces of a cube or using larger faces covering multiple cubes if the area is flat. But is a vertex buffer of roughly 67mb the max i can work with or can i create multiple?

# Answer
> 1 votes
If all else fails you can do multiple render passes, with voxels I suppose splitting the screen into squares and rendering each of those separately will work reasonably.

Also, please consider what you are trying to achieve. Voxel engines are mostly unsuitable for games, they are hard to work with and hard to get good performance from.

If you want to make a game, stay away from voxels. If you want to play around with voxels that is fine, but don't expect to make anything better than some silly tech demo.

---
Tags: xna, voxels, instancing
---


# Question
Title: Should I share classes on the server with the client?
I am fortunate being able to use the same programming language on both the server and client (javascript). I would therefore like to share my code and classes between server and client, like Half-Life (and possibly others) did.

To make things simple, suppose I have an MMO with a Player and an Enemy class, with a position, velocity, and health.

```
var Player = function() {
    this.health = 100;
    this.x = 0;
    this.y = 0;
}

var Enemy = function() {
    this.health = 100;
    this.x = 0;
    this.y = 0;
}

```

I know ideally these should inherit from each other (or use a CES system). But my question is as follows:

Since these classes will be used on the client and server (since both client and server needs to know about these entities) with some but not all shared logic, would it not be crazy to define two separate classes on both the server and client?

What are the advantages and disadvantages of sharing classes between server and client?

Are there any helpful websites with tips/tricks for this approach?

# Answer
The answer is that it varies. A lot of the foundational code, messages and protocol handling and so on, can absolutely be shared.

At the game-object layer, it's often more advantageous to have separate client and server implementations. In a class-based system, it may make sense to have a common shared base class for each entity or component.

The advantages are that there is less code and ensuring common functionality (like replicated attributes and method calls) are hooked up is easier. The disadvantages are that little of the code will be common for most classes and you're leaking server-side implementation details (which may be relevant either to security or to cheat prevention) to the clients.

I've found it handy to support both, at least when using component-based game objects. Some components have no need of client- or server-specific logic. Some need heavy customization. Some differ only in their data or which messages they emit or receive.

Of further note for a component-based design is that some components are client- or server-only. Almost all of the graphics components, for instance, have no need to be loaded on the server. Likewise, many of the gameplay components have zero reason to exist on the client (assuming you're going for a client-server architecture and not a peer-to-peer setup). Physics or certain gameplay bits are needed on both ends, particularly if you have any kind of client-side prediction for lag-compensation going on.
> 2 votes

---
Tags: server, client
---


# Question
Title: Best way to play footstep-sounds of character?
I am developing an XNA-Game, which is pretty much a runner game (side-scrolling).

Now I am in the middle of adding sounds to my game. And as it turns out, I am having quite some problems with the footstep-playback.

The following is in C#, but I am quite sure that anyone will understand it:

```
 public static void StartStepTimer()
 {
     _stepTimer = new DispatcherTimer();
     _stepTimer.Interval += TimeSpan.FromMilliseconds(500);
     _stepTimer.Tick += _stepTimer_Tick;
     _stepTimer.Start();

     _step = _content.Load<SoundEffect>("Sound\\World\\Summer_1");
     _stepInstance = _step.CreateInstance();
     _stepInstance.Volume = 0.4f;

 }

  private static void _stepTimer_Tick(object sender, EventArgs e)
  {
      _stepInstance.Play();
  }

```

As you can see, I am playing the footstep based on a timer. I am using this method, since the gamespeed gets higher during gametime (I can change the interval in that case).

But this method isn't really working. The playback lags. I thought of making a prerendered 10s soundfile and looping that in gametime, but than the playback won't fit when the gamespeed rises.

Any suggestions?

# Answer
The reason your sound is lagging is because you're using a timer event. Which are imprecise as they will only update when the CPU feels like it (just like when yielding threads). The correct way to do it is by calculating how much time passes each frame and then firing the sound at the frame the foot hits the ground (or maybe a few frames before it if you still have issues).

A piece of advice. In a game the game-loop is the artery of everything time related. Try to steer away from timers and the likes as they interfere with the linearity of your game loop as you never know exactly where you will be in code when the main thread is halted to execute the timer code. Another advantage of using the game loop for everything is that you can easily speed-up and slow-down time and everything will react to it.
> 5 votes

# Answer
May not be the best solution, but I'll throw an idea below:

You can play the footstep sound at a specific animation frame. In my game I did it indirectly.

For example, when the player is walking, it can have 6 states (walking1, walking2, ... walking6). Every state is mapped to a particular sprite. The states changes over time, in order. So, when the character changes from state "walking1" to "walking2", it will change its sprite and also play a footstep sound. Then it will cycle through everything and repeat.
> 1 votes

---
Tags: c#
---


# Question
Title: How is the result returned in SharpDX.DirectInput.Device.Acquire()?
The documentation of `IDirectInputDevice8::Acquire` says:

> Return Value
>
> If the method succeeds, the return value is `DI_OK`, or `S_FALSE` if the device was already acquired. If the method fails, the return value can be one of the following error values: `DIERR_INVALIDPARAM`, `DIERR_NOTINITIALIZED`, `DIERR_OTHERAPPHASPRIO`.

However, SharpDX's `Device.Acquire()` is a `void`. The documentation for this method is not really helpful.

How can I know if a call to `Device.Aquire()` has succeeded or not?

Alternatively, where is the source for `Acquire()` located? I've tried looking at the contents of `Device.cs`, but not only it is not located in there, but `Device` is marked as `partial`, which means the source for `Acquire()` is probably in a different file, but I can't seem to find it.

# Answer
> 1 votes
I believe the correct way to use the Acquire method is to assume it has worked correctly - if it fails to acquire the device, a SharpDXException will be thrown from the Acquire method. In this way, there is no need for a return value.

A disassembly of the Acquire method shows the code as:

```
public unsafe void Acquire()
{
  // ISSUE: cast to a function pointer type
  // ISSUE: function pointer call
  (Result) (__calli((__FnPtr<int (void*)>) *(IntPtr*) (*(IntPtr*) this._nativePointer + IntPtr(7) * sizeof (void*)))(this._nativePointer)).CheckError();
}

```

The CheckError call is a method on the Result struct, which looks like this:

```
/// <summary>
/// Checks the error.
/// </summary>
public void CheckError()
{
    if (_code < 0)
    {
        throw new SharpDXException(this);
    }
}

```

(Source from https://github.com/sharpdx/SharpDX/blob/b1596ddd38a5de77704412910a4fb265a4ab8525/Source/SharpDX/Result.cs)

# Answer
> 0 votes
I suppose you could invoke `GetLastError()`. but depending on how your program is structured it might contain a stale value (for example, if an earlier call failed and `Acquire()` succeeded but did not clear the error code) and it might not be accurate depending on how that SharpDX function is written.

You could work around the "stale" issue by invoking `SetLastError()` to prime (clear) the error code before invoking SharpDX.

---
Tags: sharpdx, directinput
---


# Question
Title: Is there a way to create multi-resolution graphics for game with createjs?
I'm on a advanced development for a game made with createjs framework. However it's time to export it to some platforms. The graphics are made for the iPad 3 resolution.

I would like to export them to devices with less processing power, like iPhone 4 or low end Androids. But hi-definition assets drains the little processor of them.

Resizing all the files is not a solution. There must be some "scale factor" on image loader or another mechanism to get images in correct sizes.

If my game canvas has virtual 1000px wide, and my asset has 1000px wide, the canvas will be filled by the asset. If I resize it to half size, it will be 500px wide, and the canvas will be just half filled. There should be a scale factor that should get the `displayObject` (not the asset) and set its `sizeX` and `sizeY` to double size to fill the screen again. I can be done manually for every one, but I'm looking for a better solution.

# Answer
> 2 votes
Resize all files is a solution. It is *the* solution.

You really should have an asset conditioning pipeline that can take your source assets and convert them into the appropriate size/format for shipping. This might include converting the textures to compress formats (the supported set of which can differ between iOS, various Android device, WP8, PC, etc.), resizing images, and possibly other things. You'll want the same for audio files and meshes if you have any.

You *could* resize the files on load, but this is a very poor solution. Loading the larger images and processing them takes time (for that poor little ol' CPU you're worried about), plus the user still has to download the high-res game on their older device. If you're deadset on this approach, though, maybe try the technique at https://stackoverflow.com/questions/2303690/resizing-an-image-in-an-html5-canvas, which involves rendering the image in a smaller resolution to a `Canvas` and then reading the result back as an `Image`.

# Answer
> 0 votes
Option 1: Detect media screen size, and load appropriate scaled-down bitmaps. Scale the images down using automated tools like ImageMagick.

Option 2: Render vector imagery instead of raster bitmaps.

# Answer
> 0 votes
A way to your solution is to decouplate your images from their resolutions.
So you need to define the virtual size of each image.
You can define a class that will take filePath, virtualWidth, virtualHeight as arguments, as well as a draw method that take care of the scaling.
The virtual Width and Height are just the w/h of the images you have running right now.

That way when you load an image, whatever its resolution you'll be able to compute the scale to apply to it, and draw it with a correct size.
As a bonus you can even mix low-res/high res images depending on how important -or big- is the graphical object. (i did just that for a game i made and it worked fine).

---
Tags: html5, html-canvas, assets, scale
---


title: Implementing Explosions

text:
# Question
Title: Implementing Explosions
I want to add explosions to my 2D game, but im having a hard time with the architecture. Several game elements might be responsible for explosions, like, lets say, explosive barrels and bullets (and there might be chain reactions with close barrels). The only options i can come up with are:

1 - Having an array of explosions and treat them as a game element as important as any other

Pros: Having a single array which is updated and drawn with all the other game element arrays makes it more organized and simple to update, and the explosive barrels at a first glance would be easy to create, simply by passing the explosion array as a pointer to each explosive barrel constructor

Cons: It might be hard for the bullets to add an explosion to the vector, since bullets are shot by a Weapon class which is located in every mob, so lets say, if i create a new enemy and add it to the enemy array, that enemy will have a weapon and functions to be able to use it, and if i want the weapon (rocket launcher in this case) to have access to the explosions array to be able to add a new one, id have to pass the explosion array as a pointer to the enemy, which would then pass it to the weapon, which would pass it to the bullets (ugly chain). Another problem I can think of is a little more weird: If im checking the collisions between explosions and barrels (so i create a chain reaction) and i detect an explosion colliding with a barrel, if i add a new explosion while im iterating the explosions java will trow an exception. So this is kinda annoying, i cant iterate through the explosions and add a new explosion, i must do it in another way...

The other way which isnt really well thought yet is to just add an explosive component to every element that might explode so that when it dies, it explodes or something, but i dont have good ways on implementing this theory either

Honestly i dont like either the solutions so id like to know how is it usually done by actual game developers, sorry if my problem seems trivial and dumb.

# Answer
> 1 votes
As far as keeping track of your explosions, a large array is probably great for prototyping something small, but as you're discovering, it doesn't scale well and passing it around can get ugly. Here are a couple of solutions:

1. Implement an `ExplosionManager`. Pros: No need to pass around a reference to your explosions array. Easy to group updates of elements it's responsible for. Cons: High coupling between it and the sections of codes that utilize it. Still a rather specific reference to a game element (which brings me to suggestion two...)
2. Implement a proper scene graph. This is most definitely a larger undertaking than option one. In the case of an explosion, when something in the game creates one, the explosion is parented to it in the graph, automatically allowing it to be rendered. Pros: Explosions (and all other game elements) can be treated generically (think `GameObject` from Unity). Lower coupling than option one. Cons: Significant amount of work. Sometimes not efficient to scatter updates of like-objects.

As far as creating chain reactions, you could have an explosion query objects in the game environment which are a certain distance away, and communicate to them that there is an explosion happening nearby. The objects react accordingly.

MarkR already provided a good answer for your issues with modifying a list while operating on it. My only suggestion on top of this is to copy the list before operating on it and operate on the copy. It can be a little less confusing than working with 'new' and 'dead' object arrays.

**Update**: An `ExplosionManager` would be implemented as a singleton with global access. My Java is rusty, but the resulting code would look something like:

```
ExplosionManager.addExplosion(new Explosion());

```

Somewhere in your game's main update loop you have:

```
ExplosionManager.update(deltaTime);

```

The class' responsibility is to oversee the existence of every explosion in your game. It holds onto them for their lifetimes, and updates them. Example code and an explanation of the singleton pattern can be found here.

As far as the scene graph is concerned, yes, it's a lot. It comes down to how much of an investment you want to make. If your game is very small and there are no plans to branch it into another project, you don't really need a scene graph. If the game is going to become large though, or you plan on making other games from the architecture of this one, then a scene graph might be a good investment. I could end up writing a lot about scene graphs, so for more information I'll refer you to the Wikipedia page.

# Answer
> 0 votes
You can use polymorphism to store a "big list of objects". In Java I would normally use an ArrayList for this (although I haven't written any Java for 7 years or something).

So you store an arraylist of objects of your base "game object" class (I normally call mine GameObject, how dull!).

Then you can iterate it and do whatever operations are done on a thing (defined in the base class, can have default implementations which are overridden). So if there is a base class method reactToNearbyExplosion(MyVectorType where) then you can call that on every nearby object, if it ignores it, that's fine.

To avoid the problem of adding to the list while iterating it (the same applies in other languages not just Java), I would normally use another list, "newObjects".

So suppose I have a class ThingManager, and an instance of this keeps track of all my GameObjects, it would have three ArrayLists, which could be called currentThings, newThings and deadThings.

"newThings" are things which are being added in the current frame, and will be moved to currentThings at the end of other processing.

"deadThings" are things which have died recently and not been cleaned up yet (this is sometimes important, particularly in languages which don't have weak references)

I normally implement a method (property?) on my GameObject, "dead" which returns true when it's time for the object to "go away" i.e. be deleted from the game and stop being used for anything. This can be read by the manager to remove it from the currentThings list, but also any other object which wants to know whether something else is dead.

Apologies for the rather extensive rant, but that's how I handle it.

---
Tags: java, architecture
---


# Question
Title: How do I make a Box2D object that makes objects passing through it slower?
I wish to have a sort of "slow motion" or "slow down" effect on a players character when they walk in a mud area, usually the character velocity is `3f` constant in any one direction. The problem is I tried to declare a rectangle to cover the object mud area but I am only able to get a solid rectangle area and therefore the character cannot walk through or over this area, the desired action would be having the character movement slow down while walking in the mud area. The code below is what I have tried to make this sort of region, but this code only makes a solid object which the character cannot pass through.

```
 final Rectangle rect = new Rectangle( object.getX(), object.getY(), object.getWidth(), object.getHeight(), vbom );

 final FixtureDef fixDef = PhysicsFactory.createFixtureDef( 0.0f, 0.0f, 1.0f );
 Body body = PhysicsFactory.createBoxBody( physicsWorld, rect, BodyDef.BodyType.KinematicBody, fixDef );
 body.setUserData( typeOfObject );
 physicsWorld.registerPhysicsConnector( new PhysicsConnector( rect, body ) );

```

# Answer
> 4 votes
If I understand your problem correctly, you are trying to create an area that can detect the player is in contact, but without preventing the player from walking in it.

In Box2D, what you want is called a `Sensor`. A `Fixture` is a physics object which will actually cause collisions with other physics objects, thereby preventing them from intersecting an area. A `Sensor` does not cause these collisions, but does generate `BeginContact` and `EndContact` events, which you can use to track whether your player is in the mud. Here's some more info. A `Fixture` is turned into a `Sensor` but setting the `isSensor` property on the `Fixture`.

On contact with your mud sensor you can set a modifier on the player's velocity, such as multiplying it by 0.4. Or, if you'd like the player's animation to slow down as well, you could use a modifier on the deltatime the player receives, causing him to literally operate in slow motion.

# Answer
> 0 votes
Ah concepts of time.

What you usually have is a concept of "real time" and "game time"

* "Real Time" is actual physical time. its the time we experience here in the real world. This is useful for things which always animate at the same frequency/velocity regardless of game time. Eg: UI components.
* "Game Time" is the time that has elapsed in the game. We can speed this up, and slow this down as needed. We typically animate and simulate using "Game Time".

So, for slow motion we simply reduce the rate of "Game Time" updates relative to "Real Time". eg: we increase "Game Time" at half the rate of "Real Time" to get a 50% slow down. We can also do the opposite, and run "Game Time" faster than "Real Time" to get a fast forward effect.

This is why there's usually two concepts of "Time" within a game engine.

As per your question. Its important to know whether the game is networked or not, as if the game is networked you need to keep "Time" synchronized between all clients (including both concepts of game, and real time).

For slowing things down within a field, you could use a temporary modifier to "Game Time", however this may cause fun deterministic issues if your game is networked. You may need to confirm the position of objects as they enter the field, and the position of objects as they leave the field to ensure consistency across clients. Lockstep engines will be pretty much fine, but ones that do clientside prediction will have issues with entering/leaving the field and subsequent deterministic calculations of position.

---
Tags: android, box2d, andengine, tilemap
---


# Question
Title: Touch Coordinate in onManageUpdate method
I want to get touch coordinate in onManageUpdate() method. So how to perform that one?

Because onSceneTouchEvent method simulation is some what slow so I could not able to get each coordinate in move event. So to achieve each coordinate in move event I want this functionality.

So someone please help me in this.

# Answer
This is not possible, because these events happen in different threads. You would have to rewrite the Engine itself. But AndEngine pauses the UIThread for a specific time after each event and that might be causing your problem. Try setting the interval:

```
    engineOptions.getTouchOptions().setTouchEventIntervalMilliseconds(faster);

```

The default value is 20.
> 0 votes

# Answer
If you want to get very fine distance coordinates points then you should use DDA Line algorithm to get all point between two touch points. It will give you very short distance coordinates points (depends on you ), though you get two consecutive points at far distance (No matter).
> 0 votes

---
Tags: andengine
---


title: Teamviewer doesn't show my game screen

text:
# Question
Title: Teamviewer doesn't show my game screen
I've been building a 3D engine from scratch using C# and I've tried to show the result to a friend of mine using Teamviewer. When my demo game starts he doesn't see it. He can only see the last active program on my screen (for example visual studio from which I started the game)

The game engine launches a windows form at start, then directx binds to this form. It's a fullscreen application with no windows forms borders etc.

Why doesn't teamviewer pick this up?

# Answer
Probably the same reason you can't use the Print key to capture the screen while running a fullscreen game: It's in exclusive mode, other programs can't access it (and will only grab the standard desktop you can't see while in the game).

Probably the easiest solution for this would be not using fullscreen mode. If you don't want window borders, remove those and essentially render in a borderless window filling the desktop. Just keep in mind that you won't be able to control refresh rate while being in this mode (and VSync might be dictated/forced by the window manager).
> 5 votes

---
Tags: c#, directx
---


title: How to do starcraft pathfinding?

text:
# Question
Title: How to do starcraft pathfinding?
I've been trying to figure out how to implement something like the pathfinding in Starcraft 2. I'm not looking for all the sophisticated features like flocking, queueing, etc. In fact I like how in Starcraft 1 the units would interfere with each other. But I do want a path finder better than that used in Starcraft 1.

From the Google searches I've done the various answers have something to do with A\* over a navigation mesh and/or dealing with some kind of "visibility graph". But I've gotten somewhat conflicting or unclear answers on what I should do.

One thing I read about has something to do with doing A\* over the vertices of a triangle mesh (the navigation mesh). And then somehow "straightening out the path" which I don't know how to do. But that doesn't guarantee optimality right?

Another question I had is how does the starcraft 2 pathfinding deal with the fact that the units are discs with a finite radius and not points when dealing with corners? And how to deal with dynamic obstacles like idle units or even other moving units.

I'm looking for some gritty detailed explaination and not the generic super high level overviews that are typical in search results.

If it matters I've already looked at Amit’s Notes about Path-Finding. I've heard of but not read Computational Geometry: Algorithms and Applications. And a blog post about a AI navigation presentation at GDC 2011 mentioned that Starcraft 2 uses a constrained delaunay triangulation for a navmesh. Although the blog post mentions Boids steering and "horizon analysis", it doesn't mention exactly how the core pathfinding is done on the navmesh.

# Answer
If you have Starcraft 2 installed, open up the *map editor* and toggle the *pathfinding*. You will be able to see how the nav mesh is constructed as you place buildings and other obstacles around.

> In fact I like how in Starcraft 1 the units would interfere with each other. But I do want a path finder better than that used in Starcraft 1.

Shouldn't be a problem - Starcraft 1's pathfinding was silly. This blog post by one of the programmers talks about it.

> One thing I read about has something to do with doing A\* over the vertices of a triangle mesh (the navigation mesh). And then somehow "straightening out the path" which I don't know how to do. But that doesn't guarantee optimality right?

It's about making the AI *not dumb* more than optimal. Your units end up with zig-zag movement between nodes if you don't apply a bit of smoothing.

When doing path planning, you will have a *refinement stage* where you look at what nodes your unit needs to walk through to get to their goal, and then you start taking out excess nodes in the middle of the path that we don't need to follow, i.e. we can directly go from node A to node C through B without static collisions, so ignore B entirely.

This ends up straightening out the path.

> I'm looking for some gritty detailed explaination and not the generic super high level overviews that are typical in search results.

If you want a solid explanation, this is already covered nicely in books (with working game code, even). So if you have some money to burn, check out Programming Game AI By Example and/or Artificial Intelligence for Games. Both of them discuss these topics in great depth.
> 10 votes

---
Tags: path-finding, navmesh, triangulation
---


# Question
Title: Remove a body when touched in LibGDX(Box2D)
I am using LibGDX to create a new project.

What i am trying to do is, i load bodies from a tmx file into levels which works fine. The bodies also has a sprite with them.

The problem is, is i would like to allow the user to touch certain bodies on the scene. When they touch the body they will be able to delete or remove it from the scene.

Is there anyway i can do this in LibGDX?

# Answer
> 1 votes
You need to remove the object from Box2D and from libGDX's render. The first task could be done with "destroyBody" method of World class. The second depends on what kind of rendering objects your are using. If you are using "Actors" just call "removeActor" on the parent of oyr render object.

---
Tags: android, box2d, libgdx
---


# Question
Title: Box2D Static-Dynamic body joint eliminates collisions
I have a static body A, and a dynamic body B, and a dynamic body C. A is filtered to not collide with anything, B and C collide with each other.

I wish to create a joint between B and A. When I create a joint (ex. revolute), B no longer collides with C - C passes through it as if it does not exist.

What am I doing wrong? How can adding a joint prevent a body from colliding with another body it used to?

EDIT: I want to join B with A, and have B collide with C, but not A collide with C. In realistic terms, I'm trying to create a revolute joint between a wheel (B) and a wall (A), and have a box (C) hit the wheel and the wheel would then rotate.

EDIT: I create a the simplest revolute joint I can with these parameters (C++):

```
b2RevoluteJointDef def;
def.Initialize(A, B, B -> GetWorldCenter());
world -> CreateJoint(&def);

```

# Answer
> 1 votes
Fixture density of body B was 0, it should be a positive value.

```
b2FixtureDef f;
...
f.density = 10.f; // greater than 0
B -> CreateFixture(f);

```

---
Tags: collision-detection, box2d
---


title: Debugging tips?

text:
# Question
Title: Debugging tips?
I'm new to games programming and I'm working on a C#/XNA project.

Something I'm spending a lot of time on is debugging. Obviously as games run in a loop finding the exact iteration that a bad condition has occurred can be tricky.

Spending time setting up conditional breakpoints certainly helps but eats up time.

Are there some ninja tips out there for helping to track down the precise moment things go bad that you guys use?

# Answer
> 4 votes
* Kind of a simple advice here but a little something that I found very useful is displaying **debugging strings/rectangles** to the screen.

You can print the player's current state, the enemy's animation state, the number of active bullets, the frames per second, etc. All these simple variables are what make up the core of your game, so it's essential that they work properly and a nice way to make sure they do so is to have debugging tools at hand.

So, in addition to logging variables like Gajet proposed (which is a very good advice *imho*), you should also show these variables while your testing so you can clearly see when something is wrong.

It may seem stupid, but it helped me find a lot of nasty bugs that I thought were much more complicated (I simply put red rectangles to show colliding tiles on a platformer, and I found out that the problem wasn't in the collision response code, but rather in the collision detection code).

You'll start out with a debugging string tool, then move on to debugging shapes (rectangles or even lines to represent vectors), then to more complicated tools and you'll eventually end up with a pretty solid **debugging toolbox** that you can **reuse** over other projects (if you make sure your debug code is general enough to be independant of the game).
* In addition to debugging tools, consider writing **unit tests**. I know it doesn't sound nice having to write tests for most functions from your game, but don't see it this way. Unit tests can save you a whole lot of time. For example, if your collision system is not working but you wrote enough unit tests for your collision detection, you can just look into your collision response code and find the bug.

Not only does it tell you where to look for the bug, it also tells you when you break something after changing a few lines somewhere, because your tests won't pass anymore.
* If unit tests are too much for you, then at least start adding **assertions** into your code. So, if something is obviously wrong (e.g. a character with negative health), your code will break right away and you won't waste your time too much.

A couple of advices that I learned the hard way. You may think some are useless, but try them out and see if they fit your debugging needs.

# Answer
> 5 votes
you can try creating log files, although they may a be a bit hard to work with but they are useful in many ways:

* using log files you can replay your game with all the things happen in it including the bugs! so in case of rare bugs you can check the bug again and again until you solve it.
* using log files you can monitor your variables without stopping your program, I mean when you try debugging your program is stopped for a couple of minutes when you are checking what is happening and usually that will lead to unexpected frames after debugging. but using log files you can monitor all those variables after program execution so there will be no unexpected changes in your application results.
* later on you can use same log file feature to create a replay viewer for your game, it's pretty good if a gamer could see what he did or what he didn't to win/lose a game.

# Answer
> 1 votes
I know that it's been awhile since this question was posted but I feel that people might benefit from these answers and I'd like to point out something else that has helped me tremendously. Right click your project in the Solution Explorer and select properties. On the properties page that opens make sure the Application tab is selected and look for the Output Type drop-down list. By Default it is set to Windows Application but you can change it to Console Application. With this enabled your application will run as normal but in addition to the XNA window a second console window will open and you can output messages with a simple Console.WriteLine()

# Answer
> 0 votes
A debugging feature that I recommend implementing is a "frame advance" function. This is a common feature in classic console emulators that allow input recordings for the purpose of developing tool-assisted speedruns. Essentially, you pause the update loop, and press a key to run the next pass of the update loop exactly once. This was really helpful for me in developing a platformer project, as it let me more easily study the effects of a collision response on the frame of the collision.

I implemented this by having a "DebugPause" flag, toggled by pressing a key while in "GameDebugMode" in the game. In the DebugPause state, the update loop is exited immediately after listening for input, essentially freezing everything in place while still rendering graphics. Then, if the "DebugFrameAdvance" key is hit, the remainder of the update loop is called exactly once. This way, you can hold the desired keys down for input, hit the DebugFrameAdvance key, and observe how the game responds on a particular frame. Combined with some kind of collision box display, you can see the details of how the physics in your game works in slow-motion. Also, while paused, you can set a breakpoint somewhere inside your update loop, and it won't be called until your next frame advance!

Note that my game used a fixed time-step, so I think some additional trickery will have to be put in place if you have a variable time step.

I hope this helps, and good luck!

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


# Question
Title: Is there a better way to handle a large amount of organized game data in Character Creation?
I am currently working on a text based prototype, in where the player is (eventually) allowed to have over 180 character choices in a quickly played permadeath type of game. It's a lot simpler than it sounds, based on a sort-of component system where the player choices several components, which can result in so many character types. However, each character type is distinctly defined, tagged, and marked with data for a very specific reason. So there may be a lot of different "Orcs" the player could create, they are each defined in game data individually with their respective changes to the base character.

Right now, the game only has about 4 character choices. This is easily handled in code, without any save/loading of files, or accessing of databases, or any fancy classes.

In many text based games, it is all handled in code, perhaps with a simple switch. Input choice: 1 = Human, 2 = Elf, 3 = Orc, 4 = Minotaur, etc. etc. However, this tends to get ugly when there are 180 possible choices. It gets uglier with nested switches.

I want to be able to have players filter the vast number of choices, with something like a GUI search bar or checkbox options. "\[ X \] Melee Based, \[ \] Uses Spells, \[ X \] Uses Stealth." Even simpler, perhaps a button for players who need help choosing, or suggestions based on a few questions for new players. "Are you big on Swords or Sorcery? blah blah" Alright, we suggest you try a: Elven Fire Wizard.

Besides hard coding this information which is what I am currently planning, is there a more organized way to handle search queries, the process of elimination, filtering of results, or any other thing I might need to help ease players into choosing from what will certainly be an overwhelming number of possibilities? Even if newbies are only given a small number of choices that are easy to grasp, even expert players will need some sort of filtering system to help them decide.

As a developer, I enjoy having my code easily accessible. Reading through nested control structures to edit information isn't my favorite way of handling it. However, right now it's certainly the easiest since I only have 4 character choices. I am entirely ignorant on databases, so forgive my ignorance if I mentioned that.

I am not exactly sure if a "database" is overkill or not for game data like this. Especially game data that doesn't need to be accessible to anyone but the developer, and is only very large after a significant amount of time has passed to update the game hundreds of times.

# Answer
What you are trying to do is also fairly similar to what older MUDs did. I am more familiar with the Diku variety and I'll explain it briefly here. If you think that is what you are looking for, you can look up the source code, it is fairly straightforward.

First, the different stats and skills are all hardcoded. Strength is a concept known at the code level. Same for hp, armor, stealth, fire resist and so on. All the skills like backstab, spells, hide, etc., also exist in code.

All the rest of the data is loaded from a database, even races and classes. So a character structure would be

* base stats
* current stats (accessor function that takes into account current status of character plus race modifier, etc)
* race
* class
* inventory

Races are loaded from a file and define:

* stats modifier (Int +2)
* available classes if you want to limit class selection in that way
* race-related skill

The same goes with the classes, but they define different elements

* minimum stats requirements (if you implement anything like that)
* skills and the level at which they are granted (spells can be considered skills)
* experience needed to advance (if it is class-based)
* etc.

Finally, you have the equipment which work just the same way: all defined in a file using a custom format

* name
* min level
* class requirement
* equipment slot (little bit more tricky)
* stat modifiers (same as race: Int +2, Armor -3, etc.)
* recharge time (for cooldowns)

So that's a brief overview but should give a good idea of what was going, you can see more for yourself in the code (tarball) but be advise there is a whole lot more concept going on in there (object containers, etc).
> 2 votes

# Answer
If you're expecting to have 180+ different types of characters, even if they are constructed via different combinations of components, you *definitely don't want to hardcode* the choices and guides for them. You're going to want to write a generic solution.

You can start by sorting out the different layers of base types and components that will be attached to them. The effects those components have can be categorized and turned into values, and the values for each component can be specified in non-code files that are read by your program. All your code has to do is load component data and combine values together, ultimately forming one of your final character types. Thus, the characters, their properties, and their abilities become *emergent*.

Suggestions for new users, as well as filters and search queries can be implemented by matching a set of input values to component or base character types. If you don't want users to interface with these raw values, you can create an abstraction layer over them. For example, instead of having users enter `Strength: 5`, you can give them choices like `High`, `Medium`, and `Low`, and behind the scenes convert them into actual values your system uses.

The 'database' you're talking about would be the collection of data defining different components and their values.

**A More Concrete Example**

Let's say we want the game to have two base classes: Elves and Orcs. The first thing to decide is how to quantify what separates different types of these classes, and thus different playstyles among players. Typically these are things like Melee, Archery, and Magic skills. To get the most emergent behavior, we'd want variables which don't directly relate to the high-level skills, but can be combined to make them. So something like:

```
strength
agility
knowledge
defense
stealth

```

A Melee character would be high in strength and defense. An archer would be high in agility and stealth. This scheme offers a lot of gray area between different specializations and more choices for your players.

Each base class provides some starting stats in each of these categories:

```
Elf:
    Strength: 4
    Agility: 8
    Knowledge: 7
    Defense: 3
    Stealth: 5

Orc
    Strength: 9
    Agility: 2
    Knowledge: 3
    Defense: 7
    Stealth: 4

```

Components that you add further define characters by adding or subtracting from these stats. I'm not really clear on what your components are, so I'll get creative for this example. One component could be armor:

```
The Iron Armor of Superb Armor...ness
    Strength +0
    Agility -1
    Knowledge +0
    Defense +10
    Stealth -2

The Light Armor of Extreme Brightness (Get it?)
    Strength +0
    Agility +2
    Knowledge +1
    Defense +5
    Stealth +3

```

I'm not sure this is such a great example component in terms of character development, but hopefully it conveys the idea. Note how these components can be defined in external text or XML files. In terms of numbers, if you have two base classes and 10 types of armor, that gives you 20 unique final character options. That number multiplies further with other component choices. And you didn't have to hardcode a single one :).

For your new users, you ask them to fill out the stats of their ideal character, or help them fill out the stats with a series of questions. You can then find a base character and components which best match the set of stats.
> 4 votes

# Answer
You should probably play some League of Legends (LoL for short). Seriously. It is a great example of a few Classes (Mage, Carry, Ranged, etc.), that can be broken down into 70 or so characters, each of which can equip a large number of 'components', making for vastly different play and experience for the player.

Sounds to me like that's the kind of concept your going for (character wise). Now, in LoL each character is distinct (at it's base) from any other character, but you could probably get away with simply having a list of `types` of characters (Orc, Human, Lizard, etc) with no base abilities. Instead, each component in your game would be tagged with metadata.

```
A sword would be tagged ('Melee','Warrior'),
a wand ('Magic', 'Mage'),
leather armor ('Ranged', 'Stealth', 'Assassin'),
a dagger ('Stealth', 'Assassin','Melee'),
fire spell ('Magic','Fire','Mage')

```

A player selecting Orc, leather armor, dagger, and fire spell could be called an 'Orc Fire Assassin' or 'Stealthy Orc of Fire"

This would require entering metadata for each of your 'components', but I see no reasonable alternative.

If none of this helps, maybe it would be a good idea to discribe how components and character work together in your game.
> 2 votes

---
Tags: databases
---


# Question
Title: Get GameTime's milliseconds in plain format
I am trying to fire an action every 125ms.

To get the current milliseconds, I go this way:

```
double passedMs = GameTime.TotalGameTime.TotalMilliseconds;

//this is a double as well
currentMs += (currentMs - passedMs)

if (currentMs > 125)
{
   //Action
   currentMs = 0;
}

```

But the value I get in passedMs is not simply milliseconds, it's more like `8833.351`.

So what could I do here?

# Answer
> 5 votes
My understanding is that TotalGameTime represents how long it's been since the executable opened. In your case, it's been up around 8 seconds. For your += statement, I think currently you're taking the difference of the two, and adding it to the current time...? I'm not even sure what that resulting value would be.

I think more likely, you're looking for `ElapsedGameTime` (documentation on MSDN); replace the contents of the parentheses with just that to get what you're looking for:

```
currentMs += GameTime.ElapsedGameTime.TotalMilliseconds;

```

Also, I would advise you to subtract 125 from currentMs, rather than setting it to 0. If currentMS becomes 200, then it's going to have somewhat inconsistent timing.

```
if (currentMs > 125)
{
   // Action
   currentMs -= 125;
}

```

# Answer
> 1 votes
Use an accumulation buffer, this way if you wait too long you don't waste the left-over. (But get your timing logic straight first)

```
currentMs += GameTime.ElapsedGameTime.TotalMilliseconds;

if (currentMs > 125) {
   //Action
   currentMs -= 125;
}

```

EDIT: oh well other answer has got the same code now lol

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


# Question
Title: Uncharted 2 tone mapping and an eye adaptation
I found an example of uncharted 2 tone mapping on this site. Here is the code:

```
float A = 0.15;
float B = 0.50;
float C = 0.10;
float D = 0.20;
float E = 0.02;
float F = 0.30;
float W = 11.2;

float3 Uncharted2Tonemap(float3 x)
{
     return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;
}

float4 ps_main( float2 texCoord  : TEXCOORD0 ) : COLOR
{
     float3 texColor = tex2D(Texture0, texCoord );
     texColor *= 16;  // Hardcoded Exposure Adjustment
     float ExposureBias = 2.0f;
     float3 curr = Uncharted2Tonemap(ExposureBias*texColor);
     float3 whiteScale = 1.0f/Uncharted2Tonemap(W);
     float3 color = curr*whiteScale;
     float3 retColor = pow(color,1/2.2);
     return float4(retColor,1);
}

```

I use Reinhard tone mapping. I calculate an average luminance and max luminance in screen space. Based on those parameters I get an eye adaptation, for example when a camera is moved from a bright outdoor area to the dark room. How an eye adaptation process is achieved in Uncharted 2 tone mapping ? In my engine I render results of the shading to the floating point texture. I assume that I don’t need hardcoded exposure adjustment (texColor \*= 16) and exposure bias = 2.0f. Or maybe I should interpret those parameters based on the average luminance ? What about “w” parameter ? Can I assign to “w” a maximum luminance from the screen space ?

# Answer
Eye adaptation is a separate process from tone mapping. As shown in the code, exposure can be adjusted by scaling the HDR image value by some factor before applying the tone curve. The \*= 16 and the exposure bias are doing this. You would replace these factors with your eye adaptation value.
> 3 votes

---
Tags: opengl, mathematics, hdr
---