# Question
Title: SAT - How to find Shortest line between two static convex 2D Polygons?
RI have a pretty standard SAT algorithm that seems to successfully be detecting collisions but now I am looking for some assistance in finding the shortest line between 2 separated Polygons.

I have spent quite a bit of time searching and trying things with no success. If someone could point me in the correct direction or give a solution to this I would be most greatful.

While a general n polygon vs n polygon solution would be awesome my use case only requires OBB vs OBB. This could simplify the answer.

# Answer
If you think they might intersect, find the intersection point(s) (likely two).

Otherwise:

1. Compute the points closest to `{A, B, C, D}` on each of the lines (containing the segments) on the other OBB.
2. If these points are withing the segments then compute the distance and store it if it's the shortest distance so far. Otherwise: Go to 3:
3. Check on which side of the segment the closest point is an and compute the distance from the corner on that side. Again, if it's the shortest distance so far, store it and overwrite the previous best.

So foreach point `{A, B, C, D}`, find the closest point on the lines of the other OBB `{X, Y, Z, W}`, check if they are on that OBB's segments and if not, compute the distance to the corresponding corner of the OBB.
> 0 votes

# Answer
AFAIK Seperating Axes is only for detecting overlap, it can't be used to determine closest points in non-overlapping cases.
> 1 votes

---
Tags: collision-detection, separating-axis-theorem
---


# Question
Title: Increase animation speed according to the swipe speed in unity for Android
I have the animation done through Maya and brought the FBX file to unity. Here is my code to calculate the speed of the swipe:

```
Vector2 speedMeasuredInScreenWidthsPerSecond =(Input.touches[0].deltaPosition / Screen.width) *     Input.touches[0].deltaTime;

```

Now I wanted to take `speedMeasuredInScreenWidthsPerSecond` and use it to increase the animation speed accordingly like this:

```
animation["gmeChaAnimMiddle"].speed=Mathf.Round(speedMeasuredInScreenWidthsPerSecond);

```

However, this results in an error that I need to convert Vector2 to float.

So how do I overcome it?

# Answer
> 1 votes
You can try to use length of your vector (Vector2.magnitude).

In your case it can be:

```
animation["gmeChaAnimMiddle"].speed=Mathf.Round(speedMeasuredInScreenWidthsPerSecond.magnitude);

```

---
Tags: unity, unityscript
---


# Question
Title: How can I determine the pixels covered by a transformed triangle (without drawing it)?
I have three points that form a triangle in a 3D scene. I want to apply an arbitrary rotation/translation transformation to this polygon and later check in which pixels of an image they would be rendered (if any), taking occlusion into account. I want to do this without having any window, so that no actual drawing is done (I know the camera parameters and the "virtual" rendering image size).

How can I accomplish this? I thought about OpenGL and the `glReadPixels` function, but I am not sure that I can query for a 3D point to get its rendered 2D pixel.

For reference, I am working on a computer vision application where I have an image taken by a camera and a 3D model of a virtual object. The virtual object is a mesh of a lot of triangles. What I actually want is to project the virtual object on the image and get the positions in the image of the non-occluded triangles, so that I can manipulate the image in those positions. As I said, I don't really need to draw, just the calculations. Now, I am doing it manually and I can get rid of those points that are occluded by other points, but I do not know how to take occlusion into account when instead of single points, they are planar triangles.

# Answer
> 2 votes
I know you don't want to render, but is this a hard requirement? How about rendering to a texture, and then reading the resulting pixels from the texture? no *screen* rendering will take place, and you will be taking advantage of the hardware to do it for you. Here's a tutorial that seems to explain how render-to-texture works.

If you *really* don't want to do any rendering at all, you can always multiply your vertices by your projection matrix, divide by w, discard z, and your x and y are the coordinates of each vertex in screen space (their meaning is dependent on the projection matrix you used).

With your three vertices in screen space, all you have to do is rasterize them to know which pixels lie inside the triangle. Here's a tutorial that seems to explain rasterization.

# Answer
> 2 votes
OpenGL provides occlusion queries, described here. They are not exactly simple to use, but I believe they will do what you need.

Basically, you create an occlusion query object, then "activate" it with `glBeginQuery` during the rendering that you want to analyze. After you are done drawing the geometry of interest, call `glEndQuery` and `glGetQueryObject`, passing `GL_QUERY_RESULT`.

This technique can be used with the texture rendering technique described above.

For an interesting description of some performance issues and ways to get around them, check out this good page.

---
Tags: opengl, 3d, rendering
---


# Question
Title: How do I programmatically access single sprites when Sprite Mode is Multiple?
Unity 4.3 newly brings an ability to cut up a sprite sheet into multiple individual sprites. This is useful since you then only need one master spritesheet, but nevertheless get references to individual sprites. It's done by setting *Sprite Mode* to *Multiple*.

Can all the sprites generated from the master file be programmatically accessed from the Unity Sprite Editor?

For example: I have a spritesheet with a grid of 50x50 sprites. Using the Unity Sprite Editor, I now have 250 sprites: `spritesheet_0, spritesheet_1, ..., spritesheet_249`. How can I get a handle to `spritesheet_102` without having to manually drag and drop it in the Unity editor?

# Answer
> 6 votes
You need to create a sprite array `Sprite[] sprites` and fill it using `sprites = Resources.LoadAll<Sprite>("Location");` inside Awake().

---
Tags: unity, sprites, spritesheet
---


title: Separating axis Theorem rotation issue

text:
# Question
Title: Separating axis Theorem rotation issue
I made a post yesterday to see if anyone could understand my problem.

However I did not receive much guidance, probably because my question was not clear.

I have worked on it a little more and discovered the actual issue and now have a clearer picture of what is causing the problem.

As you can see from the image, the boxes are projected correctly along their appropriate axis (all components labeled 1 are from the main white box 1 and vice versa).

The problem comes when the box is rotated. (See image 2). Box 1 has been rotated but the corner (projection?) in green clearly does not match the shape of the rotated box 1 and is much much closer to box 2 than it should be. The axis projections have changed and axis 1 is on the far left but axis 3 has gone?

**THE CODE CAN BE SEEN ON MY PREVIOUS POST** Separating Axis Theorem Issue

Thank you! ;D

# Answer
> 1 votes
The problem with your image is that the green box is first rotated then stretched. With no rotation, this gives the correct rectangle, but then it fails.

Anyway, I don't think you understood clearly how the algorithm works. The algorithm consists to check whether the projection on an axis of the two shapes intersects, for each axis of a nicely selected set of axes. The set of axis consist of the line going through the normal at each face, i.e. a line perpendicular to each face. Luckily in the case of boxes, it implies only two lines per shapes since sides are parallel by twos.

In the following picture, there are two boxes, in yellow and orange. Every axis is depicted by a black line.

Consider the projection on the slightly dipping axis. Its projection in the orange segment of the line. The segment was obtained by orthogonally projecting the vertices of the orange box (i.e. its corners) onto the line. They are obtained by intersecting the axis with the blue dashed lines, each one of which is a perpendicular of the axis going through a rectangle vertex.

The projection of the yellow box on one of its axis is trivial ; it is the dark yellow segment of the axis. You then have to check whether the two segments intersects. If they don't, the box don't intersect either, if they do, you have to check along another axis. If on each axis, the projection of the boxes intersect, then the two shapes intersects.

There's an optimization doable here : check that the projected vertices are either all on the left of the left side of the yellow box or all on the right of its right side. If they do, the projected segments do not intersect. Else they do intersect.

---

**Note** : Since each shapes has only two axes those axis may serve as a reference system for the plane. Consider the system generated by the yellow box, I shall call it the “yellow system”. Then each segments obtained by projecting the orange box on each yellow axis corresponds to the sides the *axis-aligned bounding box* (AABB) of the orange box in the yellow system. In the picture that I remind below, this AABB is reprensented by a dotted rectangle boundary. See how the projected segment correspond to a translation of some sides of the AABB.

Maybe building this AABB was what you were trying to compute. But to compute it nicely, you have to compute the projected segment first anyway, so there is no gain to explicity compute AABBs. In any case, I can't understand how such an AABB can be a rectangle when using two *squares* with the *same orientation*.

---
Tags: c++, vector, separating-axis-theorem
---


# Question
Title: What is the approach of creating an image puzzle game with libgdx
I would like to create a game which consists of taking a random image, slicing it up into some number of pieces (according to a selected difficulty) and letting the player solve the puzzle.

I've googled this, but didn't find anything relevant that would at least help me understand how this kind of games are to be approached. I did come across this article Custom Sprite Batcher in LibGDX, but it is not complete and is rather confusing to me for now.

Any suggestions are much appreciated. Thanks.

# Answer
> 1 votes
You should probably use texture regions.

With texture regions you can select a sprite, doesn't necessarily have to be a sprite in your case, and slice it up in parts to be reused.

As example:

```
int numOfTiles_Horizontal = 3;//Can be any size as long as it lines up with the texture size.
int numOfTiles_Vertical = 3;//Can be any size as long as it lines up with the texture size.

float tile_width = texture.getWdith() / numOfTiles_Horizontal;
float tile_height = texture.getHeight() / numOfTiles_Vertical;

TextureRegion[][] sprites = new TextureRegion[numOfTiles_Horizontal][numOfTiles_Vertical];
for(int col = 0; col < numOfTiles_Horizontal; col++) {
    for(int row = 0; row < numOfTiles_Vertical; row++){
        sprites[c][r] = new TextureRegion(texture, c * tile_width, r * tile_height, tile_width, tile_height);
    }
}

```

This leaves you with and 2D array of textureregions of the original texture. The you can copy this one into a new one. Scramble the new one. And then add your slide puzzle mechanic. Then each time the player has moved a a slice just do this.

```
public Boolean checkPuzzleSolvedOrSomething(){
    Boolean[] isEqual = new Boolean[numOfTiles_Horizontal * numOfTiles_Vertical];
    int sprite_counter = 0;

    for(int col = 0; col < numOfTiles_Horizontal; col++) {
        for(int row = 0; row < numOfTiles_Vertical; row++){
            if(sprites_scrambled[c][r] == sprites[c][r]){isEqual[sprite_counter] = true; }
            else{isEqual[sprite_counter] = false; }
            sprite_counter++;
        }
    }

    for(int i = 0; i < isEqual.length; i++;){
        if(isEqual[i] == true){continue;}//If designated region is in the right place continue
        else{return false;}//Else return that the puzzle is not yet completed.
    }
    return false;//Should never reach this but is needed to complete method.
}

```

