title: RenderTarget2D moves with scene

text:
# Question
Title: RenderTarget2D moves with scene
I encountered a strange RenderTarget issue, in XNA/Monogame.

I am currently updating my render target at every frame, just to test to see what is happening. When I move the camera around, the positioning of the drawing inside of my rendertarget moves as well.

Notice in the example, how the image moves inside of my render target:

Here is the code for the Render Target draw:

```
GraphicsDevice.SetRenderTarget(Render);
RoundLineManager.Draw(Branches.GetAllObjects(), new Color(102, 50, 18), Matrix.Identity * Camera.View * Camera.Projection, RoundLineManager.TechniqueNames[0]);
SpriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null, null, null, Camera.View);

foreach (Pool<Leaf>.Node l in Leaves.ActiveNodes)
    if (l.Item.Visible)
        l.Item.Draw();

SpriteBatch.End();
GraphicsDevice.SetRenderTarget(null);

```

Here is the related Camera properties:

```
public Matrix View
{
    get
    {
        return Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f + shakeOffset.X, ViewportHeight * 0.5f + shakeOffset.Y, 0));
    }
}

public Matrix Projection
{
    get
    {
        return Matrix.CreateOrthographicOffCenter(0, Infinidrill.GraphicsDevice.Viewport.Width, Infinidrill.GraphicsDevice.Viewport.Height, 0, 0, 1);
    }
}

```

# Answer
Ok, it was my View property of the Camera class that was causing it. Really tired today, ugh. Here is the updated code:

```
public Matrix View
{
    get
    {
        return Matrix.CreateTranslation(new Vector3(GraphicsDevice.Viewport.Width * 0.5f, GraphicsDevice.Viewport.Height * 0.5f, 0));
    }
}

```
> 1 votes

---
Tags: xna, monogame, rendertargets
---


# Question
Title: Downsides of using this integration formula for movement?
So I read that Gaffron integration basics tutorial and noticed how the Euler integration method gives a small error over time. I implemented the RK4 and noticed that with constant acceleration, I could simplify the formula. Over the course of an hour with some use of wolframalpha, I noticed that the formula eventually just simplifies down to just this:

```
float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;

Position += (0.5f * Acceleration * dt + Velocity) * dt;
Velocity += Acceleration * dt;

```

I ran it through a console and sure enough, it gives the proper values for each timestep and the correct final value.

Will this formula always yield perfectly accurate answers? My acceleration will always be constant. Is there a name for this formula?

# Answer
> 2 votes
You've discovered the equation for constant linear acceleration. This equation is used in situations of uniform acceleration to determine final position and velocity.

Essentially you start with your acceleration and integrate with respect to time to get the equation for velocity and integrate that for the equation for position.

```
a = a  //Acceleration
v = v0 + a*t  //Initial velocity + acceleration times time
s = s0 + (a*(t^2))/2 //Initial position + one half acceleration times time squared

```

If you always have constant acceleration, you can use this equation at any time to calculate the position and velocity. It should give accurate results if you're calculating from the beginning every time. You can introduce small amounts of error when adding subsequent calculations like you're doing with `+=` in your code example.

However, many times errors are introduced when you have an acceleration that changes, like when dealing with gravity.

The downsides of using constant acceleration is that it's typically not very interesting. You're very limited to how many things you can use it for.

Typically people will use these equations in very small fixed time steps with changing acceleration to calculate the position and velocity of objects.

---
Tags: xna, c#, physics, movement
---


title: How do I multiply two RGBA colours?

text:
# Question
Title: How do I multiply two RGBA colours?
I have two RGBA integers. What procedure should I perform on them to return the multiplied colour? Do I need to split the RGBA integer into its component integers (R, G, B, A)?

I'm using this for a lighting engine.

# Answer
Convert them to the normalised space:

```
float r1 = color1.r / 255.0f;
float g1 = color1.g / 255.0f;
float b1 = color1.b / 255.0f;
float a1 = color1.a / 255.0f;

float r2 = color2.r / 255.0f;
float g2 = color2.g / 255.0f;
float b2 = color2.b / 255.0f;
float a2 = color2.a / 255.0f;

```

and them multiply them:

```
float r3 = r1 * r2;
float g3 = g1 * g2;
float b3 = b1 * b2;
float a3 = a1 * a2;

```

to convert back to the 0-255 range:

```
Color color3 = new Color();
color3.r = r3 * 255;
color3.g = g3 * 255;
color3.b = b3 * 255;
color3.a = a3 * 255;

```

this is the correct procedure to multiply two colors.

EDIT: Thanks for Petr Abdulin for pointing out: You can use some math here and simplify the calculation:

```
color3.r = (color1.r * color2.r) / 255;
color3.g = (color1.g * color2.g) / 255;
color3.b = (color1.b * color2.b) / 255;
color3.a = (color1.a * color2.a) / 255;

```

Explanation:

```
c3 = ((c1 / 255) * (c2 / 255)) * 255; //multiply fractions
c3 = ((c1 * c2) / (255 * 255)) * 255; //multiply fraction with whole number
c3 = (c1 * c2 * 255) / (255 * 255)); //cancel 255 on top of fraction with 255 on bottom of fraction
c3 = (c1 * c2) / 255; //final result

```
> 4 votes

---
Tags: java, lighting, color
---


# Question
Title: Is it Possible to create one equipment piece, and handle the manipulation programatically
I have a 2D game made in XNA-4.0. I am brainstorming on how to implement a system of equipment where I can draw one Texture, and rotate/scale it to my character's current animation without haveing to create a seperate Atlas for each Weapon/Gear Piece.

Right Now I have a Default Character Sprite Sheet that I use, and For each Item I wish to incorporate into the game, I draw it onto the Sprite Sheet, remove the character from the sprite sheet, then draw the new Sprite Sheet with just the visible parts of the given piece of equipment. It works very well, and looks great... The only problem is that It requires a lot of work for each piece of gear I implement into the game.

Originally my hope was to Create one image, and have a system in place that can alter the texture as required to rotate and move with my hero's animations. Since I am in 2D, I am restricted to Scaling and rotation images.

Is this goal of creating one image even a possibility? If so I would love any direction to as how this might be achieved.

# Answer
> 1 votes
If you are doing a classic 2d platformer (which you \[the OP\] are not \[this answer is directed at people who are doing it\]) then you could use something like DragonBones (open source). Even in your situation, you could make some considerations and implement something like this.

If you must have the tool look perfect from a lot of angles and can't compromise on the variety of angles and authenticity then you need to make the animation in 3d, attach the tool to the animated model and render away (this of course would result in the texture atlas you wanted to avoid).

To get one image of a 2d tool looking good, you have to keep it bound to one plain. This means it cannot be moved very freely and will only look good when it's viewed from the side while most 2d rpg let your see the character from 4 - directions, this looks best when you can see the character only from the left or the right side of it.

You can also make one tool of each type, i.e sword, staff, mace and etc. , then use different color color palettes to get multiple similar but slightly different results.

---
Tags: xna, 2d, sprites, rpg
---


title: 2D physics collision/gravity problem?

text:
# Question
Title: 2D physics collision/gravity problem?
I'm using Love2D and my own physics engine to create a 2D platformer. Y collision works fine, but X collision... well, it's a bit buggy. When I move off of a small platform I've created, I fall but it is a lot slower than what my gravity is set to. Here's my code for collision:

```
function world.collisionCheck(o)
    for k, v in pairs(world.objects) do
        if v ~= o then
            if v.Type == "Rectangle" and o.Type == "Rectangle" then
                if o.Position.Y + (o.Size.Y / 2) > v.Position.Y - (v.Size.Y / 2) then o.Velocity.Y = 0; o.onGround = true; end
                if not (o.Position.X + (o.Size.X / 2) > v.Position.X and o.Position.X - (o.Size.X / 2) < v.Position.X + (v.Size.X)) then o.onGround = false; end --right left
            end
        end
    end
end

```

As you can see, it's pretty bad. The code for the actual physics (gravity, movement, etc.) is a bit better:

```
function world.update(t)
    for k, v in pairs(world.objects) do
        if v.Static ~= true then
            v.Position.X = v.Position.X + v.Velocity.X
            if v.onGround == false then if v.Velocity.Y < world.Gravity then v.Velocity.Y = v.Velocity.Y + world.Gravity * t end end
            v.Position.X = v.Position.X + v.Velocity.X * world.Meter
            v.Position.Y = v.Position.Y + v.Velocity.Y * world.Meter
            v.Velocity.X = v.Velocity.X * world.Friction
            world.collisionCheck(v)
        end
    end
end

```

However, it could still use some work. Whenever I step off of a 150 pixel by 15 pixel platform, I fall a lot slower than 9.8 meters per second. My meters are set to two pixels, and I'm falling at about a meter per second, which is much slower than the expected ~20 pixels per second I get while still on the platform. Everything I've tried doesn't seem to fix it; there's no problem in the movement code, and nothing I change in the collision code seems to fix it. Is there some silly problem I've overlooked?

EDIT: Okay, so I implemented a small fix which somewhat solves my problem. I modified the collision code so that it checks if it is below what is being tested for collision, and it seems to accelerate as normal when the top of the object is below the object being collided with, and vice versa. Am I correct in assuming I just need to add something to detect if the x-value is in the correct range, too?

# Answer
Regarding your gravitation/acceleration physics, here's your code again with a bit of reformatting:

```
function world.update(t)
    for k, v in pairs(world.objects) do
        if v.Static ~= true then
            v.Position.X = v.Position.X + v.Velocity.X
            if v.onGround == false then
              if v.Velocity.Y < world.Gravity then
                v.Velocity.Y = v.Velocity.Y + world.Gravity * t
              end
            end
            v.Position.X = v.Position.X + v.Velocity.X * world.Meter
            v.Position.Y = v.Position.Y + v.Velocity.Y * world.Meter
            v.Velocity.X = v.Velocity.X * world.Friction
            world.collisionCheck(v)
        end
    end
end

```

I see a few problems here:

* `v.Position.X = v.Position.X + v.Velocity.X` is missing a "t" behind the velocity.
* You compare `v.Velocity.Y < world.Gravity` which might be what you want "number-wise", but it's not physical. A velocity is not an acceleration (which gravity is), and thus cannot be compared with gravity. You can introduce a `steadyStateVelocity`, though, which seems to be the intention of your code.
* Simply "cutting off" the velocity while falling is probably not a good idea either. You can introduce friction here just like for `v.Velocity.X` (`world.Friction`). Should friction actually a property of "world"? (imho it should not, even in games)
* Your modeling of friction is a bit odd. Usually friction is modeled as F = k\*v, with a friction force F acting on a body, a drag coefficient k and the velocity v. This is just one of a few forces acting on a body, at least gravity should be included as well. You can adjust k to be velocity dependent, which is pretty close to what is done in fluid mechanics (simplified). The sign of k should be negative in order to result in drag, or simply take -k if you want to use positive values for k.
> 1 votes