Hopes this helps.

---
Tags: java, libgdx, puzzle
---


# Question
Title: glsl shader to allow color change of skydome ogre3d
I'm still very new to all this but learning a lot. I'm putting together an application using Ogre3d as the rendering engine. So far I've got it running, with a simple scene, a day/night cycle system which is working okay.

I'm now moving on to looking at changing the color of the skydome material based on the time of day. What I've done so far is to create a struct to hold the ColourValues for the different aspects of the scene.

```
struct todColors {
    Ogre::ColourValue sky;
    Ogre::ColourValue ambient;
    Ogre::ColourValue sun;
};

```

I created an array to store all the colours

```
todColors   sceneColours [4];

```

I populated the array with the colours I want to use for the various times of the day. For instance DayTime (when the sun is high in the sky)

```
sceneColours[2].sky = Ogre::ColourValue(135/255, 206/255, 235/255, 255);
sceneColours[2].ambient = Ogre::ColourValue(135/255, 206/255, 235/255, 255);
sceneColours[2].sun = Ogre::ColourValue(135/255, 206/255, 235/255, 255);

```

I've got code to work out the time of the day using a float currentHours to store the current hour of the day 10.5 = 10:30 am. This updates constantly and updates the sun as required.

I am then calculating the appropriate colours for the time of day when relevant using

```
else if( currentHour >= 4 && currentHour < 7) {

    // Lerp from night to morning
    Ogre::ColourValue lerp = Ogre::Math::lerp<Ogre::ColourValue, float>(sceneColours[GT_TOD_NIGHT].sky , sceneColours[GT_TOD_MORNING].sky, (currentHour - 4) / (7 - 4));

}

```

My original attempt to get this to work was to dynamically generate a material with the new colour and apply that material to the skydome. This, as you can probably guess... didn't go well.

I know it's possible to use shaders where you can pass information such as colour to the shader from the code but I am unsure if there is an existing simple shader to change a colour like this or if I need to create one.

What is involved in creating a shader and material definition that would allow me to change the colour of a material without the overheads of dynamically generating materials all the time?

EDIT : I've created a glsl vertex and fragment shaders as follows.

Vertex

```
uniform vec4 newColor;

void main()
{
gl_FrontColor = newColor;
gl_Position = ftransform();
}

```

Fragment

```
void main()
{
gl_FragColor = gl_Color;
}

```

I can pass a colour to it using ShaderDesigner and it seems to work. I now need to investigate how to use it within Ogre as a material.

EDIT :

I created a material file like this :

```
vertex_program colour_vs_test glsl
{
source test.vert
default_params
{
    param_named newColor float4 0.0 0.0 0.0 1
}
}

fragment_program colour_fs_glsl glsl
{
source test.frag
}

material Test/SkyColor
{
technique
{
    pass
    {
        lighting off

        fragment_program_ref colour_fs_glsl
        {
        }
        vertex_program_ref colour_vs_test
        {
        }
    }
}
}

```

In the code I have tried :

```
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName("Test/SkyColor");
Ogre::GpuProgramParametersSharedPtr params = material->getTechnique(0)->getPass(0)->getVertexProgramParameters();
params->setNamedConstant("newcolor", Ogre::Vector4(0.7, 0.5, 0.3, 1));

```

I've set that as the Skydome material which seems to work initially. I am doing the same with the code that is attempting to lerp between colours, but when I include it there, it all goes black.

Seems like there is now a problem with my colour lerping.

# Answer
> 1 votes
Okay well... I couldn't work out what was going on with the lerp in Ogre. I tried vectors and floats and it just wasn't happening as expected. However, it occurred to me that surely the shaders would have a lerp functionality in them. Perhaps one that actually works.

I modified my vertex shader like this :

```
uniform vec4 oldcolor;
uniform vec4 newcolor;
uniform float time;

void main() {
    gl_FrontColor = mix(oldcolor, newcolor, time);
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}

```

Turns out in glsl the lerp equivalent is mix.

Then I modified the code where I was setting the sky colour based on the time of day in order to pass both the oldcolor and the newcolor. The colours I wanted to lerp between.

```
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName("Test/SkyColor");
Ogre::GpuProgramParametersSharedPtr params = material->getTechnique(0)->getPass(0)->getVertexProgramParameters();
params->setNamedConstant("oldcolor", nightSkyColor);
params->setNamedConstant("newcolor", morningSkyColor);
params->setNamedConstant("time", lerpAmount);

```

Then update the skyDome with the modified material

```
OgreFramework::getSingletonPtr()->m_pSceneMgr->setSkyDome(true, "OpenZone/SkyColor", 5, 8);

```

That is a very basic GLSL shader to blend the colour of a material with Ogre3d.

---
Tags: c++, shaders, graphics, ogre
---


title: Moving unit along a computed path

text:
# Question
Title: Moving unit along a computed path
I am generating a path using pathfinding.js. This returns a path of node coordinates from a matrix. Example:

```
var matrix = [[0,0,0,0], //0 are passable, 1 are obstacles
              [0,1,1,0],
              [0,1,1,0],
              [0,0,0,0]]

var path = [[0,0],[0,1],[0,2],[0,3],[1,3]] etc.

```

I now wish to convert this to path to something like, takeoff(), turnLeft(), forward(4) etc.

What this process called, I have had a look at many programming books and guides but they seem to ignore this method or miss it out. I also had a go at it myself but can't figure out the direction of unit that is being moved along the path.

# Answer
You need to “parse” the string of positions using a state, the orientation of your plane/car/bomberman/boat/... Let say you represent direction by unitary vector in the direction; e.g. north is `[0,1]`, east is `[1,0]`, south is `[0,-1]`, west is `[-1,0]`

Now you have the direction of the car as a state during parsing, which is initialize to the current direction of the car. You can now simply feed the path nodes one by one, compute where to go for next step and remove nodes of the list when you move onto them.

A simple pseudo code would be :

```
orientation_state = plane.orientation;
position_state = path.pop();
action_sequence = [];

while( path != [] ) {
    next_position = path.pop();
    shift = next_position - position_state;
    if( shift != orientation_state ){
        orientation_state = shift;
        action_sequence.append("turn " + shift + " !");
    }
    action_sequence.append("forward !");
    position_state = next_position;
}

```
> 1 votes

---
Tags: path-finding
---


# Question
Title: Difference between Arcade, P2 and Ninja physics in Phaser
I am a beginner and trying to learn game development using *Phaser*. Currently Phaser is providing three physics systems namely Arcade, P2 and Ninja. But I don't know the differences between them and I would also like to know in which scenario we should use a particular physics system?

Please give me some insight for these physics systems.

# Answer
As mentioned in the comments, their site already explains what the three systems are and what they can be used for.

> Arcade Physics is for high-speed AABB collision only.

AABB means axis-aligned bounded rectangles; it means you have objects without rotation, and you're only checking if the image (which is a rectangle) overlaps with another image (so there's a potential collision). This is cheap to compute, and fast, which is probably why they recommend it for high-speed collisions.

One issue with AABB is that it doesn't guarantee that there really is a collision; you may have a completely transparent area overlapping.

> Ninja Physics allows for complex tiles and slopes, perfect for level scenery, \[...\]

Remember how AABB is non-rotated? Ninja Physics will handle rotations (so it can do slopes and complex tiles). This is a more flexible (and probably more accurate) physics model; it's probably slower.

> \[...\] P2.JS is a full-body physics system, with constraints, springs, polygon support and more.

If you need to model springs (eg. something swinging like a pendulum), constraints on forces, and arbitrary polygon shapes (eg. tetrahedron), this sounds like what you want. If you want a frame of reference, think of something like Angry Birds.

Based on your game, you can pick which is the best-fit to your needs. It sounds like a spectrum of speed versus accuracy/complexity (Arcade Physics being the fastest but simplest).
> 40 votes

---
Tags: phaser
---


# Question
Title: Why shouldn't I permit changing the field of view, if the technology allows for it?
This is less of a question aimed at developing a game and more about the technology behind it. A number of gaming journalists and pro gamers (both in the tournament and the home entertainment sector) often hammer on the matter that any first or third person game should have a way to change the field of view, and I agree with them. The main reason they mention this is because a pretty large number of players get motion-sickness related headaches and eyestrain if they play with an overly constrained field of view.

I can understand if an indie developer does not allow this due to budget constraints, because they need to add support to the engine for that. However, a number of developers use high profile third party engines like Frostbite, Unity, Unreal, or Cryengine, but don't offer an option for changing the field of view.

Why shouldn't I permit changing the field of view, if the technology allows for it?

# Answer
4A Games, the developers of *Metro: Last Light* were receiving a lot of criticism for not having a FoV slider in their game. Community manager Maurice Tan defended their decision on the Steam forums as follows:

> The main reason for maintaining a fixed FOV is because we have 3D elements like the watch and weapon ammo that need to remain visible.
>
> In addition, all the game's first-person cut scenes and cinematics and each and every animation involving Artyom's hands - idle weapon animations, reloads, ladder climbing, melee attacks etc, - were created assuming the same, fixed field of view.
>
> Changing the FOV would break all the cut-scenes and animations - you would be able to see inside Artyom's arms, or they would appear to float in the air in front of you. Or worse.
>
> We had considered offering three FOV pre-sets, but this would still require significant work to re-do every animation, adjust the HUD and UI and other seemingly small but incredibly time consuming tasks.
>
> Even with a wider but still fixed field of view, Artyom's hands would look too far away. We know - we tried.
>
> Game performance is also tied to FOV - the amount of geometric detail we put in each scene has been partly determined by this set FOV, and setting a wider FOV would have a performance impact.

The main reason for not having a FoV slider was that they were going for a no-hud high-immersion approach were all information important for the player was displayed on 3d elements in their field of view. When your GUI is part of your render-scene, changing the FOV changes your GUI.

Something Tan didn't mention in above post but which likely also was a part of their decision is that the FOV is important for level-planning. *Metro: Last Light* is a horror-oriented game with a lot of jump-scares and other shock-moments. There are lots of situations where the player is distracted by something interesting so they look into one direction, and are then surprised by a sudden attack from the side. This shock-effect can only work when the level designers know the FOV of the player and so know what they can and can't see when looking from a certain point to a certain other point.

The same problem also appears in a different way when directing cutscenes. When you have high-immersion first person cutscenes, you likely want to have full control over the camera to be able to control what the player can and can't see. But when you don't know the FOV, directing the cinematography properly can be impossible. When the FOV of the player is higher than you expected, they will see objects they are not supposed to see yet. When the FOV is lower, the player won't see things they are supposed to see during a cutscene.
> 40 votes

# Answer
Not having a FOV slider in your game due to budget or technical reasons is a non argument. FOV is just one parameter in the creation of the view-projection matrix. After you have a proper matrix all the other calculations will follow by themselves. To word it in another way, making the FOV changeable means that only one line of code needs to be changed (in the camera class usually) and that an option needs to be added to the menu. The change does not propagate into other systems, they only 'see' the 4x4 matrix and don't care what the meaning of the values inside of it is.

```
public static Matrix CreatePerspectiveFieldOfView (
         float fieldOfView,
         float aspectRatio,
         float nearPlaneDistance,
         float farPlaneDistance
)

```

*Matrix creation with field of view in XNA*

However there are good reasons for not having a changeable FOV slider. Setting a higher FOV means that you can see more of the world on screen, this will have an impact on performance. Another reason is that in competitive play the player with a higher FOV setting will have an edge since that player can see more around him. Lastly it can ben an esthetical choice. A narrow FOV will give the player a different feeling than a wide FOV. Especially in shooters with narrow corridors a narrow FOV could add to the experience. A good example of this is the Call of Duty games where when you aim down your sight the FOV becomes smaller.

(Note that personally I do not believe that any of the reasons above should put a very low on the FOV, I just want to illustrate that in no way it is a technical problem.
> 12 votes

# Answer
One thing no-one else has mentioned is testing.

**Every aspect of control you give a player is another variable you have to test for.** For approximate full coverage, you effectively have to play through at each potential FoV, in case you get graphical issues only on one level under particular circumstances when you're in widest FoV or narrowest, or "when you saved the game at narrowest and open the save at widest".

This additional cost/delay may not be worth the additional value of FoV widening. Just because the engine supports it doesn't mean it will "just work" (although it does make it more likely). And just because the calculations should all work out doesn't mean that the user experience will be positive.
> 3 votes

# Answer
From a user perspective the main reason is that in multiplayer a wider FOV gives an unfair advantage.
> 0 votes

# Answer
As a developer, changing the field of view is a precarious decision to be made. This would also need to be a decision made early in game, in a multi-person studio it's important that a minimum frame rate and FOV are determined early on so that animations and Occlusion culling have something strict to work by. Of course Occlusion Culling can be based of numerous factors, not just Camera view.

I would say that the main reason I have never allowed FOV to be changed in game is that when this is the case gameplay generally is greatly altered, I've also known it to cause motion sickness. It will also mean that the camera is rendering more meaning a massive performance hit as games are generally optimised for their set FOV.

However, this is assuming I'm allowing you total control. There might be scope to allow the user to alter view cone from say 70-110 or something, but I don't know without testing that myself.
> 0 votes

# Answer
The others gave a bunch of good reasons - Aesthetic (cut scenes, desired look&feel of the game), Multiplayer balancing, Performance drop with wieder FOV, but I want to add some ideas to the technical aspect:

Especially the technical issues are probably more convoluted than many of you think, since a lot of processing is done on GraphicsBuffers and these Buffers usually have a fixed resolution - so a lot of Graphics detail will depend on the translation of these Buffers to the actual Geometry. For example many modern Shadow algorithms (apart from volumetric shadows) look more and more Blocky and Aliased with a higher FOV and the same Buffersize. The same is true for any algorithm which does ray-tracing like operations, because the FOV is wider, the single rays are spread in a wider arc, and more detail might get lost in approximations...
> 0 votes

---
Tags: viewport
---


# Question
Title: best way to implement movement after A* pathfinding? tile-based movement vs pixel-based?
I was able to implement the A\* pathfinding algorithm to calculate a path from the enemy to player.

After trying to do movement well, I realized I ran into all sorts of problems. I was able to add clearance to the pathfinding, so I'm now going to have sprites of variable size, which leads to even more issues.

I am currently doing movement like - path\[0\] is first Tile in path and it is removed when you get to it:

```
            if (path.Count > 0) {
                if (path[0].isTouching(this))
                    path.RemoveAt(0);
                }
            }

                            if (path [0].getCenterX() > this.getCenterX()) {
                                speedX = speed;
                                speedY = 0;
                                System.Console.WriteLine("moving right");
                            }
                            else if (path [0].getCenterX() < this.getCenterX()) {
                                speedX = -speed;
                                speedY = 0;
                                System.Console.WriteLine("moving left");
                            }

                            if (path [0].getCenterY() > this.getCenterY()) {
                                speedX = 0;
                                speedY = speed;
                                System.Console.WriteLine("moving down");

                            }
                            else if (path [0].getCenterY() < this.getCenterY()) {
                                speedX = 0;
                                speedY = -speed;
                                System.Console.WriteLine("moving up");
                            }

                            this.move(speedX, speedY);

```

This doesn't work very well for a variety of reasons.

I am certain the pathfinding I implemented calculates the proper path of Tiles. Now I think I have to move from a pixel to pixel movement -\> tile to tile in order to have this working better. This would probably help, right? How is movement usually done to work with A\*? If the tile-based movement would aid, any tips on implementing this?

# Answer
If you are talking about move horizontally and vertically at a same time, the problem is not here. You are doing fine. Maybe problem belong to input module.

About A\*, it's a path finding algorithm, it return series of point present the path you ask for. Movement is another problem, don't stick it with A\*. The easiest way to implement moving system are storing local goal, and once you reach local goal, go to next goal in path.

```
int position_x, position_y;
float speed_x, speed_y;
int local_goal_x, local_goal_y;
bool stop;
void next_goal(){
    path.removeAt(0);
    if(path.empty()){ stop = true; return;}
    local_goal_x = path[0].x;
    local_goal_y = path[0].y;
    speed_x = (local_goal_x - position_x)/10.0;
    speed_y = (local_goal_y - position_y)/10.0;
}
void update_moving()
{
    if(stop) return;
    position_x += speed_x;
    position_y += speed_y;
    if(position_x == local_goal_x && position_y == local_goal_y) next_goal();
}

```
> 1 votes

# Answer
I would do something like this:

```
int pixelPerFPS; // pixel per FPS
void move(int x, int y);
void update(int time)
{
    character.currentX += (character.goalX - character.currentX) / abs(character.goalX - character.currentX) * pixelPerFPS;
    character.currentY += (character.goalY - character.currentY) / abs(character.goalY - character.currentY) * pixelPerFPS;
    // do something
}
int gameStart()
{
    time2 = currentTime();
    while(running)
    {
        deltaTime = currentTime() - time2;
        time2 = currentTime();
        update(deltaTime);
        // do something
        // do other thing
    }
    return 0;
}

```

This is very simple function like an example

If you want to make it more complex and flexible, you have to take care about frame per seconds (FPS)
> 0 votes

---
Tags: xna, algorithm, path-finding
---


title: Moving turret aiming at moving target

text:
# Question
Title: Moving turret aiming at moving target
I've found this post Turret Aiming Formula on Reddit and a nice answer a while back.

The solution in the answer works great for still sanding turrets but is almost unusable for moving turrets since the speed of the turret is not applied to the bullet speed. The bullet still have the same fixed speed all the time but should be faster if the turret is moving in the same direction.

There are also a lot of answers here, but non of them respects the speed of the turret.

Is it possible do integrate turret speed into this formula or is there any other known solution?

My current code without turret speed:

```
Vector2f toTarget =  target.position - attacker.position;

float a = Vector2f.dot(target.velocity, target.velocity) - (bulletSpeed * bulletSpeed);
float b = 2 * Vector2f.dot(target.velocity, toTarget);
float c = Vector2f.dot(toTarget, toTarget);

float p = -b / (2 * a);
float q = sqrt((b * b) - 4 * a * c) / (2 * a);

float t1 = p - q;
float t2 = p + q;
float t;

if (t1 > t2 && t2 > 0){
    t = t2;
}
else{
    t = t1;
}

Vector2f aimSpot = target.position + target.velocity * t;

```

**update:**

the solution is to use relative velocity instead of `target.velocity` as suggested in the answer

```
relativeVelocity = target.velocity - attacker.velocity

```

and then use `bulletSpeed + attacker.velocity` for the bullet velocity

# Answer
> 3 votes
You could treat the turret as stationary and subtract the velocity of the turret to the target's velocity before the start of the code, provided it works for a motionless turret.

To subtract velocity vectors, if the target is moving 4 pixels left and 8 pixels up in a given time, but the turret is moving 4 pixels right and 3 pixels up in the same time, the turret could be said to be motionless and we treat movement up as positive, down as negative, left as positive and right as negative, then we have:

> Target(4, 8), Turret(-4, 3)
>
> --\> Turret(0,0), Target(4-(-4), 8-3)
>
> --\> Turret(0,0), Target(8, 5)

---
Tags: 2d, mathematics, ai, aiming
---


# Question
Title: Submit scores for multiple players to Game Center from one iPhone
I have a quiz game, which i would like to integrate Game Center for. This is a "local" multiplayer game with the possibility to play six players per match.

Is it possible to submit scores to the Game Center leaderboard for all six players in this setup given that it is only one player, the one that owns the device, that is logged on to Game Center?

If so, how is that done?

# Answer
You cannot submit scores to game center for multiple players on a single device without forcing the players to log in and out of their GC accounts.

When you report a score to a leaderboard you only pass in the leaderboard ID you want to report the score to, not the player ID.
> 0 votes

# Answer
As of iOS 7, it is now possible to submit scores for multiple players from one device. However, an app can do so only when ending the game, using the method `-endMatchInTurnWithMatchData:scores:achievements:completionHandler:` in the `GKTurnBaseMatch` class.

From the documentation about this method:

> **endMatchInTurnWithMatchData:scores:achievements:completionHandler:**
> Ends the match while submitting all of the scores and achievements.
> **Parameters:**
> ...
> *scores*
> An array of GKScore objects containing the final scores for every participant in the match.
> ...
> **Availability**
> Available in iOS 7.0 and later.
> 1 votes

---
Tags: ios, game-center
---


# Question
Title: How can I store game metadata in a .png file?
Spore allows player-created creatures to be shared by exporting a `.png` file. That `.png` is a photo of the creature, but if it's imported into the game, the creature's information (such as textures, size, and shape) also come with it.

How can I implement such a feature?

# Answer
> 63 votes
If all you truly needed was the PNG file, chances are they just simply added the information into the file. This is actually a practice of Steganography. A lot of the times, this is used to hide payloads or secret messages in things that are seemingly public facing. However, it is likely in this case that this method is what was used. Typical Stegongraphy will go out of the way to hide the contents, but there is no reason why one could not simply append the data out of the image in the end of the file and retrieve it.

A PNG has the byte signature `$89` at the start, so it is possible that the information was inserted after the PNG structure itself and simply parsed by the SPORE game.

However, further research given by the other answers and a search on google reveals that Spore was actually using just a version of Stegongraphy to hide the information in the alpha bits. With this in mind, we can rule out the possibility of appended data or meta-data.

It should be noted that **meta data** is still a very viable choice, if the data is being parsed locally. If that information might be shared around the web or re-encoded, the export is not guaranteed to keep all your information. When pixel data is used, it can survive losless conversions without an issue.

# Answer
> 154 votes
The PNG format has support for more-or-less arbitrary metadata. The PNG standard defines a PNG file, essentially a series of chunks, some of which are required (and contain the image data). Others, however, are optional. For example, there's a chunk for storing gamma information or histogram data.

In particular, there is a `tEXt` chunk that can be used to store arbitrary key/value text pairs. This can be used to ship around any kind of arbitrary data you want, provided you can represent that data as text (which is fairly likely).

You will need a PNG library that allows you access and manipulate these additional chunks (such as the reference library), or you'll need to write one yourself. Then it's just a matter of choosing how to encode the data you want as key/value pairs. I'd suggest the following:

* choose key names that are prefixed with your project's name or code name as a way of creating a crude "namespace" system and avoid potential conflicts with other application's uses of the data
* don't try to store *actual* textures this way, store references to those textures that point within your game's own asset database
* data such as creature or object size, weight, et cetera -- simple scalars, basically -- can be trivially stored

---

In the interests of making a more complete answer, I'll also point out that there is another approach (previously documented by the @Vaughn and @Alexis's answers): encode the additional data you want directly in your image pixels, distributing your data across the low-order bits of the color channels. This approach doesn't require the use of extra metadata, which means you can implement it entirely without relying on it or worrying about external programs incorrectly handling that metadata. It's also got a very high "cool" factor, and because you only use low-order bits the image will still look correct to the human eye. However, it does mean your image size is a primary controlling factor for the amount of data you can store; if you need more storage you'd need to allocate more pixels to the image.