---
Tags: collision-detection, physics, love2d
---


# Question
Title: Designing a weather system for biomes in a roguelike
I'm making a roguelike game similar to dwarf fortress. So far, I have an average temperature map and average yearly precipitation map generated with simplex noise. Now, I'm trying to implement a weather system that seems realistic, as in it rains more often in biomes with higher precipitation rates, but still seems coherent.

Some of my thoughts on designing this system would be to have a weather object for each individual biome, and every time it rains (and the startup) it picks the next time it will rain based on the biomes precipitation rate.

One problem with this approach is that it would always rain within the exact edges of a biome, and I don't think it would look very realistic.

Another option could be to have cloud objects move around the map, and have them pick up water while in biomes with high precipitation rates, and when reaching the max, they rain.

This seems like a good approach to me that could be very realistic, I would just have no idea how to program the movement for the clouds.

Any thoughts on a better approach or how to implement either of these to make them work?

# Answer
\[It may be worth noting that I have never played dwarf fortress\]

Both approach seem relevant. Also usually in games the most complex part about weather systems is often the equation behind it. As you seem to already know when it has to rain you seem to have done the most of the job.

Even if both approach are OK I prefer the second one which brings, to me, more coherency with a global world.

It seems you simply need a `vector` for clouds direction and a value for their speed. The idea there is to move the cloud in the direction indicated by the vector every turn (I think dwarf fortress is a turn based game). If the cloud shape is big enough you will have the illusion of long period of rain alternating with sunny ones.

However, as I see it, it would be a binary rain system : it rains or it doesn't. As you seem to want some "realistic" system, I would suggest to add another property to the clouds which would represent the epicenter radius of the rain. According to this value, you will be able to change the intensity (surely described with a color gradient) of the rain.

**edit**: also note that if you like your clouds to a specific biome, you can play with the intensity value when they reach a biome frontier then you won't have the "no rain to full storm in the next cell" effect.

For reality purpose you need to have various sizes and shapes for them.

I hope it helps.
> 3 votes

# Answer
tl;dr

I really think this holds minor value to a game (and sounds like a bike-shed problem), if the actual gameplay is not robust and appealing already, nobody will care what the level of realism of the rain is and if the gameplay is good, again, no one will notice the level of realism involved in the rain mechanic. For now, randomizing `c` for chance, `(x, y)` for position and `i` for intesity values and simply raining here and there, perhaps increasing the amount of rain during the winter seasons is quite sufficient.

Long version:

You could randomize a map with a voronoi diagram, picking rainy areas and arid ones. Then steal some precipitation statistics graph and mimic them with the rain in your game (i.e `x` rain during the winter and `y` rain during spring).
> 2 votes

# Answer
The cloud idea seems superior to me, though it would probably be more CPU-intensive. You'd have to simulate (or approximate) even more variables to make this work, though - the clouds move with wind and atmospheric pressure, temperature, etc..

If you wanted to do the other idea, you could make a transitional area around the biome with a randomly interpolated amount of precipitation between one biome and the other, i.e., if it's raining in biome A, and drizzling in biome B, as you move from B to A add arbitrary small amounts of precipitation until it reaches the value in A and vice versa for the other direction.
> 1 votes

---
Tags: game-mechanics, roguelikes
---


# Question
Title: Make LibGDX game responsive to different phone screen sizes?
I've been experimenting with small games to learn design concepts, LibGDX, and Box2D. I am wondering how you would implement "responsiveness," so to say. For example, this is the rendering part of my game and its just drawing to coordinates. https://github.com/Elsealabs/Stacker/blob/master/com/elsealabs/stacker/ScreenGame.java

For example I'd like it to look good on Android phones of different resolutions or if the user resizes it on desktop. I am asking about design patterns or practices that would make this possible. Any solutions I can think of seem like they wouldn't scale or would over-complicate the game.

If you know of any articles or design practices that cover this topic, or have any of your own knowledge, or example LibGDX/Java games, I'd love to see them.

# Answer
There's two things needed to solve this:

1. Use a method called letterboxing. Build your game for one aspect ratio (16:9 works best for Android devices) and fill everything outside it with background image. Some developers just use black color, but background image is much nicer.
2. Once you got that, find all the resolutions you want to support and draw specific sets of graphics for each. Of course, you can scale most of the images using your graphics tool (Photoshop, Gimp, Inkscape), and you should use different font sizes for fonts.

At run-time, set the game resolution to device native resolution and load appropriate sets of resources. Use some scaling factor variable to multiply any fixed coordinates you use in the code.

Here's an example how this all works on Android, with currently available devices: http://bigosaur.com/blog/31-android-resolutions-definite-answer
> 0 votes

---
Tags: android, libgdx
---


# Question
Title: Fighting aliasing on specular highlights
MSAA does a good job removing aliases on mesh edges, but it does not help with aliased specular highlights:

Notice the aliased specular highlights on the doors and windows.

I believe the reason for this lays in the way normals are filtered after being sampled from their maps, so I wonder if there are some known methods how to make highlights more smooth?

# Answer
I've found a cheap solution in an article by Christian Schüler, where he posted a shader code used in Velvet Assassin. He smothes highlight by limiting maximum gloss to the surface curvature, which is computed by ddx and ddy of world-space normalized normals. It produces amazing results, maybe not so in noice reduction but in temporal stability of highlights (fancy graphical term, which means how much something changes across frames). Screenshots will not show the effect well enough, so I will not post them, but in action I got rid of all specular flickering on moving objects.

For those of you who are lazy (like me :)) and don't want to scan the code for the needed parts (I highly suggest that you do though, because the shader is stellar for learning purpouses) here are the relevant bits:

Add this after you transformed normal into world space and normalized it:

```
float3 ddxN = ddx(Normal.rgb);
float3 ddyN = ddy(Normal.rgb);
float curv2 = max( dot( ddxN, ddxN ), dot( ddyN, ddyN ) );
float gloss_max = -0.0909h - 0.0909h * log2(CURV_MOD*curv2);
gloss = min(gloss, gloss_max);
gloss = min(MAX_POW, exp2(1 + lerp(POW_MOD_MIN, POW_MOD_MAX, gloss )));

```

Compute specular this way:

```
half D = (gloss  + 1) * pow(NdotH, gloss);
specularColor = lightColor.rgb * NdotL * D;

```

`CURV_MOD` \- how much smothing to apply. Be careful it can make some small objects too shiny. I have it set to 2.

`MAX_POW` \- the maximum specular power you want to have in your engine. I have it set to 2000. `POW_MOD_MIN`, `POW_MOD_MAX` \- gloss boundaries. Change the lower value if you want very dull but super broad specular at low gloss values, change the higher value if you want extremely sharp specular with low AA at high gloss values. Top value will be limited by MAX\_POW as well. My values are 5, 15.

Experiment! I had to multiply the final specular result by 1/100 to make it consistent with my lighting, but for the rest I pretty seamlessly transitioned from using just a simple lit() function for specular.

Yeah one more thing - I had to change my specular intensity depending on gloss - the lower the gloss - the higher the intensity. Otherwise my highlights were too dull at low gloss.

Once again all credit for this solution goes to Christian Schüler.
> 2 votes

---
Tags: antialiasing, specular
---


title: What is wrong with my normals?

text:
# Question
Title: What is wrong with my normals?
I am trying to build a cube as a composition of many quads, with each quad being composed of two triangles. All the triangles have the same size. I am dong this (instead of drawing a single cube with just six faces) in order to have better lighting effects.

The final cube itself looks perfect however when I calculate the normals the final result looks weird. Really weird as you can see in the picture.

That's how I am calculating the normals:

For every triangle:

* calculate the normal by doing the cross product. The result is then normalized.

For each vertex of this triangle:
* Assign the same normal to all the three vertices
* if a normal was previously assigned to the same vertex, sum it with the newly calculated value. Keep track on how many times that vertex is "shared"
* Once the loop over the vertex is finished, divide each component of the normal vector with the number of times the vertex was shared.

In this picture the front face of the cube:

Also, I am adding some code:

```
//in vertices(which is an ArrayList<Float[]>) I have all my vertices.

public ArrayList<Float[]> getNormals()
{

        normals = new ArrayList<Float[]>();

        LinkedHashMap<String, ArrayList<Float[]>> map = new LinkedHashMap<String, ArrayList<Float[]>>();

        for(int i=0; i<(vertices.size()-2); i=i+3)
        {
            float x1 = vertices.get(i)[0];   float y1 = vertices.get(i)[1];   float z1 = vertices.get(i)[2];
            float x2 = vertices.get(i+1)[0]; float y2 = vertices.get(i+1)[1]; float z2 = vertices.get(i+1)[2];
            float x3 = vertices.get(i+2)[0]; float y3 = vertices.get(i+2)[1]; float z3 = vertices.get(i+2)[2];

            float[] U;
            float[] V;

                U = new float[]{x1-x2, y1-y2, z1-z2};
                V = new float[]{x1-x3, y1-y3, z1-z3};

            Float[] normal = new Float[]
                    {
                        (U[1] * V[2]) - (U[2]-V[1]),
                        (U[2] * V[0]) - (U[0]-V[2]),
                        (U[0] * V[1]) - (U[1]-V[0])
                    };

            normal = normalize(normal);

            ArrayList<Float[]> newList = new ArrayList<Float[]>();
            newList.add(normal);

            ArrayList<Float[]> list = map.get(x1+" "+y1+" "+z1);
            if(list==null) map.put(x1+" "+y1+" "+z1, newList);
            else{
                  list.add(normal);
                 map.put(x1+" "+y1+" "+z1, list);
            }

            list = map.get(x2+" "+y2+" "+z2);
            if(list==null) map.put(x2+" "+y2+" "+z2, newList);
            else{
                 list.add(normal);
                 map.put(x2+" "+y2+" "+z2, list);
            }

            list = map.get(x3+" "+y3+" "+z3);
            if(list==null) map.put(x3+" "+y3+" "+z3, newList);
            else{
                 list.add(normal);
                 map.put(x3+" "+y3+" "+z3, list);
            }

        }

        //averaging normals

            for(int i=0; i<vertices.size(); i++)
            {

                String key = vertices.get(i)[0]+" "+vertices.get(i)[1]+" "+vertices.get(i)[2];

                Float[] newNormal = new Float[]{0f,0f,0f};

                ArrayList<Float[]> lists = map.get(key);

                for(int j=0; j<lists.size(); j++)
                    {
                      newNormal[0] += lists.get(j)[0];
                      newNormal[1] += lists.get(j)[1];
                      newNormal[2] += lists.get(j)[2];
                    }

                  newNormal[0] /= ((float)lists.size());
                  newNormal[1] /= ((float)lists.size());
                  newNormal[2] /= ((float)lists.size());

                  normals.add(normalize(newNormal));
            }

        return normals;
}

```

# Answer
> 1 votes
> if a normal was previously assigned to the same vertex, average it with the newly calculated value

Let's say you have normals n1, n2 and n3 that you want to add to a vertex. The vertex's normal shall be N;

Your method: apply n1: N = n1; apply n2: N = ( N + n2 ) / 2. So, N = ( n1 + n2 ) / 2. It's still fine until now. apply n3: N = ( N + n3 ) / 2. Let's do a little math: N = ( ( n1 + n2 ) / 2 + n3 ) / 2. That means N = n1 / 4 + n2 / 4 + n3 / 2 That is not the average normal. You should not be averaging N and n3. Instead, do it so when applying a triangle's normal to a vertex:

You need another integer value, initialized at 0: int number = 0; and when applying a triangle's normal n to a vertex:

```
if ( number == 0 )
    N = n;
else
{
    N = N + n;
    number = number + 1
}

```

When you are finished do so: N = N / number; // first check that number is not 0 That way, the real average will be computed.

Hope it helps!

---
Tags: opengl, normals
---


# Question
Title: How should I store edge weights for my A* graph?
I am working on A\* pathfinding in Unity, using C#. I am implementing Dijkstra's shortest path algorithm. I have a `Dictionary` with nodes as keys and corresponding lists of adjacent neighbors as values, which I use for A\*.

My pathfinding graph is a 2D grid of nodes, with 4 connected edges each. I want to give edges representing unobstructed paths a cost of 1, and increase it for obstacles.

Where should I store each edge's weight?

---

Currently I'm representing my grid of nodes as plain gameobjects in a 2D array. I thought of storing the weights in a dictionary with node-pairs as keys and weights as values. Would that work, and be efficient enough?

# Answer
Various graph representations exist. Yours is an adjacency list with *explicit vertices* and *implicit edges*: Each vertex stores its adjacent vertices, each of which implies a directed edge to it.

In the above,
blue squares are vertex objects, arrows are references
vertex A's list of vertices is \[ B \]
vertex B's list of vertices is \[ A, C \]
vertex C's list of vertices is \[ A \]

Only explicit objects can store data, hence why your graph structure can only store data on vertices, not on edges. To store data on edges, you'll need a graph data-structure with *explicit edges* also.

A simple way to do this is simply converting each vertex's list of other vertices into a list of edge objects. Each edge object can then store any arbitrary data (for example, its weight), along with its destination vertex.

In the above,
blue squares are vertex objects, red circles are edge objects, arrows are references
vertex A's list of outgoing edges is \[ E2 \]
vertex B's list of outgoing edges is \[ E1, E4 \]
vertex C's list of outgoing edges is \[ E3 \]

---

In C#, you can implement this (in very abstract terms) by creating a `class Edge { Node destination; float weight }`, to go with your `class Node { Edge[] outgoingEdges; }` and add what other properties you need.

---

Your implementation idea would work too. Using further dictionaries instead of objects avoids having to write an edge class. The new dictionary is effectively a little database of little edge objects.

However, there are some downsides: If your graph changes (some nodes or edges disappear), dictionary entries aren't automatically garbage collected like objects are. You'll have to remove them from the dictionary yourself. You'll also have to maintain a unique ID for each node so you can concatenate them to a key representing them both together. Dictionaries also can't easily represent directed edges or parallel edges (when there are multiple edges between the same pair of nodes).

I think using objects would be cleaner and more flexible, because C# can automatically take care of a bunch of the management stuff for you.
> 5 votes

# Answer
Have you tried to create your own class/struct to represent the nodes?

You don't tell much about what your nodes are but with a Node class made by you you'd be able to stock anything you need inside and still use it as Dictionary key.

That way, when you walk through your dictionary you can always know Nodes weight.

But you can also save the list of adjacent nodes in the Node class too making the Dictionary useless. If every Node is in charge of knowing its weight but also of knowing its neighbors everything can be saved in a simple List or Array.

I hope it helps.
> -1 votes

---
Tags: c#, unity, path-finding, data-structure, graphs
---


# Question
Title: Biggest resolution for art assets for mobile games
I have created a game, and now I need to integrate graphics and distribute it for iOS and Android devices. As there are crazy number of screen resolutions, I think I should have just 3 set of art assets `HDR`, `HD = HDR x 0.5`, `SD = HDR * 0.25` and in run-time my game will choose the smallest asset for the device that can cover the screen. Cause otherwise I would have more than 10 set of assets to cover the majority of Android and iOS devices because of so many densities and aspect ratios. So I need to decide which will be the biggest asset size. Till now iPad Retina size was the reference (2048 x 1536), I guess. But after iPhone 6+ was issued with asset resolution equal to 2208 x 1242, I don't know what should be the `HDR` asset resolution. Maybe 2208x1536? to be able to cover any mobile device (all tablets and phones) screen?

# Answer
For Android, Don't go over 2048x2048, as some devices do no support them (including nexus 10).
> 2 votes

---
Tags: graphics, art, assets, resolution
---


title: MVP Matrix * Vector3 = Black Screen?

text:
# Question
Title: MVP Matrix * Vector3 = Black Screen?
I'm relatively new to computer graphics so please take it easy. I created a **ModelViewProjection** Matrix and I sent it to **my shader**:

```
#version 330 core

layout(location = 0)in vec3 vert;

uniform mat4 MVP;

void main()
{
    gl_Position = MVP*vec4(vert, 1);
}

```

When I do this I get a black screen, so I guessed I made the MVP matrix wrong but when I pass an identity matrix to MVP I still get a black screen. If I totally remove the MVP matrix from shader and code I get the desired image (a white triangle on black background).

**Should't an identity matrix multiplied with a vector return the vector unchanged ?** Ex:

```
Vector3 a
    I * a = a

```

**How should I construct a MVP matrix ?** I do it like this:

```
fovy = 120;
aspect  = width/height;
M = T * R * S;
V = lookat(position, target, up);
P = perspective(fovy, aspect, 0.3f, 1000.0f);
MVP = P * V * M;

```

**What am I doing wrong ?**

**SOLVED**

I had to call `glUseProgram(program)` before `glUniformMatrix4fv()` or any other uniform call.

# Answer
I had to call `glUseProgram(program)` before `glUniformMatrix4fv()` or any other uniform call.
> 0 votes

---
Tags: opengl, matrix, vector, windows
---


# Question
Title: How do I make parts of a texture transparent in Max?
I am applying an `eye.psd` eye-texture to my character model's face, but the results aren't what I'm expecting.

Here's what it looks like (Observe the eye on the right. Ignore the other one.):

The image is attached to a quad. I want to either

* change the color of the blank area to the skin color, as it is nearby, or
* make the image be the shape of the eye instead of square?

As shown, my image is a square and parts of it show as white, even though I erased them in Photoshop:

I expected this area to be skin-coloured:

How can I make this work right?

# Answer
> 1 votes
Use an opacity map! Simply trace the outline of the eye in Photoshop, and make the "visible" part of the texture white, and the part you want invisible black.

Then inside 3DS Max, go to your texture's mapping channels and insert the black and white image into "Opacity Map"—and voila! No more silly whiteness.

---

P.S. The reason the black space shows up as white on your model, is because 3DS Max doesn't know how to deal with the blank space on this occasion, as you haven't told it what to do. Hence it simply displays it with the default colour, which is white.

---
Tags: textures, 3dsmax, transparency
---


# Question
Title: How can I implement smooth digging effects in a tile-based game?
I'm trying to make a Dig Dug styled game where you will be digging into a material. This is going to be a tile-based HTML5 game and I have decided to use the Phaser framework.

One way to do the digging mechanic is to break the play area into tiles and remove tiles as the player sprite collides. But I would like to have a smooth digging animation/physics, so it appears that the player character "carves" out the soil as it digs through. Any tips on how I should do this? Right now I have 15x15px tiles while the player is 45x45px, this sort-of fakes the smooth digging I want. Is there a better way?

# Answer
> 1 votes
Your approach is reasonable. A simpler alternative would be to use canned sprite states for each tile, representing various levels of "dug out"-ness of the tile (100% full, 80% full, 50% full, all the way to an empty tile). But it sounds like you want something more dynamic, so you're on the right track.

When you implement this kind of technique it's important to note that you do not need to store the *entire world* at the small (15x15) tile resolution. You can store the world as the larger (45x45) tile size (or, indeed, larger if you wish. This means you have few tiles to track in-memory, particularly for dealing with the AI pathfinding, which can be optimal.

When your player hits a tile, you break the tile down into smaller pieces then and there, and being removing them as the player continues to collide with them. This hierarchical approach will help in terms of the number of individual sprites and objects you need to track (as well as with the pathfinding as detailed above).

In fact you can leverage this to further optimize pathfinding by only having the AI consider a 45x45 tile passable if some certain percentage of it's smaller 15x15 tiles (say 75%) have been removed.

In general the hierarchical approach will probably scale better -- you can use an even smaller "digging" resolution of maybe 5x5, or several layers of hierarchy if you want, and you won't suffer the performance impact of keeping your *entire map* at 5x5 resolution. Only the parts where the player has dug the map out.

---
Tags: physics, phaser
---


# Question
Title: How should I store game data in a game server?
I'm new to game server development. I'm facing this issue:

I want to develop a card game server, but I'm not sure about the solution to hold the game data while playing.

Example: In a poker game, when a player makes a move, the server will process the request and send it to all other players. But how will the game server know what the current state of the game is to do subsequent actions? Should I save all moves into database and server will look into it to know the current state?

# Answer
> 4 votes
The server has to have a copy of the game state.

If you can reasonably expect that the game server will be up and running during a particular game, and that all interaction between players in that game will always occur with that particular game server instance, you can simply hold the state in memory.

If, on the other hand, you expect a server to only be alive during a distinct *request* from the player, or for requests from a player to be distributed across potentially-many game server instances, you'll need to store the state elsewhere. A database is a possibility, as is another singular server, or a simple file on a disk accessible by all server instances, et cetera. It depends on your specific requirements.