As others have pointed out, this process is known as steganography.

# Answer
> 54 votes
The developer of Monaco actually made an excellent article on how both they and Spore accomplished this.

The basic summary of what they do is fairly simple:

* Convert your data into binary
* Convert your target image into a raw bitmap
* Walk along the pixels of the image in some predictable pattern (they simply do left-to-right from the top-left corner).
* Write one bit to the lowest order bit of each color channel of each pixel
* Export the modified bitmap to png again

Simply do this in reverse to retrieve your data.

The basic idea behind the process is that there are *a lot* of pixels in an image, and the lowest order bits of each color channel don't make a *big* difference. In addition, about half of the bits you write will just be what the bit in the image already was. What you get back is essentially the right image, but with weird artifacts. He takes time to note that these artifacts are only really noticeable if you really crank the contrast/saturation and zoom in. He does have source images with lots of initial noise, though.

From the article:

> Notice in the last image how there is a barely discernible horizontal line in the noise. That's the end of the level data. What this means is that I can actually fit all level data into a 265x120 pixel image, only using the least significant bit.
>
> A TRICKY ADDENDUM:
>
> Something I could do, and I believe that the Spore folks did as well, is actually use ALL of the color bits in pixels that are 100% transparent. Since those pixels are transparent, it doesn't matter what color you set them to.
>
> I can't do this, however, since I am using the entire image, which means that I have no transparent pixels to work with.

Why favor this technique over just storing it in the metadata?

* It's funner! :)
* Services may mangle metadata (possibly as a privacy/security feature), but shouldn't mangle your png's pixels unless they have aggressive image-hosting requirements (looking at you, facebook). But if they're completely re-exporting your image there's nothing you reliably *can* do.

Extra credit: to reduce the noticeability of noise, you could use a PRNG with a fixed seed to select the pixels to modify. You could also only modify some of the color channels in a similar manner.

# Answer
> 9 votes
I downloaded and examined a few Spore creatures from Sporepedia. From those I learned that:

* The images contain no information in addition to the standard image data.
* The stenographic data have been stored with no consideration for the image, one could imagine that the transparent parts were used exclusively, but they are not.
* The storage use depend on the amount of information that needs to be stored, some of the images used only the least significant bit for data storage, some used the two least significant bits, some might use more.
* The Spore format avoids using a bit on only part of the image, the least significant bit changes throughout the whole image, if the second least significant bit is used, it is used on the whole image. This is presumably done using random padding. This avoids a shift in quality that might be more disturbing to the viewer than the noise itself.
* All four channels are used equally, the opacity channel is given no special treatment, thus some of the transparent pixels are slightly opaque while some of the opaque pixels are slightly transparent.

It is worth noting that this is just what Spore does, it is a method that puts simplicity before most other concerns.

The choice of using stenography rather than an additional data block means that the data will survive if the image is re-encoded, for instance by a website, though it will not survive scaling or Jpeg compression.

I think that the most prominent alternative is actually to only encode an id in the image, and let the actual data be stored on a central server where this id can be exchanged for the exact creature data. Such an id would be short enough that it could be encoded in a scaling- and compression-tolerant stenography format.

Possible simple improvements to the Spore format include:

* Use only or prefer using the the colour values of transparent pixels, they don't make a visual difference.
* Use the blue channel more and the green channel less, the blue colour has a lower perceived impact on the image.
* Keeping the luminance of each pixel close to unchanged and encode the data in chroma, a little noise in this parameter is virtually undetectable to humans.

---
Tags: file-format, savegame, png
---


# Question
Title: How do I know when a player has crossed a point threshold?
I’m needing help figuring out logic when adding a time bonus to my game.

I only want to reward the player with extra time if they level up.

Currently when the player’s score is less than 100 no bonus is given. If the player’s score reaches 200 I want to reward the player with some bonus time.

My issue is if the score is 190 and then jumps to 210, the 200 level mark is passed and the player isn't rewarded.

If I turn on the logic to say if the score is between 190 and 210, it could reward the player at the 190, 200, 210 mark or skip from 180 to 220, bypassing the reward altogether. I have tinkered with the idea of setting a `bool BonusFlag`, but the same issue arises, when I set the flag.

Can anyone help provide some logic on how to overcome this obstacle?

# Answer
I'm assuming you will award bonus time very some amount of points (i.e. every 100 points, starting at 200), But this can be modified to handle any type of case.

Just use integer division to check if the value has been reached and update the last awarded value when reached. For example:

```
// this value should be global scope (class member)
int last = 1;   // last score awarded for (initialize so that 100-199 is skipped)

if ( score / 100 > last )  {
   last++;      // only increase by ONE (prevents skipping values)
   addBonusTime();
}

```

The key here is that you update the "last" value when awarding bonus score. So even if the player jumps from 100 to 300, the bonus will be awarded twice - once for the 100 points to get to 200, then again for the 100 points to get to 300.
> 1 votes

# Answer
My suggestion is that there is a moment where you are going to add points to the score. Before that instant check if the score is less than the threshold AND the score + new points is greater than it.
> 0 votes

---
Tags: algorithm, logic
---


# Question
Title: How do I summarize a game idea into a short document?
I have a lot of game ideas, but never the time to work on them. I don't want to lose these ideas, so I want to 'store' them somewhere to come back to in the future. Sometimes an idea isn't really that good, and coming back would help me decide whether a game idea is worth pursuing.

I plan to keep these in some kind of catalog form. I would like to be able to capture the 'feel' of a game in as few words as possible. Even if looking back at the design a few years later, the feel and atmosphere of the game should be recoverable very quickly.

This isn't really a full design document, but something like a 'one-page' summary.

# Answer
There is likely no one, perfect way to describe & archive your game ideas. Every game designer I know would probably do it differently, but here are some techniques to consider (besides the ones provided by yourself):

## Elevator Pitch

Create a (maximum) one-page document with as little text/images as you possibly can, to communicating the absolute core of your concept. This will force you to chose your words/images carefully and think about the essence of your concept

## MDA Framework