As you claim to be new to this, I would strongly suggest you pursue a model where there's one server per game and it's up for the duration of a game. It's a simpler model to start with.

# Answer
> 1 votes
Most turn based multiplayer games do still keep all game state in memory and have the server living and listening to the players; if you won't be constantly listening to the players and are going to set it up with requests i.e.: host your game server and send RPC/REST requests via HTTP(S) for the player moves, then a KV store like Redis or MongoDB would be a good way to hold the data in-between requests, preferable to an RDBMS because game state will be linear and your player moves and current state can be stored as Hashes (in Redis) and your moves list can be stored as a List (in Redis) so there's no need to use something like MySQL for its more powerful query system. Running a game server for simple card games over HTTP requests and storing state via a Key Value store would make it pretty easy to scale and support many games on one server and build a universal API for Windows, Mac, Linux, Web, iOS, etc versions of the game.

---
Tags: server, client-server, turn-based
---


# Question
Title: Why do these quaterion multiplications produce different results?
I am trying to use quaterions to modify the camera direction vector.

This code works perfectly:

```
glm::quat temp1 = glm::normalize( glm::quat((GLfloat)( -Input1.MouseMove.x  * mouse_sens * time_step), glm::vec3(0.0, 1.0, 0.0)) );
glm::quat temp2 = glm::normalize( glm::quat((GLfloat)( -Input1.MouseMove.y  * mouse_sens * time_step), dir_norm) );

Camera1.SetCameraDirection(temp2 * (temp1 * Camera1.GetCameraDirection() * glm::inverse(temp1)) * glm::inverse(temp2));

```

This code does not:

```
glm::quat temp1 = glm::normalize( glm::quat((GLfloat)( -Input1.MouseMove.x  * mouse_sens * time_step), glm::vec3(0.0, 1.0, 0.0)) );
glm::quat temp2 = glm::normalize( glm::quat((GLfloat)( -Input1.MouseMove.y  * mouse_sens * time_step), dir_norm) );

glm::quat temp3 = temp2 * temp1;
Camera1.SetCameraDirection(temp3 * Camera1.GetCameraDirection() * glm::inverse(temp3));

```

Why can I not multiply quaterions successfully? Am I using GLM wrong?

# Answer
> 2 votes
Your top code chunk is:

t2 * (t1 * direction * inverse(t1)) * inverse(t2)

Your bottom chunk is:

t3 * direction * inverse(t3)

Given that t3 = t2 * t1

It's (t2 * t1) * direction * inverse(t2 * t1)

As far as my knowledge of Quaternion multiplication goes, I don't think t2 * (t1 * direction * inverse(t1)) * inverse(t2) and (t2 * t1) * direction * inverse(t2 * t1) should yield the same result.

---
Tags: c++, mathematics, rotation, quaternion, glm
---


# Question
Title: MMO Client / Server Architecture (NoSQL)
The main aim is to keep the games variables server-side for obvious security reasons. I believe having server-side code to check before updating the games database values will protect me from classic game hacking methods.

To avoid clients sending direct updates to the database, the server first validates the clients requested actions.

The database keeps track of every Mobile & Item

The Server has all the game-logic

The clients simply render and work as controllers that send the server actions that wont occur unless validated by the servers logic.

**Clients** should only send the server *"Action Request"*

**Server** then checks the *"Action Request"* with two possible outcomes :

1. **Valid Request :** Update DB and Re-send updated data to Clients for post-processing.
2. **Invalid Request :** Notify the client that the Request was invalid.

I need to know if im thinking in the right tracks. Thanks.

# Answer
> 5 votes
It isn't necessarily as clean cut as you expressed but in overly simplified terms and generalized notions, you are on track.

The thing to remember is that the client expresses it's intent to perform some operation. Some operations are entirely authoritative by the server. In these cases, the server must respond before the client can proceed. This works well for turn based or critical operations such as trading items within a game, inventory updates, etc. But this type of behavior isn't appropriate in all cases.

In the case of movement, it's often a better approach to allow the client to express intent to the server and simply allow the server to veto an operation should it deem the action invalid. In this case, the client begins to move as soon as the user presses the movement keys, the server simply can tell the client to back to position x, y, z if it determines the client is moving too fast or moved to an area they aren't suppose to be within. The server still is authoritative, but allows the client to provide a better user experience in exchange for a bit more complicated interpolation and handling of error responses.

# Answer
> 5 votes
You should take a look at how games like Minecraft, Halflife, and World of Warcraft handle this, most games take the simulated client input actions and send them to the server and simulate the world on both the client and server and correct when the simulations differ by correcting the client state to match the server state. Here you can see the entire current Minecraft protocol.

Also, given that you are interested in making an MMO, that usually contains a fair amount of relational data that may be useful to query through, I would use MySQL or another RDBMS and then use a Key Value store like Redis for simple things you will never have to search/query over and for a second layer of cache below your game server's memory cache (or just use Redis and save yourself the effort of building a memory cache for your game state).

Since you're developing an MMO, it would do you a great deal of good to look through the ArcEmu source code, ArcEmu is an open source World of Warcraft server and demonstrates everything you need to know to build an MMO server.

---
Tags: architecture, mmo, server, client-server
---


title: Locking frame rate to 60 in the editor

text:
# Question
Title: Locking frame rate to 60 in the editor
My game runs at several hundred frames per second. I want to limit it to 60. So I used

```
    Application.targetFrameRate = 60;

```

This works on the iPhone. But in the editor it only reduced the frame rate to around 80-90. Am I missing yet another setting?

Mac OSX Mavericks.

# Answer
For the target frame rate to be applied in the editor it is important that the vsync is disabled.

This can be changed using the Quality Settings GUI by selecting "Don't sync" or programmatically:

```
QualitySettings.vSyncCount = 0

```
> 3 votes

# Answer
Note that "targetFrameRate is ignored in the editor".

Also, it worth noting that FPS number displayed in the Editor stats window is not accurate at all. I even came to a point where I wonder if the number displayed is about Frames Per Seconds.

I suggest you to use a custom script instead of using Editor stats.
> 3 votes

---
Tags: unity
---


title: Using xinput vibration with java

text:
# Question
Title: Using xinput vibration with java
I need to use vibration for my java game, which is only available through xinput since I use xbox controllers. How can I achieve this with jna? I've never worked with dlls before so any help is appreciated. I looked at some tutorials but I haven't found anything about using structures (specifically XINPUT\_VIBRATION vibration;) and such.

This is what I want to do in the DLL:

```
XINPUT_VIBRATION vibration;
ZeroMemory( &vibration, sizeof(XINPUT_VIBRATION) );
vibration.wLeftMotorSpeed = 32000; // use any value between 0-65535 here
vibration.wRightMotorSpeed = 16000; // use any value between 0-65535 here
XInputSetState( i, &vibration );

```

The above is taken from http://msdn.microsoft.com/en-us/library/windows/desktop/ee417001(v=vs.85).aspx#setting\_vibration\_effects

Thanks!

# Answer
Thank you world, this library works: https://github.com/StrikerX3/JXInput
> 0 votes

---
Tags: java, dll
---


# Question
Title: Best Practices for combining animation and logic
In Games I often run into this kind of scenario:

The Game Logic decides something happens, and of course the logic does so instantly. But the Game also has animations depending on the logic. Like player died -\> play death animation -\> respawn. But the logic can't wait for the animation so we have to work around that.

Or take for example Starcraft 2 siege tanks as morphing units on click and they start the siege animation, but in what state is the logic. Is there a state for each animation too? Is it just a Flag ignoring everything as long as it is animating?

It tends to become really messy as i am including more and more animations.

Hope someone can give me a hint.

# Answer
**For engines written by you in native code**

* Separate your render logic out. Every cycle, run all your game / simulation logic in one phase, and once that's all complete, run all rendering logic -- this includes animation.
* Since rendering and animation are separate, run game logic timers that use the same duration as the animations, but only have game logic react to the completion of the logic timer, *not* the animation timer. Example follows:

+ (1st tick) `gameLogic.startProcess(myDuration)`. `remainingDuration` is in the data model.
    + (1st tick) `renderer.startAnimation(myDuration)`.
    + (all ticks between 1st and final) game logic checks whether process is ready to expire by comparing time remaining against duration.
    + (all ticks between 1st and final) animation proceeds.
    + (final tick) Game Logic completes. Take game logic actions accordingly.
    + (final tick) Animation completion coincides with logic completion. No callback is required because completion was already handled in model. (You'll need to know what the animation's duration is in order to achieve this.)

...Thus because you've smiultaneously started a game logic process and a render process with the same duration, they will finish at the same time, but you don't need render logic to notify game logic that the animation is complete, because the game logic already knows by looking at `myDuration` in the model.

**For existing engines / platforms like Unity**

...or Flash, where render and game logic is mixed and events are common, best stick with the approach that is most commonly used, by chaining render logic back to game logic using an event. It is not worth the effort to go against the architectural paradigms inherent in the core language / platform, it will simply make your life difficult.

**About animation**

Again depending on language / platform, animation may or may not be handled *automagically* for you. Flash `MovieClip`s, for instance, will handle this.. Unity works similarly if you use out-of-box solutions for animation, JS also whenever you use `setInterval` or `requestAnimationFrame`. Nevertheless, bear in mind that at some fundamental level, usually in native code, there is *always* a loop that is running and doing all of this for you, whether it is animation or your main game loop updates on `GameObjects`, `Sprites` or whatever. If you are already writing native code, then you will know this from working with your main application loop.
> 2 votes

---
Tags: architecture, animation, logic
---


title: Move camera on X and Z only

text:
# Question
Title: Move camera on X and Z only
How would you implement movement on a camera in order to always move it on X and Z coordinates, and if the camera has pitch yaw or roll it still moves only in those coordinates and doesn't fly up?

# Answer
Anytime you applied a positional change (translation) to the camera, you would flatten that vector out.

Let's say in a non-restricted situation, where the camera could move along the Y-axis, that you have a movement vector like this:

```
Vector3 appliedMovement = new Vector(3, 7, 2);
cameraPosition += appliedMovement;

```

Just remove the Y component.

```
Vector3 appliedMovement = new Vector(3, 7, 2);
appliedMovement.Y = 0.0f;
cameraPosition += appliedMovement;

```

I would recommend making your mutator for your camera class do this, or make a helper function.

**If you have a class for your camera, I would use a mutator:**

```
public Vector3 CameraPosition
{
    get { return value; }
    set
    {
        if ( isUsingRestrictedVerticalMovement )
        {
            value.Y = 0.0f;
        }

        cameraPosition += value;
    }
}
private Vector3 cameraPosition;

```

**If you don't have a class for your camera, I would write a static utility method to call anytime you moved your camera:**

```
public static class VectorUtils
{
    static public Vector3 FlattenVectorHorizontally( Vector3 vector )
    {
        vector.Y = 0.0f;
        return vector;
    }
}

```

**Using this helper function with our original code:**

```
Vector3 appliedMovement = VectorUtils.FlattenVectorHorizontally(new Vector(3, 7, 2));
cameraPosition += appliedMovement;

```

**You can make your helper function more efficient by passing by reference**

```
static public void FlattenVectorHorizontally( ref Vector3 vector )
{
    vector.Y = 0.0f;
}

```

**If you use the version above that passes by reference, you'll need to call the method differently**

```
Vector3 appliedMovement = new Vector(3, 7, 2);
VectorUtils.FlattenVectorHorizontally(appliedMovement);
cameraPosition += appliedMovement;

```

Note that this is exactly what Tetrad's comment in your original question was referring to.
> 4 votes

# Answer
In a first person camera, you can move the camera forward by adding the `camera.direction` values, scaled by `speed * delta` values, to the camera position. This moves the camera forward in the direction that the camera is facing. To move the camera forward on just the X and Z planes, you add `camera.direction.x` and `camera.direction.z` to the position. Create a new vector with `camera.x`, `0f`, and `camera.z`, then normalize it, then scale it by `speed*delta`.

To move the camera left or right, you add/subtract the cross product of your vector with `camera.up` scaled by the `speed*delta` in the same fashion.

Here's the code using libgdx:

```
public void update(float delta) {
    Vector3 xz = new Vector3(camera.direction.x, 0, camera.direction.z).nor();
    if (keys.containsKey(FORWARD)) {
        xz.scl(delta * velocity);
        camera.position.add(xz);
    }
    if (keys.containsKey(BACKWARD)) {
        xz.scl(delta * velocity);
        camera.position.sub(xz);
    }
    if (keys.containsKey(STRAFE_RIGHT)) {
        xz.crs(camera.up).nor().scl(delta * velocity);
        camera.position.add(xz);
    }
    if (keys.containsKey(STRAFE_LEFT)) {
        xz.crs(camera.up).nor().scl(delta * velocity);
        camera.position.sub(xz);
    }
    camera.update(true);
}

```
> 1 votes

# Answer
you can achieve it using a dummy box, create a dummy box and attach camera as it's child. then whenever you want to move camera, you just have to move the dummy box, if you want to rotate camera left and right you also have to rotate the dummy box but for other axis rotations you will have to rotate camera itself.
> 0 votes

---
Tags: xna, c#, camera, movement
---


# Question
Title: Can an application break the graphics card?
*Quick note: I know this is a **game development** Q&A site but I guess you guys most of all know and have experience with graphics cards so I address this question to you. If you think this is completely off-topic, please refer me to a proper site/forum. Edit: Actually, it **is** gamedev-related: if a bad code can result in card overheating or breaking then game developers should be aware of that and make sure their applications don't do that.*

This might seem like a weird or stupid question but is it actually possible to write such a graphics rendering application that can break the graphics card (in **any** way)?

The immediate reason that made me ask this question was (no surprise) my own broken graphics card. After having it repaired the serviceman said that they tested various apps (games) on it and it worked fine. But when I launched my own app (deferred shading demo) it heated it to over 100 degrees Celsius. So my card didn't turn out to be fixed after all but what's important here is that the problem seemed to only occur when running my own app.

I've played various GPU-demanding games on it (like Crysis) and often pushed it to the limit and more (had settings so high that the games ran at 5 FPS), some benchmarks as well... So I've given my card, many times, so much work-load that it couldn't catch up (hence low FPS) but it never reached dangerous temperatures. But my own application managed to achieve that (at least when the v-sync was off). :P Since it was only my own app, I don't think a bad cooling system was the culprit.

So I ask - do you think (or maybe know) whether or not it is possible to break the graphics card (in any way, not just by overheating) by some vicious code?

Update:

Joe Swindell said that overheating may be the problem (well, it definitely can break the card). But shouldn't a proper cooling system prevent that from happening (under any circumstances)?

Boreal pointed out another problem. If I understand correctly, FPS is bound by both CPU and GPU (is that right?). So low FPS might signal either high **CPU** load or high **GPU** load. But again - shouldn't a proper cooling system prevent GPU from overheating even if the card is "used at 100% all the time"?

# Answer
> 32 votes
It's not the app's responsibility to ensure the GPU doesn't overheat, and it's not the app's fault if it does overheat.

If the GPU doesn't have proper cooling, then yes, running a 3D app can heat it up to dangerous levels. I don't know why your app does it and Crysis doesn't, but it means the card has inadequate cooling, and/or it has been messed with (overclocked, or other factory settings / drivers altered).

Besides overheating, I'm not aware of any other way in which software could physically damage the chip it's running on. That's really not supposed to be possible; it would be a very serious failure of design.

# Answer
> 24 votes
It has happened in the wild.

Starcraft II in 2010 had a problem where it had an uncapped framerate on menu screens placing an odd load on graphics cards, destroying cards from some vendor with insufficient thermal protection.

Design and manufacturing flaws in the GPU itself can also lead to the card dismantling itself under load. G84/G86 mobile GPUs had solder joints that broke under acceptable temperature loads and eventually broke. We also have the infamous Red Ring of Death of the XBox 360 which has similiar thermal problems with solder and expansion.

All of the above are a mixture of hardware defects and insufficient thermal designs, amplified by software load.

# Answer
> 9 votes
Your question is much more complex than what you wrote. I would say the general question is "can software break hardware?", and the answer to that is a definite yes.

Mind you, not all hardware can be theoretically broken via software commands, but eventually, what software does is send electrical signals to very delicate hardware components. Usually, the more delicate a hardware component is, the more likely it is for it to be damaged when it is handled in a way in which it was not designed.

There's a lot of fun ways hardware can break, but let's just consider overheating: processing work generates heat, and that heat has to go somewhere. Depending on the dissipating characteristics of your card, the airflow in the case, and the overall temperature in the room, the amount of heat removed from the system can be more or less than what is being generated by it.

If you ask the video card to do work that generates more heat than can be efficiently dissipated, then the chip temperature will rise. If you keep it going, then the temperature will rise above the safe operating level, and the chip will break, lose its magic smoke, and probably even cause a fire hazard. You have just broken your video card, I hope you're happy.

Now, can *you* write software that does this? I would say most likely not. Any (user-level) program you write will not talk directly to the video card. There are lots of safeguards designed to prevent this situation, and they all have to fail so your rendering program ends up burning your house.

1. Generally, heat dissipators and fans are designed so they can comfortably remove the maximum amount of heat the card will generate, even on poorly ventilated cases on hot climates (within the operating ranges specified by the manufacturer)
2. If heat generation is greater than heat dissipation, the first line of defense would be the driver. Most drivers will be checking the core temperature of the GPU, and if it is going up, the driver may limit the amount of instructions it sends to the GPU to prevent generating more heat.
3. Should that fail, the firmware in the graphics card should detect that heat is dangerously building up, and will therefore reduce the clock speed in an attempt to reduce heat generation.
4. If after all that, heat is still building up, a thermal diode available in most modern CPUs and GPUs will shut down the video card entirely, and heat generation will stop.

So, if you want to break your expensive video card from a user level application via overheating, in addition to build a piece of software that stresses the system to its maximum, you would need:

1. A faulty or broken heat dissipating system. Simply sticking your finger in the fan (always in the center, not in the blades) should do the trick. Difficulty: Easy
2. A custom (or buggy) driver with throttling features disabled or broken. Difficulty: Normal
3. A custom firmware with clock reducing features disabled or broken. Difficulty: Hard
4. A broken thermal diode. If you're constantly triggering the thermal diode, it may get damaged. Difficulty: Very hard

... but not impossible! Feel free to try it\*, but do make sure you keep your fire department's phone at hand when you do it.

\*: This is sarcasm. I am in no way condoning the creation of a fire hazard, or any activities that may harm you, your family, dog or community in any way. By reading this post you completely waive me of any responsibility your actions may bring.

# Answer
> 2 votes
Even with VSYNC off, many games can fail to hit even 98% GPU utilization. The more actual gameplay they implement, the fewer frames they can stage and the more likely the GPU will go underutilized. Good multi-core optimized games can get significantly closer to 100% GPU utilization, but generally gameplay logic keeps the CPU busy enough with other tasks that it is not able to saturate the GPU with a full workload. Pure rendering applications can easily reach 100% GPU load, but games do a lot more than rendering.

On a side note, on my home machine my GPU generates significant EMI under high load and it interferes with the cheap integrated audio on my motherboard. I can hear a high-pitch whining over the analog audio whose frequency varies with load. I have come to enjoy that and consider it a feature rather than a design flaw, it makes profiling interesting as I can actually ***hear*** the load level without having to sample a GPU performance counter. However, I suppose if you have some device that is highly sensitive to EMI and inadequately shielded this could be a problem... high GPU load could cause failure in *another* device.

# Answer
> 0 votes
Overheating IS breaking your graphics card. Throwing a massive loop of data that it can't handle will certainly, as you've seen, crash and possibly damage your card permanently.

# Answer
> 0 votes
Yes, It can.

* Overheating as the obvious example, can be caused by extreme workloads. Usually achieved through overclocking. This would be the easiest to cause purposefully.

Can be avoided with good cooling systems. Enabling V-sync is also a good way to avoid this. V-sync prevents the GPU from outputting frames at a faster rate than the monitor can handle, which are frames that normally get dropped, never to be seen.

Fewer frames = less processing = less extreme workload.

Keeping track of the abilities of the GPU is also important. I imagine the programmers at Crytek wrote the code to be ready for someone to overestimate their graphics-cards abilities. If they did, I'm sure it's a feature that has saved many-a-GPU, and has saved many unknowing GPU owners from frustration.

* A little bit of corrupt (or improperly coded) data can cause a pointer to end up pointing to somewhere it's not supposed to, which can wreck all kinds of things. Though likely not permanent, it could cause varying degrees of failure in it's operation. Such a fault on the CPU is normally caught by the OS and avoided or, if it can't be avoided, will invoke a BSOD (Blue screen of death.)