Define your game using the MDA framework of Aesthetics (high level "feelings" the game should provide), Dynamics (major "systems" at play, as player interacts with the game) and Mechanics (low level rules and assets). The "aesthetics" part is overall feeling you want to provide, and serves to communicate the ideal end goal (feelings in the player's head) of the game, but your ideas might also dip into interestinc Dynamics. Likely you will not need to describe low level mechanics at this point.

## One-page designs

Create your game design as a single page containing a schematic, sketch, flowchart or illustration, as inspired by Stone Librande's GDC Talk on the topic. The point being that if you cannot communicate the game on one page, the idea is too complex and needs revision. There is an excellent GDC Vault talk on this subject, but it requires membership.
> 2 votes

# Answer
I don't mean to answer my own question, but trying to explain what I meant ended up so long that I might as well have put it as an answer. This is the technique I use currently, but I'm hoping someone with more experience in the industry can give a better answer.

**Elevator pitch**: Describe what the game is about in as few words as possible. Describe the genre and target market. What makes it fun and stand out from other games?

**Game philosophy**: What are features that necessarily have to be in the game to make it feel as it is? What 'feel' would players look for in sequels of the game?

Some examples would be "Can be played 5 minutes a day", "Players should be encouraged to cooperate but the mechanics can be used to settle conflicts", or "Pace must be suited to playing on online forums and email."

**Core mechanics**: Based on the philosophy, what technical components are vital to the game? On a very tight budget, which ones can be dropped? What code and programming languages are available that can do this right now and do they do the job well enough?

This part should make perfectly clear the technical and design challenges in creating the game, and cut out on the feature bloat.

**Simplest implementation**: The absolute fastest way to implement the concept and core mechanics. Can it be modded into an existing game? Which components need to be prototyped, which are tried and tested?

**Sample of play**: Similar to Dwarf Fortress's Power Goals or Stories. This is a brief rant about how cool the game would feel like. With a good enough game idea, it is inevitable to rant somewhere when describing the game, and this is left as an appendix to capture what inspired the game.
> 1 votes

---
Tags: game-design, design-document
---


# Question
Title: How do I create a Fixture in Andengine and assign it user data?
I´m following this tutorial: How do I use a JBox2D ContactListener to check if my character is standing on the ground? in order to get input from player's bottom part including a fixture in player's main body. My problem is that I´m initializing FixtureDef like this:

```
    body = PhysicsFactory.createBoxBody(physicsWorld, this,BodyType.DynamicBody,PhysicsFactory.createFixtureDef(0,0, 0));

    body.setUserData("player");
    body.setFixedRotation(true);

    // create the bottom sensor
    final FixtureDef footSensor = PhysicsFactory.createFixtureDef(0, 0, 0);
    footSensor.isSensor = true;
    body.createFixture(footSensor);

```

Now I can't do: footSensor.setUserdata("sensor") because only Fixture class has this method. How can I initialize Fixture class to be able to include a user data? Thank you.

# Answer
Take a look at the method you are using on this line:

```
body.createFixture(footSensor);

```

It returns the fixture:

```
public Fixture createFixture (FixtureDef def);

```

So the only thing you need to do is:

```
Fixture footSensorFixture = body.createFixture(footSensor);
footSensorFixture.setUserdata("sensor");

```

Also your naming convention is a bit confusing. You are calling a fixture definition "footSensor", but the defition is basically just the set of parameters, not the sensor itself.
> 1 votes

---
Tags: andengine, jbox2d
---


title: LibGDX: Miscalculated polygon collision

text:
# Question
Title: LibGDX: Miscalculated polygon collision
These 2 polygons are not colliding, though this method returns true:

```
Intersector.overlapConvexPolygons(
            new float[]{
                        100.0f, 750.0f,
                        200.0f, 750.0f,
                        100.0f, 150.0f,
                        200.0f, 150.0f
                        },
            new float[]{
                        77.0f, 695.0f,
                        91.0f, 695.0f,
                        84.0f, 681.0f
                        },
            null);

```

Am I using it correctly?

# Answer
> 1 votes
The first polygon is not convex, swapping vertex 3 and 4 solved the problem

---
Tags: collision-detection, libgdx
---


# Question
Title: Do I need to call Release() on D3D objects when I use them in another function?
For example, I have an `IDirect3DSurface9 * Surface` and `IDirect3DSurface9 *BackBuffer`.

If I were to use them directly in the `render_frame` function, I would need to release them on the `closeD3D` function. However, if I use them in a function in same file or in another .h and .cpp file, when I call `Release` in `closeD3D` it gives me an error.

So, do I not need to release them if I'm using them in a function, or am I doing something wrong?

# Answer
> 2 votes
The rules for whether or not you should call `Release` on a D3D object are simple:

It is your responsibility to *balance* your calls to functions that increase reference counts with those that decrease reference counts. Explicitly calling `AddRef`, for example, should be balanced by a call to `Release` when you are finished with that reference.

Most functions that create or get resources from somewhere implicitly increment the reference count, which means you should call `Release` when you are done with that reference to the object. The documentation for a given function will note if it does not increase the reference count.

These rules apply regardless of the function the object was created in or with, used in, and so on. They are more about the higher-level semantics of your program: generally if you allocate a bunch of resources in a startup function, you should clean those up (call `Release`) in a matching shutdown function. But if you allocate or acquire a resource temporarily within one specific function, you should release it within that function, unless you know another matching function in your codebase will be able to safely release the resource instead.

If you are getting "errors" when you move the release calls around, you've probably unbalanced the add/release reference count pairs. Or you have another sort of bug. Either way, however, "debug my code" questions are off-topic here so you'll need to resort to the old-fashioned means of problem solving: your debugger.

---
Tags: c++, directx9
---


# Question
Title: Shader that "cuts" hole through all geometry
How can I create a shader that "cuts" through all geometry, only rendering the clearing background in Unity? An example:

That's a prism in a huge white box-shaped room. The surface of the prism is just rendering the skybox of the scene (a starry sky). I used multiple cameras, which is pretty inefficient... There must be a way with just shaders.

How can I do this?

# Answer
Ok, finally figured it out!

You see how the sphere mesh “cuts” through the cylinder and plane all the way to the skybox. This took me longer than expected to figure this out but thanks to a wiki page (DepthMask) I got it all sorted.

Before using the shader setup in the wiki page I was using three different cameras with different clearing/depth flags to achieve the same result. It worked but it totally choked on the Ouya. The above solution requires only one camera and runs much fasta.

So I setup the scene like such…

1. added a realistic skybox (nasa)
2. added some shapes
3. added the SetRenderQueue script to the plane, sphere and cylinder
4. set the queue order on the sphere to 2999 (the other objects are at 3000)
5. then added the DepthMask shader to the sphere

That’s it. Any questions let me know!
> 15 votes

# Answer
Couple of options to get the effect you want - but they do come a a cost:

* Write the holes into the stencil buffer or destination alpha channel, then draw the skybox last, using a suitable stencil test or alpha blend, and with no z-test?

or

* Render the skybox to a texture at the start of the frame, and project that on to the 'hole geometry'

I suspect that there must be a way to do this by using/abusing the z-buffer, too - but you probably want to z-test the 'hole polygons' using their real Z, then write a different Z. You could probably use multiple passes and the stencil buffer - drawing the hole 3 times with renderstate set up like this might work:

* Pass 1: No z-test, Clear stencil under hole polys
* Pass 2: Normal z-test, Increment stencil value (where depth test passes)
* Pass 3: Clear Z where stencil \> 0

You'd still need to draw in a specific order - first the environment, then the holes, and finally the skybox last, though.
> 2 votes

---
Tags: unity, shaders, occlusion
---


# Question
Title: How to put basic scripting/variable changes into dialog xml files?
I have a simple XML structure for my dialog between the player and NPCs. What I'd like to do is put variable changes (and maybe other things) directly into the XML. So, for instance, if you select a certain conversation option the character gives you gold. Like this:

```
<story>
  <segment id ="1">
    <dialog>
      <speaker>Fred</speaker>
      <text>Do you like futurecrew?</text>
    </dialog>
    <choice>
      <prompt>Yes</prompt>
      <target>2</target>
      <command>$gold-10</command>
    </choice>
    <choice>
      <prompt>No</prompt>
      <target>3</target>
      <command>$relationship-20</command>
    </choice>
  </segment>
</story>

```

In exploring this issue I have written a really terrible brute force command parser, but it just feels wrong at so many levels:

```
public class Command
    {
        string commandText;
        Symbol symbol;
        Field field;

        public Command(string _commandText)
        {
            commandText = _commandText;
        }

        public void Execute()
        {

            //look for operators
            int test = -1;
            int location = -1;
            int amount = 0;

            test = commandText.IndexOf("-");
            if (test != -1)
            {
                symbol = Symbol.Minus;
                location = test;
            }
            test = commandText.IndexOf("+");
            if (test != -1)
            {
                symbol = Symbol.Plus;
                location = test;
            }
            test = commandText.IndexOf("*");
            if (test != -1)
            {
                symbol = Symbol.Multiply;
                location = test;
            }
            test = commandText.IndexOf("/");
            if (test != -1)
            {
                symbol = Symbol.Divide;
                location = test;
            }
            string variable = commandText.Substring(0, location);
            amount = Int32.Parse(commandText.Substring(location + 1));

            if (variable.ToUpper() == "$GOLD")
                field = Field.Gold;

            if (field == Field.Gold)
            {
                Logger.log("Gold before {0}", Game.Instance.Gold);

                if (symbol == Symbol.Minus)
                    Game.Instance.Gold -= amount;
                if (symbol == Symbol.Plus)
                    Game.Instance.Gold += amount;

                Logger.log("Gold after {0}", Game.Instance.Gold);
            }
        }
    }

```

If I have 30 different variables I want to "expose" to the XML "scripting" it looks like I'll be writing a lot of stupid achey breaky code.

I have searched around and found people asking/answering about conditions, which I see as simpler than this. I have also seen suggestions for CodeDom for realtime compiling but this is in unity C# so I don't anticipate that will work. I looked into LUA for .NET and IronPython but that seems overkill when really I just want the ability to change variables on my Game singleton.

Any ideas or direction would be much appreciated!

EDIT: I found UniLua https://github.com/xebecnan/UniLua for a unity safe pure c# implementation of lua. I haven't decided yet if I'll use it, but my presupposition that I couldn't use Lua turned out to be false.

# Answer
> 3 votes
Using an existing scripting language like Lua may be overkill for your needs, but on the other hand it also actually solves your needs with a minimal amount of effort wasted reimplementing the wheel. I would reconsider its use. Especially as a scripting language of this type can come handy in plenty of other places.

If you really just don't want to use Lua, another option is to build a generic `IDialogCommand` sort of thing that can be bound to a dialog file. A dialog option can include one or more commands, which are just classes that derive from `IDialogCommand`. They can include parameters marked up in the XML which are loaded into the command class instances via serialization of some form. An example XML bit might look like:

```
<dialog>
  <speaker>Palpatine</speaker>
  <text>Something something dark side.</text>
  <command type="GiveGold">
    <amount>30</amount>
  </command>
  <command type="GrantXP">
    <amount>1000</amount>
  </command>
  <command type="Effect">
    <duration>60</duration> <!-- in seconds -->
    <effect type="Stat">
      <stat>Strength</stat>
      <amount>5</amount>
    </effect>
  </command>
</dialog>

```

Using a registration manager or even just C# reflection, you can create a list of factories to use for the `<command>` elements. For instance, you might have

```
class GiveGoldCommand : IDialogCommand
{
  public int Amount { get; set; }

  IDialogCommand.Apply(Character player)
  {
    player.Gold += Amount;
  }
}

// elsewhere
DialogCommandRegister.Register("GiveGold", new CommandFactory<GiveGoldCommand>());

```

Note that such a system is essentially not actually better than using a simple sandboxed scripting language in *most* respects unless you also build a good dialog editor that naturally understands the commands and uses them to create appropriate UI for each command.

---
Tags: unity, c#, scripting
---


# Question
Title: Adding an object viewer to a Unity Editor Window
I'm wondering if its possible to add an object viewer (For example when you import an .fbx file into unity you can see a small preview of it in the inspector) to a Unity Editor Window? I've looked through the docs and didn't seem to be able to find anything for this

Thanks,

Lewis

# Answer
It isn't exactly what you're looking for, but the way I've solved this in the past is to dynamically create a camera in the editor and have it do a render to texture that I display in the editor window itself using something like GUILayout.Box with the RenderTexture in it.
> 1 votes

---
Tags: c#, unity
---


# Question
Title: How to make game sessions like "with friends" games?
I want to make a game like "words with friends" or "chess with friends" or "Draw Something" or any of the other online multiplayer type games that are based around friends having game sessions with each other. I have made one app before that had no online features so I know the basics of objective-C and xCode. I looked up facebook connect so I know how to make friends find other friends to play with through Facebook. Just not how to make the gaming session.

I only need my game to send a small array (or XML if it's better) of strings and integers from one iPhone to the other as each iPhone takes a turn. I'm NOT sending some complex video or anything like in "Draw Something."

I was hoping someone could point me in the right direction (whether link to website or book or just a general idea) for how to do gaming sessions between two iPhones. I read this tutorial http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server but it seems to be more about having two iPhones communicate over a server on a laptop or through the same wifi, not how to have iPhones game together over any Internet connection like in "with friends" games.

I've tried to research this in other places but I'm never quite sure if what the articles I find are talking about is related to what I want or not. Someone please just point me in the right direction or give me a general outline of what to do. I will look up the specifics on my own once I know what to look for. Thank you.

# Answer
> 2 votes
My guess, at least in the case of games like * With Friends, is that they host their own server and database that keeps track of turns/game states- not the either of the users phone. This way, the games persist for each user, and are harder to manipulate than if they were being computed on the devices themselves.

If I were to make a game with turns/sessions, I would set up a database with tables of players, games, and the moves within each game. I would also have some sort of authenticated API (in my case, in PHP) which would be used by the app to check the state of the game, and to post moves/changes to it.

The concepts themselves aren't necessarily game related, so not all the information you'll find on them will be either.

# Answer
> 1 votes
If you want to make a multiplayer online game then what you need is a server that the iOS devices can communicate to. So you can get your own or you can use apples game centre for your requirement.

If you are having your own server than i dont think that you are need to be told what do to then but if your using apples game kit framework then you can use these links to get your game development started and test for the desired results.

http://vivianaranha.com/integrating-apple-gamecenter-to-your-application/

http://vivianaranha.com/apple-gamekit-bluetooth-integration-tutorial/

You can also check out some really awesome tutorials from the same website's home page

http://vivianaranha.com/

# Answer
> 0 votes
I know this was asked about a year ago but let me see if i can shine a little light on the subject for anyone else trying to figure this one out. (Do not quote me on this) I believe the answer to your question is this. The "with friends" games, I believe, are actually web applications coded in html5 and js and then through a service is "downsized" and remapped for iOS and android devices. I do not remember the site I saw that did this and mentioned the company, but that would make the database and server connection easier than using Xcode or even eclipse.... thats my two cents. Not sure if right or not, but thats how I would do it if i were to make something like this.

---
Tags: networking, iphone, multiplayer, cocos2d
---


title: Aspect ratio in LibGdx

text:
# Question
Title: Aspect ratio in LibGdx
I'm learning LibGdx and I need some help with the camera.

Let's see, I'm making a Chu Chu Rocket! clon to start. I've loaded a TiledMap (10x10), and I've created an OrthographicCamera to show the map. This is my camera code, written in the Map class constructor, which is invoked in the create() method:

```
map = new TmxMapLoader().load("data/maps/" + filename);
renderer = new OrthogonalTiledMapRenderer(map, 1.0f/24.0f);
camera = new OrthographicCamera();
camera.setToOrtho(false, 10, 10);

```

And this is the result, when I compile

The problem is that the tiles I used in Tiled were squares. When I load, as you can see, they're rectangles. That's a problem for me.

I've read some things about resizing, changing aspect ratio, etc, but everithing was about doing it to fit various devices resolutions / screen sizes. So, my questions are:

* How to define correctly the aspect ratio for a tiled map using a ortographic camera?
* When I do that, the ratio will be correct for every device?
* The elements which aren't the map (like the mice) would need to be also adjusted? How?

Thanks for your answers.

# Answer
What your dealing with is an aspect ratio mismatch. Your trying to map an aspect ratio of 1 to an aspect ratio of 16:9 or 16 :10. That is why your tiles look stretched. Set your games resolution to a square aspect ratio like 300x300 if windowed. Or make your tiles about 160x90 pixels to look square at that resolution.

Topics of interest would be http://en.m.wikipedia.org/wiki/Aspect\_ratio\_(image) and http://en.m.wikipedia.org/wiki/Field\_of\_view\_in\_video\_games.
> 1 votes

---
Tags: libgdx, tilemap, resolution, screen, aspect-ratio
---


# Question
Title: Games with simple graphics like Dots or 2048?
I want to try making an Android game, but I'm bad at making graphics. I want to make a game with very simple graphics and I'm looking for inspiration. What are some games like Dots or 2048?

# Answer
I think best way to find inspiration would be to look through android store (if you only want to prectise code and not sell it). Some I can think of:

Hundreds

Lazors

7x7

Pong

Any Pool/Snooker etc

Chess

Tic Tac Toe

Bowman

---

edit:

UnBlock Me

Tetris?

Breakout
> 1 votes

---
Tags: 2d, android, mobile
---


# Question
Title: When is messaging/observing preferable to 'built-in' functionality in game objects?
In working on a Python/Pygame project I recently came to an impasse which couldn't be solved elegantly via my previous methodology - using wrapping functions as an Observer pattern - and it was impressed on me to look at some kind of event system instead.

As an example:

```
class Player(sprite):
    ...
    @property
    def lives(self):
        return self._lives
    @score.setter
    def lives(self, new):
        old = self._lives
        self._lives = new
        self.fire_event(LifeChanged(self, old, new))
    ...
mainchar = Player()
scoreboard = Scoreboard()
scoreboard.listen_for(LifeChanged, scoreboard.on_life_changed)

```

So this was literally the only thing in-game that I felt I 'needed' to handle in this way, and while I prefer it to calling `scoreboard.text = mainchar.lives` in every loop, it gives me a bit of pause because at present it is pretty much the only thing I'm using events to manage.

I realize that a lot of this stuff is by-preference, and I'm not looking to refactor my entire game here or get a breakdown of why MVC/Entity Systems/whatever is preferable, but it did raise a question for me regarding the practice of objects that create objects. The simplest example being something like a character which fires projectiles:

```
def fire(self, shot_direction):
    newshot = Bullet(self.rect.center[0], self.rect.center[1], shot_direction)
    newshot.add(self.groups())

```

Again, it may just be an implementation detail, but it does start to "feel like" a better way is to send a message to a `Bullet` factory instead of letting the object doing the firing instantiate the `Bullet` *and* add it to `Sprite.group` instances that it happens to belong to. After all - why does my `Player` object need to 'know' anything about the groups it belongs to, or have the responsibility to add things to a game object that is more or less not part of the game action?

I could be overthinking all the things -- I do that. :/ But I'm genuinely curious as to whether or not there is a fundamental consensus on 'best practice' (regardless of design patterns) that dictates whether or not game objects should be doing the creating of game objects directly, or whether there should instead be a factory sitting in the background somewhere that churns out all instances of new bad guys, projectiles, powerups, and so on.

# Answer
> 1 votes
The way I see it is, don't stick the hooks in for something that will give you no benefit. Write your code in the simplest possible manner first, which almost always means "hard-coding" some things like the sprite group snippet you mentioned. If you come across some new change or requirement that would benefit from the factory, then by all means, write it, but don't write it until you need it. Note that I'm not advocating eschewing *all* abstractions out of the gate - rather, just the ones where there's no recognizable benefit.

In other words, YAGNI.

---
Tags: python, design-patterns, pygame
---


# Question
Title: How to use blender files in your own engine?
It is not trivial to use your own shader on blender, so I've created a good-looking webgl shader. Now, what do I need to use the things I made in blender on it? An obvious first idea would be to parse the blender format. For that, I need to know it's specification: what does it include? Meshes? Bones? Animations? Vertex colors? What else? But I guess there could be easier paths, though. Maybe an exporter from Blender to an easy-to-understand JSON format exists? So that is my question, what is the fastest path to use blender files with my webgl renderer?

# Answer
This is going to depend on what you want to work with. Blender has an export feature which will allow you to export the models into several formats. If you want to write a customer parser, there are a few for various formats. You mentioned WebGL, which makes me think you're going to be working with JavaScript. With this in mind, Three.JS has some built in loaders you could use:

Source

With this in mind, you could use Blender to export to several of these, such as Collada, JSON, or OBJ. Just research the method you want to use, such as OBJ.

If you want to write your own loader, you can find documentation on these more popular formats all over the web:
> 2 votes

# Answer
The easiest approach is probably going to be exporting to COLLADA. Blender comes with a COLLADA exporter out of the box, so you'll just have to import the COLLADA XML data into your own data structures.
> 1 votes

---
Tags: 3d, shaders, animation, rendering, webgl
---


title: What path finding algorithms are there?

text:
# Question
Title: What path finding algorithms are there?
I'd like to read up on path finding algorithms. Is there a primer available or any material or tutorials on the Internet that would be a good start for me?

# Answer
If you're looking to research and learn about pathfinding in general, I'd definitely suggest learning more than just one algorithm. You'll want to understand the overall concepts but be able to apply them to whatever it is you are working on. Most game developers who need to do any serious pathfinding end up writing their own custom algorithms, although highly based on known solutions, every game is different and will have different requirements.

I'd start by reading up on some of the more well know methods like A\*, Dijkstra's Algorithm, Depth and Breadth-First searches. There's a lot of good information on the internet on each of these. (http://en.wikipedia.org/wiki/Pathfinding)

While reading them, take note on what the upsides and downsides are to each approach, as well as the type of data the algorithm can operate on. Can it be applied to 3-dimensional paths? Can it be modified to account for our human AI who wants to avoid the landmines in the map?

When it comes to pathfinding, A\* is pretty much the golden ticket that everyone uses. You should definitely know how it works. (http://en.wikipedia.org/wiki/A\*\_search\_algorithm)

Here's a good example of A\* as it applies to an RTS game, which needs to take entities of different size into account: http://aigamedev.com/open/tutorials/clearance-based-pathfinding/

Good luck!
> 34 votes

# Answer
Pathfinding algorithms are basically a graph search problem solving algorithms.

http://en.wikipedia.org/wiki/Pathfinding#Algorithms

Most known being Djikstra's algorithm: http://en.wikipedia.org/wiki/Dijkstra's\_algorithm

and its variant A\* search algorithm: http://en.wikipedia.org/wiki/A\*
> 22 votes

# Answer
This is a great beginning resource that takes a look at all aspects of path finding in a very easy to digest approach.

***Amit’s Notes about Path-Finding***

> ... Pathfinding addresses the problem of finding a good path from the starting point to the goal―avoiding obstacles, avoiding enemies, and minimizing costs (fuel, time, distance, equipment, money, etc.). Movement addresses the problem of taking a path and moving along it. It’s possible to spend your efforts on only one of these. At one extreme, a sophisticated pathfinder coupled with a trivial movement algorithm ...
> 14 votes

# Answer
There's a good list on Wikipedia: Pathfinding

As far as I know, A\* and D\* are both pretty popular.
> 5 votes

# Answer
Pathfinding is a pretty solved problem... as mentioned in almost every answer here, some variation on A\* is going to be what you use.

The bigger challenge to me, is how you want to represent your *path*. Using a grid, pathnodes, navmeshes, hierarchical grids or other complex structures, etc.

I don't have any specific references in mind, but exploring AIGameDev will give you all kinds of ideas as to what's out there.

Just remember that each representation has its pros and cons; it's not about finding the 'best one', it's about finding the one that is the best fit for *your gameplay*.
> 5 votes

# Answer
There are several path finding algorithms out there.

One of the most popular ones is probably A\* (A-Star). It's a very useful algorithm if you have a heuristic function that can give you estimated costs to reach a goal (example would be the line-of-sight distance to the target). A\* is very useful to find the shortest path from a start to an end point.

Other than that there's also Dijkstra's algorithm which is very useful to find the nearest item out of several items. Eg. if you want to find out which power-up (or similar) is closest to your gaming character.

There are several other algorithms out there, but I guess A\* is by far the most popular one. Mat Buckland has an excellent chapter about Path-Finding in his Book *Programming Game AI by Example*. I strongly encourage you to get a copy of it. Otherwise you'll find loads of information online by searching for "A Star search".
> 4 votes

# Answer
Here's a tutorial on using Dijkstra's Algorithm for pathfinding.
> 3 votes

# Answer
Here is a good example of A\* being used in a game with some psuedo code: http://www.anotherearlymorning.com/2009/02/pathfinding-with-a-star/
> 3 votes

# Answer
This isn't much of a primer, but we discussed graph algorithms extensively in our algorithms class last Fall 2009. We used this book,

Introduction to Algorithms, Third Edition by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein

http://mitpress.mit.edu/algorithms/

and it also has accompanying youtube lectures from an MIT class.

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/video-lectures/

Chapters 17, 18, and 19 dealt with shortest paths.
> 2 votes

# Answer
See \[Graph and tree search algorithms\] on Wikipedia. They are pretty much just a variations of State Space Search, You just have to go trough all of these and find where they differ.

There is also Collaborative Diffusion, which is one of previously mentioned algorithms done interesting way.
> 2 votes

# Answer
This one looks interesting:

http://www.codeproject.com/Articles/455 I wonder is it better than A\*?
> -2 votes

---
Tags: algorithm, path-finding
---


# Question
Title: How do they made Pokémon games so flawlessly balanced?
I find it hard to believe how well balanced the Pokémon games are. Not just within the games, where you'll find amazing balance from the very beginning to the very end, but, surprisingly, even when things get more competitive. If you have ever played the simulators that are available, you'll know what I'm talking about www.smogon.com. There are thousands of unique Pokémon characters, moves, traits and items. Yet, if you try to find a single broken strategy, You can't. And if you do find something obscure that could give you a good advantage, you'll realize it's impossible. The emerging competitive scenario is one of the most amazing strategy games I've ever seem, and it's not even a feature of the Pokémon games!

# Answer
I highly recommend you to check this AltDevBlog article on the very same topic. It basically says that the balancing process can be automatized to some point in a mathematical way.

http://altdevblog.com/2012/02/17/the-craft-of-game-systems-tuning-rpg-content/
> 19 votes

# Answer
Any game requiring strategy requires many iterations to get right. Having worked on multiple games that required balancing, I've learned that you start extremely early during production on the creation of different rules and abilities and immediately start balancing them.

There is no "silver bullet" that will guarantee a well-balanced game. Each time a new ability is created you must weigh it against your existing set to make sure there will be little to no chance of exploiting with it.

The Pokémon card game, specifically, is a relatively simple strategy game in terms of what the abilities do compared to a card game like Magic: The Gathering. Many of the Pokémon abilities do damage only, others just apply poison, or some other simple thing related to damage. You can only have two cards in the "active" position for combat. Compare this to magic where you can have a whole field of cards that can attack, many cards respond to events that occur, cards in hand can interrupt other actions. Long story short, some games are much easier to balance than others based on the range of abilities a player has at their disposal, and for most strategy game there's no way to cover every possible case without plenty of testing and iteration, reworking things until they feel fair and still fun.
> 14 votes

# Answer
Actually, I'm going to go against the crowd here.

**Pokemon is horribly broken.**

What? Why is that? Well, let me explain...

Pokemon has had a lot of things that have been built up over time and a lot of modifications to make it more suitable. There's a lot of Pokemon that are just useless, weak or otherwise not useful. In fact, due to this fact many Pokemon have to be classified for many tournaments that are hosted. **Note: Nintendo does not ban any Pokemon in official matches.**

These are community vetted because Nintendo has failed to fix THESE exploits. Thus, it is important to note and study why these occur. You make the claim that these simulators are well balanced, and that's because they are... with constraints. These simulations are iterated over and occasionally someone DOES find a broken team combination. When this happens, the community blacklists and creates rules around it. This happens **frequently**.

So, how many Pokemon are in each tier and what? Well, this diagram provided by Smogon (typically respected and used frequently) shows, as of today:

Smogon says,

> Smogon's tier system is used to rank Pokemon into several groups based on their perceived power and usage in competitive play. These tiers dictate which Pokemon can be used in the various metagames of competitive play. Each metagame encompasses different Pokemon, and therefore each one is unique in its style of play. The standards set by Smogon's tier system seek to balance competitive battling, ensuring no Pokemon is "too powerful" or over-centralizes the metagame it appears in. This allows players the flexibility to show "flair" in their team design rather than being restricted to using a particular Pokemon to win.

To summarize, the higher tier Pokemon are stronger than those used below. Thus, when playing in a "Little Cup" match, it is respected that Pokemon in above tiers will not be used. This is because Pokemon in above tiers are usually considered broken in comparison. Especially those in the **uber** tier.

**Bans and Clauses**

Then, we have the banlist and Pokemon clause lists. These are certain rules that are enforced during community battle because they been deemed to be broken by the community. You can read about most of them here, but I'll highlight some of them that are very broken.

**Sleep Clause.** Basically, this states two Pokemon cannot be put to sleep at once. If you're familar with the game, this becomes obvious why.

**OHKO Clause.** This one is a bit easier to understand without game knowledge. Essentially, these are moves that can kill any opponent in a single turn, based on luck. These are banned because they take the skill out and can let any unskilled opponent win a match with fairly good odds.

**There are many more reason Pokemon is broken, but in conclusion Pokemon is not balanced in the slightest.**
> 9 votes

# Answer
While I've been out of the competitive pokemon scene for a while, when I left it was anything but balanced; if you didn't run legends, there was no point in even trying. And bugs? get out of town.

Looking over smogon, it seems things have changes (sycther good? wut?). So it seems balance was achieved the good old fashioned way; lots of iteration. Introduction of new systems, and insuring nothing got to out of hand.
> 3 votes

# Answer
it is way too expensive wat u mean by balanced game. the pokemon and star wars wiki are designed in such a way that the database of complete storyline occurs as many pages in the site. look at the details in serebii.net *website* the bulbapedia also provides such drastic explanation.The only reason why this might be true that a balance of moves and types of pokemon are made an instance in the game rather than individual pokemon. looking at the design code every pokemon is managed by its type and the type of its attack so what so ever is its type a tm move advantage will also occur. so the perfect answer to your question is that pokemon games include diversity classification based on group methods rather than individual intances belonging to various groups.This is the reason why theese become so balanced
> -4 votes

---
Tags: game-design, game-mechanics, balance
---


# Question
Title: How to keep track of previous scenes and return to them in libgdx
I have three scenes: `SceneTitle`, `SceneMenu`, `SceneLoad`.

(The difference between the title scene and the menu scene is that the title scene is what you see when you first turn on the game, and the menu scene is what you can access during the game. During the game, meaning, after you've hit "play!" in the title scene.)

I provide the ability to save progress and consequently load a particular game. An issue that I've run into is being able to easily keep track of the previous scene. For example, if you enter the load scene and then decide to change your mind, the game needs to go back to where you were before; this isn't something that can be hardcoded.

Now, an easy solution off the top of my head is to simply maintain a `scene stack`, which basically keeps track of history for me. A simple transaction would be as follows

1. I'm currently in the menu scene, so the top of the stack is `SceneMenu`
2. I go to the load scene, so the game pushes `SceneLoad` onto the stack.
3. When I return from the load scene, the game pops `SceneLoad` off the stack and initializes the scene that's currently at the top, which is `SceneMenu`

I'm coding in Java, so I can't simply pass around Classes as if they were objects, so I've decided implemented as enum for eac scene and put that on the stack and then have my scene managing class go through a list of `if` conditions to return the appropriate instance of the class.

How can I implement my scene stack without having to do too much work maintaining it?

# Answer
Your idea seems fine. A short stack of screens would let you transition into and back out of a menu without any problem. But the way you've described your problem is really odd. You plan to create a new screen instance while popping off your stack? That would defeat the purpose have having a stack of screen instances. You only need new instances when adding to the stack, not when moving back down.

While moving into new screen, i.e. pushing onto the stack, you do need to create new instances of screens. But since that process will happen only as a result of interaction with any given screen, you can simply define code paths that instantiate the correct screen type. For example, selecting load from the menu executes a specific function. That function's purpose is solely to initialize a loadscreen instance and push it onto the stack. This screen instance's type is defined in the code, so no reflection or enumeration/switch required.

When you do that, the menu screen is put on hold (however that works for your project), but it isn't destroyed. It remains on the stack, and can be reactivated. So your dilemma of needing to pass around class definitions seems moot. When moving backward through screens, pop off the current screen (probably destroy it), and activate the screen below it. Perhaps you need to define some reset logic for reactivation, but that is better than creating a new instance in the manner you described.
> 1 votes

---
Tags: java, libgdx, scene
---


# Question
Title: OpenGL: missing GL_SPECULAR light on the texture
I'am missing specular lighting on the texture. I have `#include <GL/glext.h>` in the project, so basically I used `glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SEPARATE_SPECULAR_COLOR_EXT);` for specular effect. My init code:

```
glEnable(GL_DEPTH_TEST);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_CULL_FACE);
GLfloat AmbientLight[]   = {  0.3,  0.3,  0.3,  1.0 };
GLfloat DiffuseLight[]   = {  0.7,  0.7,  0.7,  1.0 };
GLfloat SpecularLight[]  = {  1.0,  1.0,  1.0,  1.0 };
GLfloat Shininess[]      = { 90.0 };
GLfloat Emission[]       = {  0.0,  0.0,  0.0,  1.0 };
GLfloat Global_Ambient[] = {  0.1,  0.1,  0.1,  1.0 };
GLfloat LightPosition[]  = { 7.0, 7.0, 7.0,  1.0 };

glLightModelfv(GL_LIGHT_MODEL_AMBIENT, Global_Ambient);
glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularLight);
glLightfv(GL_LIGHT0, GL_POSITION,LightPosition);

glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION,  0.05f );
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION,    0.03f );
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.002f);

glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, AmbientLight);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, DiffuseLight);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, SpecularLight);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, Shininess);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Emission);

glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);

```

My render code:

```
glClearColor( 0.117f, 0.117f, 0.117f, 1.0f );
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// load texture
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_LIGHTING);
glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SEPARATE_SPECULAR_COLOR_EXT);
glColor4f(1.0, 1.0, 1.0, 0.2);
glDisable(GL_COLOR_MATERIAL);
// render geometry here
glFlush();

```

What is missing here?

# Answer
OK! I got it... The problem was that my program was using old dll `opengl32.dll` that was located in the same folder. After removing the old dll the rendering context automatically switched to the local dll's: `atioglxx.dll` for AMD and `nvoglv32.dll` for NVidia. So basically now the `glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT, GL_SEPARATE_SPECULAR_COLOR_EXT);` is working as it should. Thank you for your interest.
> 0 votes

---
Tags: opengl, textures
---


# Question
Title: How can a game engine's renderer be visually compatible with Maya's?
Say you create some model in say Maya, you apply all kinds of effect to the model and then export the file. Then the game engine has to load the file and render it, so surely the game engine needs the same renderer as Maya's to reproduce the effects created in Maya?

# Answer
> 4 votes
Most professional modelers have little expectation that the model in-game is going to look exactly like it does in Maya. The engineers have a very strong responsibility to provide tools for very quickly visualizing models using the game's rendering engine.

This may be by allowing models to be re-loaded in game so there's no long shutdown/startup process to see the model in its final environment, which of course is significantly more valuable than simply visualizing the model by itself.

The needs may be satisfied by creating a model previewer using the engine. Thus the artist can at least see how the model and its animations will work using the engine's tech. The viewer needs a lot of options to control lighting and environmental parameters so the artist can mimic the actual environment(s) the model will be used in.

Another option is to write a plugin for the modeling tool (Maya, whatever) that embeds the engine and allows the artist to work in real-time against the actual final output. Again, environmental controls are critical. I haven't seen this approach used in a while, but it wasn't uncommon a decade ago. Stand-alone previewers that automatically convert and reload models when they're modified are simpler and about as productive, though.

Larger and more complete engines usually offer both of the first two solutions.

Short version: the modeling tool's rendering should never, ever be expected to match that of the game and an artist needs tools to visualize what the actual output will be quickly and efficiently.

# Answer
> 1 votes
> so surely the game engines needs the same render as Mayas to reproduce the effects created in Maya?

They don't need to be the same, only the results need to be the same. Since you seem to think Maya's the reference, you can call what you see in Maya the *expected result* of a renderer rendering what is contained in the model.

Break the renderer's stuff in two parts: **implementation** and **output** (or result). In order for the game engine to provide the same effects as Maya does when displaying the model, the **output** of both needs to be the same. However, the implementation can vary. It may be possible to get to a result in two different ways, and it may be possible that Maya's developers chose one of the ways, and, say, Unity's developers chose the other one.

# Answer
> 1 votes
3D modeling software packages like Maya usually include a great variety of options for rendering. For instance, Maya itself includes several software and hardware-accelerated renderers, and 3rd party renderer plugins can be used. Different renderers have different features and support different effects, but for the most part, they're designed for high-quality, *non-realtime* rendering.

Rather than try to make an engine which supports all the myriad of advanced effects you could create in a 3D modeling package, the options are either to create a plugin for your 3D editor which will render objects as they would appear in your engine, or more commonly, to use an external tool or editor built especially for your engine which imports the asset, converting it to whatever engine-specific format you're using, and lets you edit engine-specific material properties, use custom shaders, etc.

---
Tags: maya
---


title: Data Locality and Polymorphism

text:
# Question
Title: Data Locality and Polymorphism
I've been reading over the various chapters available at http://gameprogrammingpatterns.com, and in particular his chapter over Data Locality(http://gameprogrammingpatterns.com/data-locality.html) has raised a few questions. I've sent him out an email, but while waiting for it I figured I'd gather the opinions of others.

In the chapter, it is suggested that you would take your GameEntity class and strip everything away, sticking all of the components into an array and using a dirty bit to tell whether or not the component is active. This allows for faster iteration and avoids thrashing the cache.

However, it is also stated to avoid polymorphism in order to keep all components of some type the same size, and avoid virtual methods. Rather, for every type you would have an array. To me, this sounds wasteful. Say I have 20 different enemies, and I allow for 100 enemies to exist at a time. That'd be 21(20 different MOBs + 1 array that would hold the entity) arrays of 100 entries, so 2100 objects just for the different enemies. And then each enemy needs a physics component, a rendering component, and maybe even more depending on the game. If every enemy needs it's own physics and rendering component, that'd be 21 Entities + 20 Physics Components + 20 Rendering Components, all multiplied by 100(or however many entities you are allowing to exist at once). That's a lot of data for stuff that isn't going to even be used most of the time.

Wouldn't it be simpler(and smarter) to just have arrays of the base class, then stick in the needed subclass at some index? The base class would hold all the data that would need to be accessed by any of the subclasses, the subclasses would only have an overloaded Update() function. Yeah, it'd be a bit slower because then the program would have to look at the vTable over and over again to figure out which Update() function to use and not all the data in the base class will be used by every subclass, but it sounds simpler and faster than having 100+ arrays, each with 100+ members, when a large portion of them aren't even being used at any given moment. Are there any downsides to my take on it? Am I missing an important concept of data locality? What is your take / what would you do?

# Answer
> 1 votes
> Wouldn't it be simpler(and smarter) to just have arrays of the base class, then stick in the needed subclass at some index?

This doesn't work. Child classes are likely to be a larger size than the base class, since child classes usually add some new data members. If you have an array of a base class (which is, say 32 bytes in size) you can't fit a child class (which is larger than 32 bytes) in the array elements.

You'd have to store *references* to the object instances in the array (or pointers). Using references does not give you data locality since the actual instances still end up spread out over memory and iterating over the array requires you to do "pointer chasing" to actually access the data in each object.

You could make an array full of over-sized entries big enough to hold any child of the base, but then smaller base classes put into the array are spread out unnecessarily in memory. This means you retrieve less useful data in each cache line request and your overall memory access times suffer.

There are many options to avoid waste. One is to allow your array of components to be resizeable in some fashion. If you use a plain resizeable array, you'd want to store indices rather than direct pointers to the elements of the array. You could also use a chunked approach in which you allocate new pages of memory when the "array" grows and then keep an array of the pages making up the "array." This allows you to efficiently iterate over the elements of the container, more or less with the same efficiency as a completely contiguous array, but it allows you to grow the array without needing to copy/move all the elements whenever it does grow.

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