Can be avoided with careful coding and double checking at run-time. (But there are always bugs. If there aren't, it's because they're toying with you.)

* The GPU is also going to have a driver, which adds another place things can go wrong. Some data can be corrupted there, or there can be a bug, etc., etc. To add to that drivers, in general, run the risk of causing a BSOD. The fallback system of the OS when something goes terribly wrong and it needs to run an emergency shutdown operation to try and minimize, or prevent, the damage. A carefully coded driver will (hopefully) not do this, but there's always a chance for bugs. Including in emergency shutdown procedures.

This can be avoided with careful coding and double checking at run-time.

# Answer
> 0 votes
One word answer: YES.

Detailed answer: Yes. It can (in certain situations). Imagine you write a program which drastically transfers data to your GPU to an infinite loop. It is certain that it will get overheated. Now again is not its Cooling system's responsibility to take care of it? Of course it is. But you should also remember that, the cooling system also have some threshold levels. If the heat produced is out of operating range of your cooling system, then your cooling system is hardly of any use. I dunno what your app does, but talking to a programmers perspective, you may write such programs which leads to this kind of situation.

# Answer
> 0 votes
1. Installing a mismatching driver with the actual card used can easily lead to causing permanent damage. My friend has somehow managed to do it through repetitive reinstallation of OS and physical change of HDD.
2. Make your PC turn on and off a lot of times. Not sure if that can cause failure but it's very possible. Anyway, doesn't sound like a very `software` way to do it.
3. Manipulate the level of power in the system by turning power-consuming USB devices on and off(example: external HDD that doesn't use it's own power). Doing this always makes my keyboard and mouse unusable until next restart and it has (over 2 years of everyday pluging 3 HDDs in and out) burned several cells in one of my RAM chips which resulted in a BSOD every 10-20 minutes.

# Answer
> 0 votes
**My personal experience:**

I used to have an Lenovo Thinkpad T61p with a Quadro FX570M built around August 2008, this batch was to known to have faulty GPUs that would one day or the other fail (soldering was sub-optimal on some of the GPU pins.)

Everything was fine for about 5 years until I ran XCOM The Bureau on it (a game known for not really being optimized), the laptop was hot, fans at full speed and for about 1 hour of gaming it did freeze but not an *usual* freeze.

*Guess what ?* I turned the laptop off and back on, it was dead with relevant BIOS beep codes indicating a video failure.

**To answer your question** : yes (as others have pointed out), a software can definitely break hardware if the former is not protected in *some way*; if for instance the GPU fan is turned off then it will definitely blow up with a 100% chance of success :D

# Answer
> 0 votes
I once had a GeForce 4 MX 440 graphics board and I wanted to play Prince of Persia: sands of time. But the game didn't launch because it couldn't find the expected Pixel Shader support. This was a bit unexpected for me, because the later Prince of Persia: Warrior Within worked just fine.

So, in the end I found of 3d analyser(http://www.tommti-systems.com/main-Dateien/files.html) and forced the game to run and played the game for several days. After a couple of days, my video card broke - didn't display anything anymore. I had the new computer for about 5-6 months so I think that forcing the game to run this way actually broke my video card :(

# Answer
> -1 votes
Yes, I have broke a few. I don't run grid gpu calculating apps anymore. Some apps tend to break those especially when machine goes to sleeping mode, but in normal situations when blowers are working/cooling liquid is circulating there shouldn't be issues unless cooling is undersized.

# Answer
> -2 votes
It can if the card's circuit shorts, however this is very unlikely to happen because the system is isolated until a certain high temperature. In some case the thermodynamic system of the card can be disturbed if it is really close to another system or if it is even touching another material that is not a system.

---
Tags: gpu, hardware
---


title: What is isometric game?

text:
# Question
Title: What is isometric game?
There is an understanding like isometric or 2.5D games. As I understand those are the same things. But I could not understand completely what is it. Is it about how the art for the game is drawn? I mean if art is drawn such that you see the game scene from the angle (visible from a top-down perspective or side view \[from wiki\]) and not perpendicular, is this isometric? Or there are some programming tricks that make game isometric, such as ability of the hero to move in 3 dimensions whereas it actually moves only in 2D like in old Nintendo games (Ninja Turtles or Double Dragon). Please explain this understanding.

# Answer
Isometric games are indead games viewed from above, in such a way that the x, y and z axis are exactly 120 degrees from eachother. So an isometric game is a game viewed in an isometric projection: http://en.wikipedia.org/wiki/Isometric\_projection (this source is very reliable :P).

So as you have already guessed, it is about the way the game is drawn.
> 3 votes

---
Tags: isometric, 2.5d
---


# Question
Title: box2D and libgdx: Attach ParticleEffect to Body
Hello I am a newbie with libgdx, my question is: how could I add a Particleeffect to a Body that is moving? I searched about the matter and I didnt find anything related to it.

I have the following code to add my ball:

```
public Body createThrowedBall(float x, float y) {

    Gdx.app.log("createThrowedBall", "("+x+","+y+")");

    BodyDef ballDef = new BodyDef();
    ballDef.type = BodyType.DynamicBody;
    ballDef.position.set(x,y);

    CircleShape shape = new CircleShape();
    shape.setRadius(5.5f);

    FixtureDef fixtureDef= new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 1f;
    fixtureDef.friction = 0f;
    fixtureDef.restitution = 0f;
    fixtureDef.filter.groupIndex = -1;

    Body body = world.createBody(ballDef);
    body.createFixture(fixtureDef);
    shape.dispose();

    // note the massive impulse vector

    body.applyLinearImpulse(new Vector2(0, 5500), new Vector2(x,camera.viewportHeight), false);

    return body;
}

```

That draws a simple circle shape that is throwed up. I want to add like a fire effect burning during the throw ( I did it with the Particle Editor) but I dont know how to attach it.

# Answer
I solved it adding the ParticleEffect to he body and before rendering the effect in render function:

```
    public Body createThrowedBall(float x, float y) {

    Gdx.app.log("createThrowedBall", "("+x+","+y+")");

    BodyDef ballDef = new BodyDef();
    ballDef.type = BodyType.DynamicBody;
    ballDef.position.set(x,y);

    CircleShape shape = new CircleShape();
    shape.setRadius(5.5f);

    FixtureDef fixtureDef= new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 1f;
    fixtureDef.friction = 0f;
    fixtureDef.restitution = 0f;
    fixtureDef.filter.groupIndex = -1;

    Body body = world.createBody(ballDef);
    body.createFixture(fixtureDef);

    ParticleEffect effect = new ParticleEffect();
    effect.load(Gdx.files.internal("effects/ball_in_fire.p"), Gdx.files.internal("img"));
    effect.setPosition((x+camera.viewportWidth/2)*10, (y+camera.viewportHeight/2)*10);
    effect.start();
    body.setUserData(effect);

    shape.dispose();

    // note the massive impulse vector

    body.applyLinearImpulse(new Vector2(0, 5500), new Vector2(x,camera.viewportHeight), false);

    return body;
}

```

in render:

```
    public void render(float delta)
{
...
        game.batch.begin();
        //imageBackground.draw(game.batch, 1.0f);
        Array<Body> bodies = new Array<Body>();
        world.getBodies(bodies);
        for(int i=0;i<bodies.size;i++)
        {
            ParticleEffect effect = (ParticleEffect)bodies.get(i).getUserData();
            if(effect != null)
            {
                effect.setPosition((bodies.get(i).getPosition().x+camera.viewportWidth/2)*10, (bodies.get(i).getPosition().y+camera.viewportHeight/2)*10);
                effect.draw(game.batch,delta);
            }

        }

        game.batch.end();
}

```

**NOTE:** I calculated the position of the effect because the ParticleEffect need the x,y of the screen and the ball needs the x,y of the camera.
> 1 votes

---
Tags: libgdx, box2d
---


# Question
Title: Mouse state not acting as I intend it to
I am creating an inventory system. I have it working well, but for some reason when I pick up an item from a slot(lets say slot 2 of 20) and drop it into that same slot(slot 2) the mouse state fails to update correctly, resulting in the item being dropped and picked back up in the same cycle. I feel like I am missing something here, but would appreciate any help. Below is my code.

The method that controls the Item being Dropped into the inventory:

```
    public void ItemDropped(Vector2 pos, Item item)
    {
        for (int intlc = 0; intlc < InvBoxes.Count; intlc++)
        {
            if (InvBoxes[intlc].Intersects(new Rectangle((int)pos.X, (int)pos.Y, 1, 1)))
            {
                if (Items[intlc] != null)
                {
                    ClampedItem = Items[intlc];
                }
                else
                {
                    //Set bln in Game to stop drawing item at cursor
                    ClampedItem = null;
                    GlobalVariables.TheGame.blnClamp = false;
                }
                Items[intlc] = item;
                break;
            }
        }
    }

```

Logic in my Inventory Class' Update method to Update the mouse state, after setting the old mouse state. Then it check for hovering over an item, and sets all old hovers to false. It then looks for if I am clicking on the item hovered over, and therein lies the problem :

```
        oms = ms;
        ms = Mouse.GetState();

        //set hover
        for (int intlc = 0; intlc < Items.Count; intlc++)
        {
            if (Items[intlc] != null)
            {
                if ((ms.X - Items[intlc].location.X) < 50 && (ms.X - Items[intlc].location.X) > 0 && (ms.Y - Items[intlc].location.Y) < 30 && (ms.Y - Items[intlc].location.Y) > 0)
                {
                    Items[intlc].invhover = true;
                }
                else
                {
                    Items[intlc].invhover = false;
                }
            }
        }

            for (int intlc = 0; intlc < Items.Count; intlc++)
            {
                if (Items[intlc] != null)
                {
                    if (Items[intlc].invhover)
                    {

                        if (ms.LeftButton == ButtonState.Pressed && oms.LeftButton == ButtonState.Released)
                        {
                            ClampedItem = Items[intlc];
                            Items[intlc] = null;
                            GlobalVariables.TheGame.blnClamp = true;
                        }
                    }
                }
            }

```

In my game Class at the end of the the Update I have a few calls that pertain to this issue :

```
        Rectangle rect = new Rectangle(mouseState.X, mouseState.Y, 1, 1);

        if (blnClamp)
        {
            if (rect.Intersects(inventory.Bounds) && mouseState.LeftButton == ButtonState.Pressed && MoldState.LeftButton == ButtonState.Released)
            {
                inventory.ItemDropped(new Vector2(mouseState.X, mouseState.Y), inventory.ClampedItem);
            }
        }

        inventory.Update(InvPos);

```

If you look at the conditional in my game's inventory's Update method's check for mouse state's current and old button state being pressed and released, when I grab an item from slot 1 and drop it into slot 2, the mouse state conditional validate as intended. But when trying to grab the item at slot 1 and drop it back into slot one, the item drops, and is immediately clamped again because old mouse state is up and new mouse state is down. Both instances will hit the conditional that is inside the hover conditional.

Additional Note : When I put a breakpoint on the ItemDropped Method inside my inventory class, the debugger causes the mouse state to update as intended, and the item that I picked up out of slot 2 is placed into slot 2 without fail. There is a flaw programatically to how I have my updates set up somehow.

# Answer
After a good nights rest, I have worked out the solution.

By moving the problem logic :

```
        for (int intlc = 0; intlc < Items.Count; intlc++)
        {
            if (Items[intlc] != null)
            {
                if (Items[intlc].invhover)
                {

                    if (ms.LeftButton == ButtonState.Pressed && oms.LeftButton == ButtonState.Released)
                    {
                        ClampedItem = Items[intlc];
                        Items[intlc] = null;
                        GlobalVariables.TheGame.blnClamp = true;
                    }
                }
            }
        }

```

Into its own method I have the following code in my Inventory class :

```
    public void GrabItem()
    {
        for (int intlc = 0; intlc < Items.Count; intlc++)
        {
            if (Items[intlc] != null)
            {
                if (Items[intlc].invhover)
                {
                        ClampedItem = Items[intlc];
                        Items[intlc] = null;
                        GlobalVariables.TheGame.blnClamp = true;
                }
            }
        }
    }

```

In my game class, I have conditionals to pick up, and drop the item as follows :

```
        if (rect.Intersects(inventory.Bounds) && mouseState.LeftButton == ButtonState.Pressed && MoldState.LeftButton == ButtonState.Released)
        {
            if (blnClamp)
            {
                    inventory.ItemDropped(new Vector2(mouseState.X, mouseState.Y), inventory.ClampedItem);
            }
            else
            {
                inventory.GrabItem();
            }
        }

```

By checking the Mouse State from within the Game class, I was able to get my methods to fire as I intended them to. Perhaps it is best to always check against mouse state and position from the game class, always firing a method in a child class from the parent level.
> 0 votes

---
Tags: xna, input, mouse
---


# Question
Title: In a TPS, how to aim bullets to the direction the camera is pointing, but make the shooting from the player?
(In C#/XNA.) I mean, I can't find an answer nowhere. I'm trying to learn how to make a Third Person Shooter, especially like the one I found in a game called "M.A.R.S.", from Epic Games. I don't want to remake that game, I just want to understand how the Third Person works.

There, the screen aims to a direction, has a crosshair and its center stays right next to the player, slightly above the shoulder. And the player aims to that same direction the screen aims, pointing to that.

What I don't understand is how the bullets the player shoot go to that direction if the player is not aiming from the same position the camera is (or is it?).

For now, in my game, I can only select things that are in front of the player, having his own View Direction (a Vector3) which follows camera's WorldMatrix.Forward and applying a Ray from the player to that direction. So if I change the direction of the camera, the player will select things in front of him, following the camera direction.

And it doesn't work to be a shooter, because if I put a crosshair in the center of the screen, the player won't shoot there but to his own front.

Thanks for any help. I'm still searching, but even here I couldn't find what I want yet.

EDIT: what I found in this link is how to make the Ray cast come out from the camera. But how much should I rotate the character's view direction so its Ray goes to the same point the camera's one goes? So the Rays make something like this: /|.

EDIT 2: Now I'm testing some code. The closest way I created until now is this.

```
            Game.ActiveCamera.FollowPosition = Player.Position;
            Game.ActiveCamera.FollowReference.Y = Player.Race.Height * 0.5f;

            Vector3 target = Player.Position;
            target.Y += Game.ActiveCamera.FollowReference.Y;
            target += (Player.ViewDirection * Game.ActiveCamera.FarPlaneDistance);
            //if (Game.Input.KeyHeld(Keys.F2))
            //    Game.ActiveCamera.Target = Game.ActiveCamera.Position + Game.ActiveCamera.WorldMatrix.Forward;
            //else
            Game.ActiveCamera.Target = target;
                //MathConverter.Convert(Player.Character.Body.Position + Player.Character.ViewDirection * 10);

```

I use a chasing camera that follows the FollowPosition. It has an Offset with X and Z, and I change Y to stay right above the character's shoulder.

Then the camera's target, which is the problem, I'm using the Player's Position plus its Forward (ViewDirection) times the camera's FarPlaneDistance, so the camera aims far away to the same point the character aims.

But I still don't know if the bullets are going to respect the crosshair on the screen this way.

# Answer
> 7 votes
Real-life gunsights have the exact same problem. There are several ways you can deal with it:

1. **Do nothing.** Just have the bullets fly from the gun in the direction the player is facing, and accept that they won't hit exactly where the player is looking at, but rather some distance below and maybe off to one side.

This is a reasonable choice for characters shooting from the hip, "spray and pray" style, and trusting sufficient firepower to make up for lack of accuracy. Players who want more precision with this type of targeting will just need to learn how much their gun's aim is off, and compensate manually.
2. **Align the barrel with the vision.** This is what you usually do when aiming a gun in real life. Basically, you hold the gun so that the barrel is straight in front of your face, pointing in the direction you're looking at. This way, any parallax difference between the line of sight and the line of fire is minimized.

Typically, there will be some kind of a sighting device mounted on top of the barrel to help you find and maintain the correct position; there are various kinds of sights, but they all have essentially the same purpose. In a video game, you can just position the gunsight directly in front of the player's camera (and the barrel just below the sight).
3. To get rid of the remaining small amount of parallax (and, more importantly in real life, to compensate for the fact that bullets don't fly perfectly straight), you can **pick a specific aiming distance** and tilt the barrel with respect to the sight (or vice versa) so that the line of sight and the line of fire precisely intersect at that distance.

In fact, since realistic bullet trajectories are approximately (shallow) parabolic arcs, while line of sight is straight, by slightly tilting up the barrel you can have the bullet follow the line of sight quite closely over a considerable distance. Basically, the bullet will emerge from the barrel a little below the line of sight, rise slowly to a peak just above the line of sight, and then gradually descend again. This gives you two distances where the aim is exact, and a range between (and around) them where it's only very slightly off.
4. Finally, in a game, you can **cheat**: cast an invisible ray forward from the camera to find the distance to the nearest target, and then automatically rotate the gun so that the bullets, fired from wherever the barrel is, will intersect the line of sight at that distance. (This is, in fact, not completely unrealistic, if the gun in question is an advanced one equipped with a modern computerized fire control system.)
5. Another way to "cheat" is to do the opposite of the above: project a ray *from the gun*, find out where it hits a surface, and **show an aim marker there**. This is basically what laser sights do, and there are also advanced systems that can do something like this "virtually", without actually projecting a visible laser beam onto the target.

Of course, while even simple laser sights will let you hold the weapon away from your line of sight and still aim accurately, they won't solve the issue with curved bullet trajectories, or with parallax between the sight and the barrel. If you wish to include such details (which, of course, are completely optional in a game) for the sake of realism, you'll still need to apply some of the techniques above to correct for the errors they introduce.

---
Tags: xna, c#, geometry, bullet-physics, third-person-view
---


# Question
Title: XNA/MonoGame/SharpDX: Pixel shader with sprite sheet
I've searched around for two days now on the internet but cannot find a solution. I've also read up on Pixel Shaders on MSDN with no luck.

I'm trying to apply a simple pixel shader to a sprite batch for alpha masking. It worked fine when I used two separate textures; one for the sprite and a matching one for the shader.

Problem is I don't want to do this. I'd like to use my sprite sheet and source rectangle and use a separate mask from a sprite sheet of masks.

However it doesn't work. The sprite draw perfectly but the mask does not and appears to be using a sprite at a different locating in the mask sheet. It has something to do with getting the coordinates of the mask.

My idea was if the sprite to draw was at 200\*200 in the sheet, subtract the correct tex coordinates from it to get the pixel, then add this to the mask.

pos = texCoord - sprite start = offset + mask start = location of mask from current pixel

EG; pos = 200\*200 - 200\*200 = 0 + maskPos = 440\*330 pos = 201\*201 - 200\*200 = 1 + maskPos = 441\*330

**UPDATE:** It is definitely converting the coordinates of the sprite to the mask that is the issue. I've tried numerous methods to try and convert this and normalize the coordinates to singles with no luck.

1. The result after masking
2. The mask being applied
3. The actual mask that should be applied

I have no idea why the result is being botched and section cut out like shown in image one. 22 is the width and height of both masks and sprites. 512 is the width and height of both sprite sheets.

To calculate the pos in the mask that generate the botch:

```
float maskPixelX = (inCoord.x * 512) + X pos to draw the tile;
float maskPixelY = (inCoord.y * 512) + X pos to draw the tile;
float2 maskCoord = float2((maskPixelX - maskpos.x) / 22, (maskPixelY - maskpos.y) / 22);

```

Pixel shader:

```
uniform extern texture ScreenTexture;
sampler screen = sampler_state
{

    Texture = <ScreenTexture>;
};

uniform extern texture MaskTexture;
sampler mask = sampler_state
{
    Texture = <MaskTexture>;
};

float2 startpos;
float2 maskpos;

float4 PixelShaderFunction(float2 inCoord: TEXCOORD0) : COLOR
{

    // Get the matching pixel offset in mask.
    float2 pos = inCoord - startpos;
    pos = pos + maskpos;

    float4 color = tex2D(screen, inCoord);
    float4 color2 = tex2D(mask, pos);
    if (color2.a > 0) color.rgba = 0;
    return color;
}

technique
{
    pass P0
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

And here is the draw call:

```
  mask.Parameters("MaskTexture").SetValue(maskSheet) ' Sprite sheet with mask.
  mask.Parameters("startpos").SetValue(New Vector2(200, 200))
  mask.Parameters("maskpos").SetValue(New Vector2(440, 330)) ' Postion of mask in sheet.
  Dim source As New Rectangle(200, 300, 22, 22)
  spriteBatch.Draw(sprites, Vector2.Zero, source, Color.White, 0.0F, New Vector2(0, 0), 1.0F, SpriteEffects.None, 1.0F)

```

# Answer
It took quite a while but I've found the solution and am posting it here for anyone else who has the same issue.

The draw code remains the same.

**Pixel Shader:**

```
// Texture sprite sheet.
uniform extern texture ScreenTexture;
sampler screen : register(s0) = sampler_state
{
    Texture = <ScreenTexture>;
    MinFilter = POINT; // Stops pixels bleeding together.
    MagFilter = POINT;
};

// Alpha map (mask) texture to blend with.
uniform extern texture MaskTexture;
sampler mask : register(s1) = sampler_state
{
    Texture = <MaskTexture>;
    MinFilter = POINT;
    MagFilter = POINT;
};

float2 spritePos; // Screen coordinates of the tile.
float2 maskPos; // Screen coordinates of the mask.

float4 PixelShaderFunction(float2 inCoord: TEXCOORD0) : COLOR
{

    // Convert the mask position to 0-1 texels.
    float2 maskTexel = (maskPos - spritePos) / 512;
    float2 pos = inCoord + maskTexel;

    // Blend!
    float4 color = tex2D(screen, inCoord);
    float4 maskColor = tex2D(mask, pos);
    if (maskColor.a > 0) color.rgba = 0;
    return color;

}

technique
{
    pass P0
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```
> 1 votes

---
Tags: xna, shaders, monogame, sharpdx, alpha-blending
---


# Question
Title: In what instances would you want to use path-finding algorithms other than A*?
I am familiar with how the common ones technically work (BFS, DFS, Dijkstra, A\*) but as far as their realistic benefits I don't quite see the need for them. Considering that, given the right heuristics, A\* is more performant then why bother with any others?

# Answer
> 6 votes
I'm not very familiar with many of them but I have seen the usage of Dijkstra's algorithm not for pathfinding but for finding the nearest X to you. For example, what powerup is closest to you or what enemy is closest to you out of a group of enemies. So a "target nearest enemy" function often uses that.

# Answer
> 3 votes
What you are really listing are, rather, graph search algorithms, which are a part of Graph Theory. A\* happens to be one which is optimized for "pathfinding" applications.

Why bother? Those algorithms are good for much, much more than simple pathfinding. In fact, there is an entire branch of mathematics devoted to studying graph theory and its properties.

BFS and DFS, in particular, are one of the most basic and powerful tools of graph theory application.

**EDIT**

It is of use to note that A\* is rather weak when the shape and nature of the obstacles to be navigated around is dynamic and changing. In this case, it is usually a good bet to look into other pathfinding algorithms.

# Answer
> 3 votes
I'm not an expert, but I can see Floyd-Warshall being better in some situations where you can afford to just precalculate *all* best paths up front and then reuse them.

# Answer
> 3 votes
If you're working with a uniform-weighted grid and don't need to worry about dynamic pathing, Jump-Point Search is an extremely efficient pathfinding algorithm. It's extremely fast, usually ten-to-thirty times as speedy as A\*. It achieves this through symmetry reduction, which is a method by which empty spaces are ignored.

# Answer
> 0 votes
A\*, because of the closed and open lists, can be more memory intensive than a well-implemented Dijkstra. However both are probably processor-bound anyway so you might as well go for the flexibility of A\*.

# Answer
> 0 votes
**Zombies!!**

Sometimes your AI shouldn't be so "I". For certain classes of MOBs (see above), the "Face where you want to go and Advance" algorithm is all you need.

---
Tags: path-finding, algorithm, graphs, search
---


# Question
Title: Is it bad practice to add GameComponents and DrawableGameComponents outside of the main initialization method?
I'm working on a snake game that has multiple game objects (snakes, apples, obstacles), and game modes (classic, adventure), that are DrawableGameComponents. Is it OK that I'm adding them as needed instead of in the main initialization method?

If not, how should I go about drawing and updates components of my game that need to be added in other methods?

If yes, is there any way to get the initialization or load overridden methods to run? Or is making my own load method and calling it right after adding the component how it should be done?

Thanks!

# Answer
**Yes**, you can add (`Drawable`)`GameComponent`s at any time. When you add them *before* `Game.Initialize` (eg: in your game constructor), they will have their `Initialize` method called when `Game.Initialize` is called.

If you add them ***after*** `Initialize` is called on your game class, then they will have their `Initialize` method called when they are **added** to the `Game.Components` collection.

Note that the upshot of this is that there is a small window in your game class's `Initialize` method, in between you calling `base.Initialize()` and returning, where game components will **not** be initialized!

Note that `Game.Initialize` will call `LoadContent`, so adding components in your `LoadContent` method also will cause them to not be initialized. Although adding components from a game *component* `Initialize` method *will* work.

`DrawableGameComponent.Initialize` calls `DrawableGameComponent.LoadContent` (so don't skip any `base` calls in methods that you `override`).

---

You could also add them at the start of your game and then toggle the `Enabled` and `Visible` properties as required.

Alternately, you could skip the game components system all together. It's basically just a list of objects with virtual `Update` and `Draw` methods (et cetera). This way you can program things to do *exactly* what you want.
> 2 votes

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


# Question
Title: Opentk LookAt() and 'eye' argument rotating
I'm trying to create rotating camera, which looks down by 45 deegre like this:

However my code for rotating eye vector is not working properly and I achieve vertical rotation, when it should be horizontal. What am I doing wrong?

```
class Camera
{
    private Vector3 target;
    private Vector3 origin;
    private float rotation;
    public Matrix4 ModelViewMatrix;

    public Camera(Vector3 target)
    {
        this.target = target;
        origin = target + new Vector3(5);
        SetMatrix();
    }

    public void Move(float x, float y, float z)
    {
        Move(new Vector3(x, y, z));
    }

    public void Move(Vector3 translation)
    {
        target += translation;
        origin += translation;
        SetMatrix();
    }

    public void Rotate(float deegres)
    {
        rotation += MathHelper.DegreesToRadians(deegres);
        SetMatrix();
    }

    public void Zoom(float zoom)
    {
        origin += new Vector3(zoom);
        SetMatrix();
    }

    private void SetMatrix()
    {
        var rotationMatrix = Matrix4.CreateFromAxisAngle(target, rotation); // rotation around target
        var eye = Vector4.Transform(new Vector4(origin, 1), rotationMatrix);
        ModelViewMatrix = Matrix4.LookAt(eye.Xyz, target, Vector3.UnitY);
    }
}

```

# Answer
I believe I see two problems here:

```
var rotationMatrix = Matrix4.CreateFromAxisAngle(target, rotation);

```

This line is passing the target vector into the method to create a rotation. That's probably not right. If you want to rotate about the axis shown in your picture, you'd want to pass it the global up vector, like you do in your LookAt line.

The second problem is:

```
var eye = Vector4.Transform(new Vector4(origin, 1), rotationMatrix);

```

This will rotate the origin( camera position ) vector about the origin( 0, 0, 0 ). This isn't what you want either. If you want to rotate about the target, you write:

```
var eye = Vector4.Transform( new Vector4( ( orgin - target ), 1 ), rotationMatrix ) + target;

```

This way we're rotation the vector from the target to the origin( camera position ) about ( 0, 0, 0 ). This will give us our rotated vector relative to the target, then we simply add the target vector to get back to where we were.
> 3 votes

---
Tags: c#, 3d, vector, opentk
---


# Question
Title: Is there a Box2d b2World::ShiftOrigin function in Libgdx?
Is there an equivalent Box2d b2World::ShiftOrigin function in Libgdx? I can't seem to find it.

# Answer
According to libgdx's Box2D introduction, "The Box2D implementation in libgdx is a thin Java wrapper about the C++ engine", which would be in `World.java` in the libgdx sources, but it's not.

So: **No**, there isn't.

…yet!
You could ask nicely in the libgdx issue tracker. (Or maybe implement it yourself and send a pull request if you know C++ Box2D? I'm surprised how straightforward their wrapper code looks.)
> 0 votes

---
Tags: libgdx, box2d
---


title: Combination Keypad in Unity

text:
# Question
Title: Combination Keypad in Unity
Im having a slight problem in getting my Combination keypad to work. Ok so basically I'm using gameObject buttons to use for the numbers 0-9. So each gameObject button has a number link to it. The combination passcode is found by finding items, in which these items have link numbers to them as well, hence item.password. The problem Im having trouble with is for the combination to show if its correct or incorrect and also if you push one of the buttons 5 times it will show incorrect code. Please help if you can Here is the code:

This is where I will have the mouse click on the button to declare a password digit.

```
public class RayCasting : MonoBehaviour
{
public float pickupDistance;
public List<Item> items;
public List<Keybutton> buttons;

// This is for the KeyPad Buttons Area

    foreach(Keybutton button in buttons)
    {

        if(Input.GetMouseButtonDown(0)) {
            if (button.gameObject.Equals(hit.collider.gameObject))
            {
                hit.transform.renderer.material.color = Color.red;
                    button.ButtonWasClicked(button.currentCombination);
                break;
            }
        }
    }

}

```

}

This is where the magic works. This is basically the gears of the combination to work. It suppose to get the 5 combination numbers from my Item class password variable and implement them to make the combination. The thing is that Im not sure if that works plus if I hit one gameObject button 5 times it says incorrect passcode.

```
[System.Serializable]
public class Keybutton
{
public GameObject gameObject;
private int Combination;
public int currentCombination;
private int buttonClickProgress;

public void  ButtonWasClicked (int buttonNmb){
Item item = new Item ();

Combination = item.password;
buttonClickProgress++;
currentCombination = buttonNmb;

if(buttonClickProgress < 5){
    decimal d = (decimal)currentCombination / 10;
}
else{
    if(currentCombination == Combination){
        Debug.Log("Correct Passcode");
        buttonClickProgress = 0;
        currentCombination = 0;
    }
    else{
        Debug.Log("Wrong Passcode, reseting...");
        buttonClickProgress = 0;
        currentCombination = 0;

        gameObject.SetActive(false);
    }
}
}
}

```

Any ideas? I know its a lot but feel free to ask whatever you need.

# Answer
> 1 votes
The traditional approach to these situations is to use a string based password.

```
string currentCombination = ""

public void  ButtonWasClicked (string newKey){
    currentCombination += newKey;

    if (currentCombination.Length == correctCombination.Length) {
        if(currentCombination == correctCombination) {
            //correct combo!
        }
        else {
            //bad combo!
        }
    }
}

```

---

However you have opted for an int based approach but the implementation does not seem to store the previous button presses to build a complete code.

I would expect the following change to help:

```
//Change from this:
//currentCombination = buttonNmb;

//To this:
currentCombination = (currentCombination * 10) + buttonNmb;
// shift the existing numbers left then place new one on the right.

```

I have no idea what is intended by this line but it currently doing nothing of consequence:

```
decimal d = (decimal)currentCombination / 10;

```

It is declaring and assigning a value to a local variable. It will only remain in scope for that clause (the if block) and the value will be forgotten next time the method is called.

---

In the future one of the easiest way to do light debugging of issues like this is to print the value of you variables to the console. If you add the following line to the end of this method you will be able to see is the code is being built correctly or not.

```
 Debug.Log(currentCombination);

```

If this doesn't provide enough information then setting a breakpoint and setting though the code will usually find the problem.

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