title: Choppy enemy movement

text:
# Question
Title: Choppy enemy movement
I had a question about How to calculate the enemy to arrive in the middle of cell.

How to calculate the enemy to arrive in the middle of cell?

The posters pointed out that the direction of the enemy isn't needed because the velocity already has a direction. I modified the code -

```
if(position.x < start.position.x) {
            velocity.x = ENEMY_VELOCITY;
        }
        else if(position.x > start.position.x){
            velocity.x = -ENEMY_VELOCITY;
        }
        else {
            velocity.x = 0;
        }

        if(position.y < start.position.y) {
            velocity.y = ENEMY_VELOCITY;
        }
        else if(position.y > start.position.y){
            velocity.y = -ENEMY_VELOCITY;
        }
        else {
            velocity.y = 0;
        }
        position.add(velocity.x * deltaTime, velocity.y * deltaTime);

```

The enemy's movements were choppy after it go around the tower I added the range of the middle of a cell but it looks like it'll stop in certain places.

```
public void plotPath(Cell start, float deltaTime) {

        if(position.x < start.position.x && Math.abs((start.position.x - position.x)) > 0.01f) {
            velocity.x = ENEMY_VELOCITY;
        }
        else if(position.x > start.position.x && Math.abs((position.x - start.position.x)) > 0.01f){
            velocity.x = -ENEMY_VELOCITY;
        }
        else {
            velocity.x = 0;
        }

        if(position.y < start.position.y && Math.abs((start.position.x - position.x)) > 0.01f) {
            velocity.y = ENEMY_VELOCITY;
        }
        else if(position.y > start.position.y && Math.abs((position.y - start.position.y)) > 0.01f){
            velocity.y = -ENEMY_VELOCITY;
        }
        else {
            velocity.y = 0;
        }
        position.add(velocity.x * deltaTime, velocity.y * deltaTime);
    }

```

I think Math.abs((position.y - start.position.y)) is a wrong way to calculate. I tried to fix 0.1f to different value, but it'll stop somewhere after passing the tower or having choppy movements, it's much less than before.

# Answer
Conceptually, the problem you're running in to is that you want to stop at an exact point and don't know how to handle the problem with time sliced velocity calculation.

One way to solve this is to consider not moving the enemy at only your `ENEMY_VELOCITY` number. When the distance between your current position and your desired position is less than your per-frame velocity, set your velocity for that frame to the distance. That'll put you pretty much where you want to be (of course with float inaccuracies) and you can stop at that frame.
> 2 votes

---
Tags: tower-defense
---


title: Fifteen puzzle modifications algorithm

text:
# Question
Title: Fifteen puzzle modifications algorithm
What would be a good algorithm for the Fifteen puzzle, if the puzzle is slightly modified in that you only have a small number of pieces that should be placed correctly and these correctly placed pieces can be located anywhere on the board

Say we had the board

1100
1000
0000
000

and we need the shape

111 anywhere in the board so

1110
0000
0000
000

and

0000
0000
0111
000

are winning results.

# Answer
There are only 7280 different positions, you could easily make an index of all of them. Then you could build a solution tree, start from the legal solutions, work out all possible previous positions, put the move required in the index, then from these positions work out the previous positions, register the move in the index etc. It is important that when a position already has a registered move you do not overwrite it but instead just drop that branch.

This way your index will contain the optimal move for every possible position.

Assuming that there is plenty space you could solve the "puzzle" by choosing a solution where there is at least a double wide edge of 0's on the bottom and right side of the figure, then you can systematically build it starting from the upper left corner and working you way towards the bottom right.
> 3 votes

# Answer
I propose to solve this with A\*. You have your start state, then you get neighbours from this state. Put your neighbours into priorityty queue statesToCheck ( where more valuable is state which has got more pieces on destination places ), also store visited states ( or shortcut from them ) to not visit the same state. Where you have destination state, you must back to start state - you must store information about how this state was created ( for example L - state was created by moving blank piece left ), second you must store "parent state" to know what was previous state in solution. Pseudocode:

```
Dictionary<StateShortcut, char > moves;
Dictionary<StateShortcut, StateShortcut> previousStates;

solve = false;
queue.Add(startState);
while(queue.count > 0 and solve == false)
{
currentState = queue.top;
Visit(currentState);
if(IsSolverd(currentState))
{
solve = true;
}
else
{
neighbours = GetNotVisitedNeighbours(currentState);
SetNeighboursValues ( for prioritytyqueue)
for(State state in neighbours)
{
previousStates[state] = currentState;
}

queue.add(neighbours);

}

}

```

This is only psudocode, but I think you can base on it.
> 3 votes

---
Tags: algorithm
---


title: Sounds categories volume level in xna

text:
# Question
Title: Sounds categories volume level in xna
I am preparing sounds system to my game in xna. I am using XACT Tools, and i got problem.

There is class SoundCategory. I can change sound level for all sounds in that category easily.

```
SoundCategory category = engine.GetCategory("music");
category.SetVolume(float_value);

```

But there is no such function like:

```
category.AddVolume(float_value);

```

Which would increase or deacrease that value. There is also no function that get current volume so i can do thing like:

```
float vol = category.Add(float_value);
vol += 0.1;
category.SetVolume(vol);

```

Is there some clever way to achive what i want without creating some additional variables which keep current volume for all sounds categories ?

# Answer
> 1 votes
I think you can get volume from category, beacouse various sound in this category can have various volumes. When you set volume for category, you set the same for all.

# Answer
> 1 votes
I suspect what you are trying to implement is a slider control in your game that allows the user to select the SFX volume and the Music volume independently.

Assuming that's the case, whatever volume the user picks IS the value you set in `.SetVolume(float);` For example, every time the Music Volume slider changes, it changes a float variable from 0.0 to 1.0 and at that time, you call `.SetVolume(sliderValue);` If you are trying to implement an Up/Down volume control which moves in increments, you don't need to add .05f to the current sound, you need to always know what it was before (storing the volume value outside the SoundCategory).

---
Tags: xna, sound
---


# Question
Title: How to deal with procedural terrain, pre-load or real-time calculation?
I have developed an algorithm that generates 2D terrain coordinates for my iOS 2D game. This may be a possible visual output:

The coordinates are stored in a 2D array.

```
mVertices[i][0] = ccp(sx, sy);
mVertices[i][1] = ccp(sx, 0);

```

E.g. `sx` is increased in steps of `30px` while `i` is the number of steps. For each step a `sy` is generated. To get the line straight down I need a second point which is the second line of code.

Imagine in the game there will be a character on that terrain. The terrain scrolls to the left while you have to move your character. Now I want to figure out what would be the best way for me to draw the terrain.

One way is to pre-load the terrain. So I would generate the points for say 5000px along the x-axis when the user starts the game while a loading spash is displayed.

Another way is to generate the terrain in real-time. I think this is the best solution here. What do you think?

When I take the real-time way, how I do the array stuff? I mean the part that goes out of screen has to be removed from the array and there is a new step that is added.

Maybe a classic array is not good as data structure for that prupose. I introduced it in my project because I can pass it to the `ccDrawPoly` function that takes a `CGPoint` array.

Please share your ideas.

# Answer
> 5 votes
I think the best Idea is to go with the real time generation since there are always some nerds who break every limit you put for yuor game.

for example if you go with 5000 nodes there will be some people to player far past it just like what happen to pacman, none of the developers never tought of someone go beyond level 255, but there were geeks to break that limit! so you need realtime generation.

Now how to generate levels in realtime: you are saying you are developing your game for IOS and as your sample shows you are going to create a landscape game so you have 480px screen to draw you game, considering your terrain is create by 30px pieces you need `480/30+2` piece ready at each frame. since there are always atleast 480/30 pieces inside screen and just by a little movement a part of another piece will come in your viewport. lets say we store one extra piece as reserved. some games doesn't have a feature that player can go back in levels (just like super mario bros) in these cases you can remove every tile that goes out of screen to free unused memmory, but if your game let's player to move freely inside levels you need to keep whatever was generated. just ignore them in drawing phase.

to store the levels you may use both arrays and linked lists. since you usualy don't need a direct access to any of the pieces, linked lists doesn't slow your code down. in my case I usually try using queues to store my level information. if you know how many pieces are in your levels you can easily use an array and keep your all your data inside it, you may either shift data as new pieces are generated or you can keep head and tail of queu and use that array like a queue (circular buffer as maik suggested).

then you need to draw them, ccDrawPoly is a good choice by I prefer to use ccSprite or ccTMXTileMap since you can't apply texture to what you are drawing. don't worry about your object may be out of screen since cocos2d handles these situations and draws only visible parts. I think for objects that are completely out of scene it even ignores drawing but it's better to remove objects that move outside. it help you organise your game better.

# Answer
> 1 votes
A proper data-structure for this situation is a Ring-Buffer, aka Circular Buffer

---
Tags: 2d, cocos2d-iphone, terrain-rendering
---


# Question
Title: Drawing the same mesh or drawing the same material?
I was wondering. Suppose I have a 1000 grass meshes. They all have the same material, but I create them separately, because they look slightly different, because they have different heights.

Does my GPU speed up if I only draw one mesh over and over again? Or is only the material switching and uniform setting the main problem?

So: Should I consider going to only one mesh a 1000 times, or is it ok to have a lot of different meshes with only the same material?

# Answer
> 4 votes
If you are using OpenGL, you can use DrawInstanced. This is useful for cases, where you have one model and want to draw it many times (for example grass). In vertex shader you will get unique ID, and according to this ID you can set per model transformation (for example take it from big array of transformation).

It's really fast and useful. I think in DirectX there will be something similar.

If you want to draw separate (but similar) models with different materials, it will slow your application down. Material switching is not too cheap operation (again - I'm talking about OpenGL).

# Answer
> 2 votes
You should re-use the same geometry wherever possible. GPUs have hardware support for re-drawing the same meshes with different parameters. Re-using the same geometry means that you don't have to, for example, move the new geometry into the hardware registers, and that sort of thing, and it fundamentally reduces the number of calls to the GPU, which is a big bonus.

# Answer
> 0 votes
I'm not sure how it's done but I know you can send material data once for GPU and then ask GPU to draw multiple mesh using it. I know this because GameEngines usually have a flag or group which you can spicify every thing under that group has same texture and this speeds up your game(I'm saying this as written inside the manual) since you pass the material data once for as you say 1000 objects and it seems to be faster.

---
Tags: graphics, optimization, 3d-meshes, gpu, jmonkeyengine
---


# Question
Title: Finding closest coordinate of a pre-known set
Let's say I have a large number of conceptual objects of some kind, each of which occupies a pre-known set of points in a Cartesian 3-space.

1) What is the best combination of data structure (for modeling these objects, their occupied points, and/or the enclosing space) and algorithm for the purpose of being able to retrieve only the point within each object that lies *closest* to an arbitrarily selected point, with speed the first concern and memory footprint secondary (but still important)?

2) Let's say that that a point may be visually occluded with respect to another point, according to a black-box true/false rule, and I now want to retrieve the closest *visible* point of each object. Asking the same question as in #1, is the answer the same or is something else now advisable?

3) Let's say that the pre-known set of points for each conceptual object may potentially change somewhat frequently, enough so for computational expense in data structure management to be a concern. Are the answers to #1 and #2 still good, or are they expensive enough in setup/teardown to be likely to cause problems under this condition?

(I really do want to know the answers to these items separately, if they have distinct answers. Mega bonus points for any answers that generalize well to a Cartesian 4-space.)

# Answer
I'd suggest a kd tree.

The nearest neighbour search is O(log Npoints) for randomly distributed points and you can easily extend the nearest neighbour search to account for occlusion.

However it's not ideal if lots of points move frequently. This may or may not make the kd-tree more expensive than other options depending on how often you need to rebuild it vs how many queries are done.

It will generalize to N dimensions.
> 2 votes

# Answer
I will point you to the page, which is one of the best resources in NN-search (Nearest Neighbors). It contains slides and links to other resources. But KD-tree is probably best solution (but there are many variants):

http://simsearch.yury.name/

There are great on-topic slides from Data structures of computer graphics course on CTU in Prague, by Vlastimil Havran:

http://dl.dropbox.com/u/5034466/dpg0904.pdf
> 1 votes

# Answer
1) Since speed is a concern, you may want to take a look at approximate nearest neighbor algorithms. I've used ANN in the past and it performed very well for around 12 dimensions. It lets you adjust desired precision so that you can have a trade off between speed and precision and find what works best.

2) Since your visual occlusion is a black-box one (I'm assuming unpredictable moving obstacles), I'm not sure if you have much of a choice other than doing occlusion tests on the points that the NN algorithm returned.

3) I don't believe ANN supports points changing, but I'm not sure since I didn't need that. It seems Cgal and Pastel support dynamic sets, but in terms of insertion/removal of points. Perhaps the papers here would also provide some insight.

I don't know if you need this advice, but I found that reusing libraries for such problems almost always is a better idea. There are so many pitfalls one can fall into while implementing the details. Good luck!
> 1 votes

---
Tags: 3d, mathematics, algorithm, data-structure
---


# Question
Title: android zoomable and scrollable board game
I'm developing a Android board game and have a question regarding creating a board that is zoomable and scrollable. The board contains a static background, characters (players) and the actual "level" which is drawn using tiles.

My solutions is to have a collection of elements (tiles, figures, all game elements - all have x,y coordinates and width + height), a camera and a renderer that draws the collection according to cameraX,cameraY, cameraWidth and cameraHeight. So if a user would scroll to the right, the camera would just set the cameraX appropriately - and the surface is scrollable. And if a user would zoom in/out the renderer would just scale every element image appropriately.

Example code for the renderer with scrollable surface and zoom in/out

```
    protected function draw(Canvas c){
      Collection elements = collection.getElements(cameraX,cameraY,cameraWidth,cameraHeight);
      if(elements.size() > 0) {
         for(int i = 0; i < elements.size(); i++) {
              elements.get(i).drawElement(c);
         }
      }
    }
    .
    .
    .
    // element class drawElement function
    protected drawElement function(Canvas c) {
        if(this.image != null) {
          int w = this.width;
          int h = this.height;
          if(this.zoomFactor < 1) {
             w*=this.zoomFactor;
             h*=this.zoomFactor;
          }
          c.drawBitmap(this.image,this.x,this.y,w,h);
        }
    }

```
* Is this the best solutions?
* Could it be achived somehow else?
* Could scrolling be achived using a ScrollView?

I dont wanna use any engine, because this is for a school project.

# Answer
Good logic but use Matricies with scale transformations to implement zoom, do not try and calculate it everywhere yourself.

That way you could write the following code:

```
canvas.save();
canvas.setMatrix(myMapMatrix);

// TODO write the rest of the drawing code here using map co-ordinates

canvas.restore();

```

Where myMapMatrix is the matrix that lets you go from the screen viewport to the board game map. And if you get the inverse matrix then you can transform a map co-ordinate into a screen co-ordinate. I know because this is the way that I am currently doing it in my game.

I will leave how to create the Matrix as an exercise for you but let me give you a hint.
> 1 votes

---
Tags: 2d, android, rendering
---


# Question
Title: Sorting array of points in clockwise order
Is there such an algorithm to sort an array of 2D points in clockwise order?
I'm specifically dealing with right triangle in my case so only 3 points.

However I'm interested in knowing if such an algorithm exist, if not what is a simple way to return the 3 points of my triangle in clockwise order?

Edit: I am trying to compute the points clockwise relative to the centroid of the polygon, which is convex.

**Update:** This is the implementation I ended up using based on the chosen answer, it's not performance critical and only happens once in a while so it works out.

```
ArrayList<PVector> pointList = new ArrayList<PVector>();
pointList.add(A);
pointList.add(B);
pointList.add(C);
Collections.sort( pointList, new TriangleVectorComparator(origin) );

return pointList;

// Comparator
package triangleeditor;

import java.util.Comparator;

import processing.core.PVector;

public class TriangleVectorComparator implements Comparator<PVector>  {
    private PVector M;
    public TriangleVectorComparator(PVector origin) {
        M = origin;
    }

    public int compare(PVector o1, PVector o2) {
        double angle1 = Math.atan2(o1.y - M.y, o1.x - M.x);
        double angle2 = Math.atan2(o2.y - M.y, o2.x - M.x);

        //For counter-clockwise, just reverse the signs of the return values
        if(angle1 < angle2) return 1;
        else if (angle2 < angle1) return -1;
        return 0;
    }

}

```

# Answer
Your question is not precise enough. An array of points is only « clockwise » or « anti-clockwise » relative to a reference point. Otherwise, any array of three points can always be either CW or CCW. See the following picture: on the left, the points are ordered clockwise; on the right, the exact same points are ordered anticlockwise.

In your case, I believe using the barycenter of the points as a reference point is reasonable.

A good method for an unknown number of points could be the following one:

* let `P[0], P[1], ... P[n-1]` be the list of points to sort
* let M be the barycenter of all points
* compute `a[0], a[1], ... a[n-1]` such that `a[i] = atan2(P[i].y - M.y, P[i].x - M.x);`
* sort points relative to their `a` value, using `qsort` for instance.

However, you can be sure that a good sorting algorithm will perform poorly with three input values compared to an ad-hoc method. Using `atan2` is still valid, but just don't use `qsort`.
> 20 votes

# Answer
I believe that what you're actually asking about here is the triangle's winding order, which is actually pretty simple to test.

Since there are only three points in your triangle, your triangle is already in either a clockwise or counter-clockwise order, and so all you need to do is to check which of those two it is, and reverse the order of indices if the winding isn't the one you want.

Here's the general idea, assuming that the three vertices of a triangle are *a*, *b*, and *c*, and that you have a simple vector subtraction operation:

```
Vector2 AToB = b - a;
Vector2 BToC = c - b;
float crossz = AToB.x * BToC.y - AToB.y * BToC.x;
if ( crossz > 0.0f )
{
  // clockwise
}
else
{
  // counter-clockwise.  Need to reverse the order of our vertices.
}

```

Note that depending upon which way you've oriented your +y axis (up or down), the "clockwise" and "counter-clockwise" cases may be reversed from how I've labelled them in the comments in this sample code.
> 5 votes

# Answer
Can you give more info? You want CCW order of points, but what point should be center of ordering?

If you have just triangle (3 points) in plane, you can compute determinant from matrix, where lines are coordinates of points (3rd coordinate is 1). If determinant is \> 0, points are in CCW order. If not, you can swith for example last two points and you will get CCW order.

If you have points A, B, C, then your matrix looks like:

```
|xA, yA, 1|
|xB, yB, 1|
|xC, yC, 1|

```

Determinant is: xA\*yB + xB\*yC + xC\*yA - yB\*xC - yC\*xA - yA\*xB. Then you can compare it with zero. If it's \> 0, return points A, B, C, if it isn't, return A, C, B.

If you have set of points and know, they make convex polygon (all are part of convex hull), and want to get their order, you can use Graham Scan or Jarvis's March (these are algorithms to find convex hull from many points, but it should also work here :) )
> 2 votes

---
Tags: 2d, mathematics, algorithm
---


# Question
Title: Does XNA provide any special class to make a game server?
For my multiplayer game server, I made a class inheriting from "Microsoft.Xna.Framework.Game", just like I did for the client-side part.

The thing is, I don't need any graphical display for the server, so I end up with a useless blank game window floating around. Also, the LoadContent/UnloadContent and Draw overrides are left empty. On the other hand, I still need to use Microsoft.Xna.Framework.Game for the game loop and logic update parts.

So is there any special class in XNA made especially for the server-side part, or is everyone else doing it just like I do?

# Answer
There is no class that is part of the XNA library that acts as a game server.

You probably should not use the framework to write the server code unless you are creating a peer to peer Xbox based game over Xbox Live. I assume that you are not doing so because you would then need to render things onto the screen.

All C# programs start in the public static void Main method, including a program begun with the XNA framework.

If you do not already know how to create a program and import the XNA libraries without using the framework, you may be in over your head when it comes to the creation of a multiplayer game.
> 2 votes

# Answer
An XNA application is a .NET application, just like any other. In your Program.cs on the server, don't call the constructor or Run() for the Game class; just run your server logic instead.
> 2 votes

# Answer
Why is it a problem that your game doesn't draw anything?

It seems like you're tilting at windmills.

If you want you can make a console application and then just import the XNA networking classes that you actually need, or make any other type of application, and import the XNA networking stuff. If you need a fixed time update loop, that is pretty trivial to implement.

You can create a windows forms application, and use it with XNA, by following the information here: http://forums.create.msdn.com/forums/t/6471.aspx

You probably want your server to draw *something* though, like the current status, or provide some sort of GUI controls.
> 1 votes

# Answer
What kind of multiplayer server you are going to write? Is this just a lobby server for setting up peer-to-peer games? Is this a full on multiplayer server that is dedicated to hosting the game and communicating with clients (like Counterstrike servers, for example)? Or are you wanting to add multiplayer capability to your game in which a player starts a game that others can join?

If the last variant is what you want, XNA/.NET do provide some networking classes.

If you want to create a dedicated multiplayer server, you should do as HydroxicAcid says and avoid using the entire XNA framework as you will not need much of what it provides. What you *should* do is isolate your logic from your rendering code (in separate assemblies!) so that you can reuse these classes in your server application. You'll want to look into serialization over a network of figure out some lightweight message format for transporting gameplay data. There may be some instances where a 1:1 match between how a game object is represented on the server must be very different from how that same object is represented on the client, so be prepared to deal with that.

If you want to create a lobby server, you probably don't need to even write it in C# or use the .NET framework or even run it on a Microsoft platform. Its sole purpose is to find other people that want to play the game and tell them about each other, so there will likely be no need to reuse any existing game code for that.

Whatever it is you're looking to do, you can find a lot of good resources on AppHub =\> http://create.msdn.com/en-us/education/catalog/?devarea=19
> 1 votes

---
Tags: xna, server
---


# Question
Title: Collisions between players at spawnpoints
I am working on a FPS/MMORPG and ran into a problem at spawnpoints, when I enabled collision detection between players. Neither player would be able to move if both spawned at the same time, because both players would essentially be "trapped" within each other's meshes. What is the best way to resolve this problem?

# Answer
> 6 votes
The usual way to avoid this problem is to do a collision check before spawning the player, to make sure that the spawning area is clear of obstacles before spawning.

In general, you want to have several different spawning positions (as many as possible), so that if one of them is blocked, you can spawn the player at a different one.

If all spawning positions are blocked, then you need to delay spawning the player until one of the spawning positions becomes clear. (This is why you need lots of spawning positions, to keep a team of players from conspiring to grief their opponents by intentionally standing in all the available spawning positions and keeping their foes from respawning)

Your extra spawning points don't even need to be in different parts of the world; it's very, very common to make "clusters" of spawning points that are very close to each other. This lets you still know approximately where players will spawn (which can be useful from a design point of view), but still have spawnpoints available for immediate use when a player doesn't immediately move after spawning.

# Answer
> 2 votes
You might also consider just not having players collide with each other. Besides simplifying the spawn problem it also eliminates griefing such as door blocking.

---
Tags: opengl, c#, collision-detection, physics, opentk
---


# Question
Title: What are some typical server/vps/colo hosting costs for deployed MMOs?
From my estimates the MMO I'm designing can support 500000 concurrently connected non-idle users (and still be able to you know, do stuff) for about $1700/month in total hosting costs (includes bandwidth). No system admin is needed as the infrastructure auto-scales. Each additional 40000 users costs another $136/month. I've spent several months designing this backend and I'm curious how much other such systems cost.

I should note that this does NOT include the cost of any assets used by the client game. Assume it's an iPhone game with bundled assets.

Thanks!

# Answer
> 8 votes
There's too many undefined or barely defined terms there. MMO is such a loaded term. Without knowing how much CPU processing a user needs, how much backend storage a user needs, etc... It's impossible to say.

I mean just at a bare minimum assuming the hardware can support it, you would need 8 front end servers just to support 500,000 connections. (TCP max of 65,536 ports per VPS rounded down to 65k.) I assume you've read about the C10k problem (The difficulty in scaling a single server to 10,000 connections, and 8 front end servers assumes you're at 6 times that rate.) If not take a look at http://www.kegel.com/c10k.html

However, the metric I've used when it comes to MMO buildout was to assume 1 'CPU' per 100 connected users. This worked out to be a good average from 2001-2005 but I haven't developed an MMO since. This 1 CPU basically just encapsulates the cost of gameplay servers, front end servers, database servers, content distribution servers etc... It worked whether it was a blade server with 10 CPUs or old dual Pentium Pros. Of course as an added example those build-outs usually assumed one full time Network Operations person per 5,000 connected users. (Both obviously scaling with the peak-tie ratio.)

I'd advise getting to your scalability tests sooner than later because I think it's going to wake you up to some problems in your design. Get 50,000 people on 1/10th the hardware you expect to run in production and see where the seems come apart. (Ideally do that 12-18 months before you expect to ship.)

# Answer
> -1 votes
Stop thinking in terms of servers and start thinking in terms of cloud computing. Build it with the Google App Engine for example. It will automatically Scale to handle any traffic growth. Besides not stressing about CPUs, servers, databases, RAM and diskspace, you also pay for just what you use.

---
Tags: mmo, server, costs
---


# Question
Title: How to make a custom semantics HLSL shader for the pixel shader
I'm pretty sure it's possible but i have no idea how.

Could anyone tell me how to make a custom semantic for a pixel shader.

Thanks

# Answer
> 6 votes
Typically, you just use `TEXCOORD` for any data that DX doesn't understand.

http://msdn.microsoft.com/en-us/library/bb509647(VS.85).aspx

This page suggests that the system doesn't give a crap, effectively, what semantics you give to your pixel shader inputs.

---
Tags: shaders, hlsl
---


# Question
Title: How would I setup the Environment Variables for BulletPhysics?
I am using Bullet Physics v2.78. And Im trying to build this library to be used for ogrebullet. The main problem is that Im getting errors trying to find the Bullet Directory.

Im wondering if maybe my environment variables are setup wrong.

I am using Windows Vista 32 bit, and here are my Environment variables:

BULLET\_ROOT: C:\BulletPhys

BULLET\_INCLUDE\_DIR: C:\BulletPhys\src

as other information I am trying to build these libraries in cMake. Bullet physics builds perfectly, but ogrebullet cant find the libraries needed to configure(Dynamics, Collision, LinearMath, etc.)

So my question is: How would I setup the environment variables so ogrebullet can find them?

If any other information is needed i will provide upon request.

Thanks

-Molma

# Answer
After building bullet, you have to copy the libs to the ogre folder as explained here

Particulary this part: **"Put these files to ....\OgreBullet\lib\Debug\\:"**
> 1 votes

---
Tags: c++, ogre, bullet-physics, mingw
---


# Question
Title: OpenGLES 2.0: Rendering Multiple Sprites - Texel Corruption
I'm having a tremendous time getting the second (or additional) sprites in my game engine to render properly. The first one always works great: it is positioned and sized properly in screen coords, and its texture is mapped properly. When I add a second sprite to the world, its texture does not get mapped properly. If I reverse the two sprites render orders, the sprite that was rendered second previously (and had corrupt texture mapping) is now correct, and the other sprite is now corrupt.

I think it has to do with something in my shader not getting cleared out properly before it is used again. I have to admit, I'm fairly new to shaders. Interestingly, I'm building this engine to support both ES1.1 and ES2.0, and the same code works great in ES1.1 for multiple sprites.

I'll attempt to provide relevant code snippets below. Any suggestions would be great - I've browsed dozens of good forums and Stack Exchange. Is there perhaps a call I should be making between primitive renders to clean out the shaders?

Here's the snippet for rendering in ES2.0

```
void Sprite::Render(GLuint shaderProgram, UniformHandles* uniforms, AttributeHandles* attributes)
{
// Use the shader we were sent
glUseProgram(shaderProgram);

// Enable transparent blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

// Performance: could pull this out and only recalculate when moved
PVRTVec2 bottomLeftPos = PVRTVec2((m_viewDims.x - m_position.x) / m_viewDims.x,
                                      ((m_viewDims.y - (m_position.y - m_drawDims.y)) / m_viewDims.y));

PVRTVec2 topRightPos = PVRTVec2((m_viewDims.x - (m_position.x + m_drawDims.x)) / m_viewDims.x,
                                    (m_viewDims.y - m_position.y) / m_viewDims.y);

// Draw the quad for ES2 (positioning is not based on these values: do not change)
DrawQuad((bottomLeftPos.x * 2.0f) - 1.0f, (bottomLeftPos.y * 2.0f) - 1.0f, (topRightPos.x * 2.0f) - 1.0f, (topRightPos.y * 2.0f) - 1.0f, m_textureResource->texture, uniforms, attributes);

// Turn off blending
glDisable(GL_BLEND);

```

}

And here's the snippet for DrawQuad()

```
void Sprite::DrawQuad(float x1, float y1, float x2, float y2, GLuint texture,
                  UniformHandles* uniforms, AttributeHandles* attributes)
{

    // Set the uniforms for rectangle position and width
    // Landscape
    glUniform2f(uniforms->LowerLeft, -y1, x1);
    float scaleMatrix[4] = { 0, x2 - x1, y1 - y2, 0 };
    glUniformMatrix2fv(uniforms->ScaleMatrix, 1, GL_FALSE, scaleMatrix);

    // Use the given texture
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);

    // Bind the vertex buffer object
    glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
    glEnableVertexAttribArray(attributes->in2DVertex);
    glEnableVertexAttribArray(attributes->inSpriteTexCoord);
    glVertexAttribPointer(attributes->in2DVertex, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT) * 4, 0);
    glVertexAttribPointer(attributes->inSpriteTexCoord, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT) * 4, (unsigned char*) (sizeof(GL_FLOAT) * 2));

    // Draws a short triangle strip
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glDisableVertexAttribArray(attributes->in2DVertex);
    glDisableVertexAttribArray(attributes->inSpriteTexCoord);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

```

And finally the vertex shader and fragment shader for 2D sprites:

Vertex Shader attribute highp vec2 in2DVertex; attribute highp vec2 inSpriteTexCoord;

```
uniform highp vec2      LowerLeft;
uniform highp mat2      ScaleMatrix; // Width/height and screen rotation

varying mediump vec2    TexCoord;

void main()
{
   gl_Position = vec4(ScaleMatrix * in2DVertex + LowerLeft, 0, 1);
   TexCoord = inSpriteTexCoord; // formerly in2DVertex
}

```

Fragment Shader uniform sampler2D sTexture;

```
varying mediump vec2    TexCoord;

void main()
{
    gl_FragColor = texture2D(sTexture, TexCoord);
}

```

# Answer
> 0 votes
Although I don't have a solution to the problem I was encountering, I did find a workaround and I am posting it if anyone else ever sees something similar.

For reference, the rendering code I was basing the above snippets on (esp the shaders) came from PowerVR's OpenGLES2.0 SDK (I think the Alpha Blending demo). I mostly understand the coordinate system it is using to render sprites, but I think it's pretty funky. At least, I sure don't think that way when I consider graphics!

SO, I switched it over from that system to a much more "3D"-oriented shader. Here's the new vertex shader:

```
attribute highp vec4    inSpriteVertex;
attribute highp vec2    inSpriteTexCoord;

uniform highp mat4      OrthoProjectionMatrix;
uniform highp mat4      ModelviewSpriteMatrix;

varying mediump vec2    TexCoord;

void main()
{
    gl_Position = OrthoProjectionMatrix * ModelviewSpriteMatrix * inSpriteVertex;
    //gl_Position = vec4(ScaleMatrix * in2DVertex + LowerLeft, 0, 1);
    TexCoord = inSpriteTexCoord; // formerly in2DVertex
}

```

Notice I'm still using a 2D texture coordinate but have now upgraded to a 4D position vector for the given vertex and a including two matrices for transformation: an orthographic view matrix and a model view matrix that contains the scale/rotation/translation transforms that have been applied to this sprite.

Again, I wish I knew what I was doing wrong in the original snippets, but this approach seems much more sensible. Probably not as fast at render time, but I think it is reasonable. Hope this helps someone!

---
Tags: opengl-es, textures, shaders, rendering, sprites
---


# Question
Title: How can I easily implement swinging in a platformer game?
I'm developing a game in which player can use ropes to swing (just like what Spiderman or *Bionic Commando* did) and I'm having problem implementing this behavior. Can anyone help me how to do this, I mean physics formulas and etc. Till now I've come up with 3 ideas. One is using spring, but it consumes a lot of time and sometimes it is jumpy. The other two are trying to calculate next step (one via calculating potential energy and one via calculating torque) and both of them almost crash whenever the actor is trying to swing.

Here is the code I wrote to calculate torque:

```
float dx = Runner->getPosition().x - ancher.x;
float dy = Runner->getPosition().y - ancher.y;
float t0 = atan2(dy,dx); //my current angle
float k = ((dy) *vx - (dx) * vy) / (dx * dx+dy * dy); //previus angular velocity
k -= gravity * cos(t0) *dt; // new angular velocity (gravity is positive)
t0 += k * dt - acc * cos(t0) *dt * dt / 2; // rotate the rope
float dx1 = r0 * cos(t0); // new position (r0 is rope length)
float dy1 = r0 * sin(t0);
vx = (dx1 - dx) / dt; //calculate velocity
vy = (dy1 - dy) / dt;

```

# Answer
> 3 votes
after many attempts I went with box2d.

there are generaly two approches to for this simulation or at least I found 2:

1. one is to use some circle shapes and connect them using distant joints.
2. and the other one is to rectangles for the chain itself and then attach them using revolute joints

in each senario you have got to have a ancher (which in my case was an static box). it's better if you lower the weight of rope parts (either you use circle shapes or rectangle shapes), for example to have more realistic physics I set their density to 0.1 and for the box connected in the end of rope I used density 10.

another thing you need to worry about how your rope segment react to each other. i just wanted my rope to move freely in scene so I marked all rope fixtures as sensors. you may need diffrent approch.

the next thing you have to worry about is the number of iterations you are pasing to the world update: for low segment of rope( maybe 8 at most) there is no need to use a high iteration value maybe 10/10 which box2d itself suggested is enough but if you increase the number of segment for example i tried 30 segments, with low number of iterations your rope seems to increase it's length more that it should, so you need maybe areoung 40/40 iterations to solve those situations.

after some testing it seems box 2d is designed for scenes with object sizes of 0.1m to 10m and the maximum size suggested for large scenes is somthing about 50mx50m. so basicaly you need to scale your object down to match these parameters. in my case I first tried to pass pixel positions directly to box2d but it seemed like there was some speed limits preventing world to move as fast is it should, so I had to scale my scene around 64 times to have the best results. although i didn't test myself there are some limits in box2d that prevent you from using larger scenes. for example there is a defined value in `b2Setting.h` file `#define b2_maxTranslation 2.0f` you can change box2d settings but it seems not recommended.

# Answer
> 6 votes
If you want a rigid-swing, so the distance to the rotation-point is constant, just treat the character as a point on a circle centered at the rotation point. Give him a one-dimensional (along the circle) angular-velocity. Each frame the angular-acceleration should be `accelerationDueToGravity * cos(angleOfPlayerOnCircle)` (with 0-degrees pointing right).

If you want the rope to get longer/shorter, you could use the above scheme and just vary the radius each frame.

# Answer
> 2 votes
Have you considered slowing down the speed of the swing movement based on how far the rope is from the plumb line (the centre)?

# Answer
> 1 votes
When the player is further than the length of the rope, the player will be immediately pushed back with a force equal to the distance that he has passed it. This should work without feeling springy, and should feel intuitive to the player. You may have to tweak your physics to get the best results for your game though.

When the rope is attached. Save a `maxLength` value.

Each update, check the `distance` between the `player`, and the `attachPoint`

If the `distance` is less than the `maxLength` update normally, no effects from rope.

If the distance is greater than the `maxLength`, find the `normal` from the `attachPoint` to the player. Get the difference between the `distance` and `maxLength`. Add to the `playerVelocity`, `normal` multiplied by the difference.

Pseudo Code:

```
dx = (attachPoint.x - player.x)
dy = (attachPoint.y - player.y)

distance = sqrt(dx*dx+dy*dy);

if (distance > maxDistance)
{
    float dx1 = dx / distance * maxDistance;
    float dy1 = dy / distance * maxDistance;
    v.x += (dx1 - dx) / dt;
    v.y += (dy1 - dy) / dt;
}

playerVel += v * dt;

```

# Answer
> 1 votes
If you look at http://www.cocos2d-iphone.org/archives/1112 there is a implementation of a rope with a rigid body attached to the end of the rope. It uses Box2D for the physics engine. If you look at the source code, I'm sure you can implement it in any language you like.

Also, the above link to the Rope question is mine and this demo(link provided) above really helped.

---
Tags: physics, platformer, rope-physics
---


# Question
Title: Is this design a service locator design pattern?
I was reading what a service locator pattern is from this article, and now I'm just wondering if I merge service and locator classes is it still a service locator pattern or not? And if not, do you think this implementation is usable enough as single or service locator pattern? (since the example was an audio manager I'll give same example here)

```
class IAudio{
private:
    static IAudio* instance;
    static IAudio _NULLINSTANCE;
public:
    IAudio()
    {
        instance = &NULLINSTANCE;
    }

    IAudio* getInstance()
    {
        return instance;
    };

    void registerInstance(IAudio* pInstance)
    {
        instance = pInstance;
    }

    virtual void load(const char* path)
    {
        //do nothing
    }

    virtual void play(const char* path)
    {
        //do nothing
    }

    virtual void stop(const char* path)
    {
        //do nothing
    }
};

```

And then I'll inherit classes I need from AudioManager and call registerInstance in my initialization function.

# Answer
This is no longer the service locator pattern because anything that would like to talk to the audio service, now has to know about the class, it's location/package etc..

Take a good look at this quote from the site you linked:

> These callsites, of course, have to be coupled to something in order to make a sound play, but letting them poke directly at the concrete audio implementation is like giving a hundred strangers directions to your house just so they can drop a letter on your doorstep. Not only is it a little bit too personal, it’s a real pain when you move and you have to tell each person the new directions.

In the final example any game object that can ask for the audio engine only has to know about the IAudio interface and where the locator is. Not where the actual AudioService class is. By putting the locator inside the AudioService you violate this idea, and you just get a weird singleton.
> 3 votes

# Answer
First off, this is not gamedev related and as such is a more SO question. Also, why should it matter if you're using the service locator pattern? Why should it matter if your code is an observer, or a visitor? Design patterns are meant as structures that can be used for generic aim. It is unlikely you will need them in their raw form.

Anyway, it is not. The idea of a service pattern is to act as a messenger. You, person `X`, want to get an object `Z`. The service provider `Y` simply has a reference to `Z`, and passes you that. The idea is that you do not need to know anything about `Z` (other than what it is). It could be a red object, a blue object, a yellow object - the service provider is simply giving you the object without having to reference it exactly.

In this case, the load/play/stop functions are just showing this as a singleton. You want three classes; an interface `IAudio` which is what you program against, a `AudioServiceProvider` which has the `IAudio` pointer, and a number of `Audio` concrete classes that implement `IAudio`. You have missed out the middle step.
> 3 votes

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


title: What are windows used for?

text:
# Question
Title: What are windows used for?
I have a very general question: In games, what use does the programming concept of a window have? Or, in other words, why do some game dev libraries offer interfaces through which to create multiple windows? — Why would you need more than one windows in a game?

Are multiple windows used as different views/states of the game? (I.e. in-game, main menu, pause menu, etc.)

# Answer
> 5 votes
They are literally as you describe; a window is a window on the screen. It is separate from a 'View', which acts like a viewport (a part of the display) or a 'State' (which is more like a separate menu).

# Answer
> 1 votes
Some devices can render to more than one window. It's increasingly common for desktop computers to have two screens, and there are platforms like the DS and 3DS that offer multiple screens.

# Answer
> 1 votes
While most games don't use multiple windows, tools will often create more than one separate window that they want to render to.

# Answer
> 1 votes
A window is an organizational tool, as noted for separating and displaying information. In a PC context you'd generally use this for (as example) a primary output window and a debug window (or a game window and a multiplayer lobby/chat).

I don't see a lot of games that use multiple windows, generally I see view ports used to divide up the screen among a viewable game area, inventory, chat and so on though even that is somewhat out of vogue right now, with most controls simply overlaying the play area in a HUD like display.

Hope this is what you were looking for.

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


# Question
Title: Have a while loops but inputs depend on events fired, what are some ways on getting the input?
I think I'm at a conundrum here, I've creating a matching game in C# winforms. And I'm 90% done, the only thing left is the game loop.

The matching games consits of two multidimensional arrrays which are panels. And after I set everything up, I can RunGame(), which where my game loop is, the problem I am having is getting input. I'm not sure how to do that yet.

For example.

It's a while loop.

So,

```
while(game.isRunning()){

//get input from player.

//getchoice then redraw panels accordingly

//get input from player 2.

//getchoice then redraw panels accordingly

}

```

The problem is my players click on panels that's how I get the choice they've made. So I wanted to know if you guys have any good ways of getting input in a loop from an event that will be launched outside the loop for a game.

Thanks.

# Answer
> 6 votes
This kind of game loop is a poor choice if you're using winforms. In winforms UI, input events are processed in the same thread as your program logic - in this case, game loop. This means that you *won't* get any input events while the loop is running (unless you create a second thread, of course.)

It is much better to use events for everything. There's a `Timer` class that you can use to have events fired periodically - every 100, or 50, ms. That's not enough resolution for an action game, but will probably be OK for a puzzle.

Then, you can have your matching, animation etc in `OnTimer` event handler, and input in `OnClick` event handler. Or, for simplicity, `OnClick` could just set some state like "player clicked here", and `OnTimer` would then check this state and act accordingly - that way, all game logic would be in the same place.

Take a look at `Timer` documentation here. What you need is place code that updates panels inside your timer handler (`TimerEventProcessor` in the example), and user input code inside corresponding `Click` handlers for your panels. Something along the lines of

```
panel1.Click += HandlePlayerInput; // this methods handles player's clicking on the panel. Use other events to capture other input like dragging.
panel2.Click += HandlePlayerInput;
panel1.Paint += RedrawPanel; // this method actually draws whatever there is in the panel
panel2.Paint += RedrawPanel;
timer1.Tick += UpdatePanelContents; // this is whatever logic is left in your game loop - generally, checking the state of panels, finding matches, and the like...

```

# Answer
> 0 votes
Attach a function that set a variable to each event, like:

```
gloabl eventfired=false
eventhandler=function(){
    eventfired=true
}

while(...){
    if(eventfired){
        //do stuff
        eventfired=false
    }
}

```

# Answer
> 0 votes
Since you are using WinForms, I suggest that you drop the game loop (by the way, where exactly are you planning to put it?), add a timer component and process game logic in timer "Tick" event handler. Each tick should be equivalent to one iteration of the loop.

And for the input handling you should probably do something like this:

1. Create a buffer where you store information about recently pressed keys. It can be as simple as an array with as many entries, as there are keys. Each entry should be a boolean value that indicates whether the specific key was pressed (where the index of the array is the same as the key code). Alternatively, you could create something like a HashSet. For each pressed key, you would then add it's key code.
2. Add event handlers to KeyDown/KeyUp or KeyPress events. Each handler should change the key press state information in the earlier mentioned buffer.
3. Each time the "Tick" event handler gets called, simply check the buffer for the state of the keys that you are interested in and run the appropriate game logic.

# Answer
> -2 votes
```
while(game.isRunning()){
    if(player1InputKey())
        DoSomething();

    if(player2InputKey())
        DoSomethingElse();

    Draw();
}

```

---
Tags: c#, gui
---


# Question
Title: OpenGL 2 and back vs 3 and forward: What are the key differences for 2D graphics?
OpenGL contexts before and after OpenGL 3.0 are rather different. So far I've really only worked with buffers on either side anyway, I do know the most notable difference is lack of Immediate Mode.

Throwing out Immediate Mode considerations all together, what important differences should I look out for specifically when coding low-level two dimensional operations in a 2-D graphics engine?

# Answer
> 9 votes
In terms of the contexts specifically, there's little difference. Most OpenGL implementations have most of the features of OpenGL 3.0+ even when using a legacy context, due to the way OpenGL extensions work.

If you're specifically asking about what features in OpenGL 3.0 are worth using, some of the best ones are geometry shaders and instancing, both of which are useful even for 2D graphics in certain circumstances. However, in most cases for simple 2D, all you're going to be doing is filling up a streaming vertex buffer every frame and making a single draw call, so there's really very little extra you're going to be doing.

In terms of 2D in OpenGL in general, just make sure you have a texture atlas (sprite sheet) so you very rarely need to change texture states. You want to avoid doing a draw call per sprite, as that is incredibly inefficient, and rather you want to batch together a lot of sprites and draw them all at once. Render with painter's algorithm, where "render" means pushing the geometry into a vertex buffer, and draw it at the end. Post-process as you see fit.

# Answer
> 3 votes
You can find a lot of information here: OpenGL registry. There is a lot of extensions. Each section (ARB, EXT, ...) are ordered according to adding date. New extensions are written against newer versions of OpenGL. For example - if I look at ARB section, almost every extension under ARB\_timer\_query (including) is written against OpenGL 3.2 or newer.

You also mentioned buffers, so you can try extension GL\_NV\_vertex\_buffer\_unified\_memory. Some info can be found here (there is also link to presentation).

Also shader\_buffer\_load should be usefull, if you are using shaders, but I haven't read the specification yet.

---
Tags: opengl, 2d, graphics-programming
---


# Question
Title: XNA beginner - can't display cannon in 2D tutorial
I taking my first steps with XNA. I'm building the old 2D tutorial that used to be posted on the XNA website. I got to the part where I display the cannon, but its not showing. Can someone please take a look and say what is wrong. The background texture is displaying fine.

Main class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace XNA2DTutorial
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D backgroundTexture;
        Rectangle viewportRect;
        GameObject cannon;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            backgroundTexture = Content.Load<Texture2D>("Sprites\\background");

            cannon = new GameObject(Content.Load<Texture2D>("Sprites\\cannon"));
            cannon.position = new Vector2(120, graphics.GraphicsDevice.Viewport.Height - 80);

            viewportRect = new Rectangle(0, 0,
                graphics.GraphicsDevice.Viewport.Width,
                graphics.GraphicsDevice.Viewport.Height);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
#if !xbox
            KeyboardState keyboardState = Keyboard.GetState();
            if (keyboardState.IsKeyDown(Keys.Right))
            {
                cannon.rotation -= 0.1f;
            }
            if (keyboardState.IsKeyDown(Keys.Left))
            {
                cannon.rotation += 0.1f;
            }
#endif
            cannon.rotation = MathHelper.Clamp(cannon.rotation, -MathHelper.PiOver2, 0);

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
            spriteBatch.Draw(backgroundTexture, viewportRect, Color.White);

            spriteBatch.Draw(cannon.sprite,
                cannon.position,
                null,
                Color.White,
                cannon.rotation,
                cannon.center,
                1.0f,
                SpriteEffects.None,
                0);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

Game object class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace XNA2DTutorial
{
    public class GameObject
    {
        #region Attributes
        public Texture2D sprite;
        public Vector2 position;
        public float rotation;
        public Vector2 center;
        #endregion Attributes

        #region Constructors
        public GameObject(Texture2D loadedTexture)
        {
            rotation = 0.0f;
            position = Vector2.Zero;
            sprite = loadedTexture;
            center = new Vector2(sprite.Width / 2, sprite.Height / 2);
        }
        #endregion Constructors

        #region Methods
        #endregion Methods
    }
}

```

# Answer
The problem comes from your `spriteBatch.Begin` call.

You're passing `SpriteSortMode.BackToFront` and since both of your `layerDepths` are equal to 0, I'd guess that the order would get mixed up when the sprites get drawn on the `spriteBatch.End` call, therefore drawing the background on top of the cannon.

Try passing `SpriteSortMode.Deferred` instead. This will draw the sprites immediately when you call `spriteBatch.Draw` and should draw them in the proper order. Works for me at least.
> 3 votes

---
Tags: xna, 2d
---


title: ways to make a physics engine

text:
# Question
Title: ways to make a physics engine
Hey so i've been looking into real time physics engines, which led me to the crazyLaggoa multiphysics engine by thiaga costa, and brought up the question of:

**What are some possible ways, ideas that have or have not already been done to make a real time physics engine? How about non-real time?**

I know the Lagoa engine uses meshes and a crapload of particles... and then there's the rigid body way of going about things..... Also i'm only at 2d level in creating games right now so any 2d physics ideas would be great too!

# Answer
Box2D was written as a tutorial on how to write 2D physics engines. The site contains links to a lot of presentations on how the algorithms work and how to make it efficient.

You might also want to look into this presentation done by the Pixeljunk Shooter team, describing how they did 2D fluids.

If you are interesed in 3D, read Realtime Collision Detection.

For more cutting edge offline physics this might be a good presentation. It describes how a new solver was developed for Maya, and I remember our physics programmer going nuts over it some years ago.
> 7 votes

---
Tags: physics, 3d-meshes, particles
---


title: XNA black glow (shadow-ish)

text:
# Question
Title: XNA black glow (shadow-ish)
How can I make a black shadow/glow **around** my drawn rectangle made of primitives? Drop-shadowing is easy, but it's not exactly what I am looking for.

# Answer
> 6 votes
Render your primitives to a render target, and then use a pixel shader to blur and blacken the render target when you draw it back onto the screen. Then simply draw your render target without a pixel shader (or render your original primitives) to the backbuffer.

The Bloom Postprocess sample on App Hub should provide a sufficient example of how to render to a render target and then post-process it with a blur, to implement your effect.

# Answer
> 1 votes
Make two textures - foreground and background.
First draw your shapes in black color on first texture, and then blur this texture.
Next draw your shapes in normal color on second texture.
Draw first, then second.
Keywords: postprocessing, RenderTarget2D, gaussian blur

---
Tags: xna
---


# Question
Title: When does a parallel-tasks engine becomes a good solution?
I'm often tempted to break the game I'm working on to try a parallel-tasks based architecture, but that don't seem a big requirement for my project so I avoid this for the moment. I'm planning to just try it in a toy project first, to "play with the concept."

Now, what I'm asking is, as lot of (non AAA) games do not require really really high performance, it feels like using a task-based engine isn't worth bothering until... what cases?

At the moment, I'm only guessing that it's necessary when you really need to exploit maximum performance of the (multi-core) hardware. Is there other cases where it's a good idea to use task-based engine? Or maybe, for new projects, it's always good to start with a task-based engine?

# Answer
> 7 votes
Threading is used in two situations:

1. When you have heavy work to do but need user responsiveness to be maintained.
2. When you need the power of more than one processing core on your favourite platform/minimum requirement.

If you can reasonably expect either or both of these things to be necessary, then go for it. Else, don't. Of course, nobody is going to stop you from threading for fun because you can, or to poke around and investigate it, but in terms of doing threadng for the benefits of actually gaining a multi-threaded application, then the two use cases above are pretty much it.

# Answer
> 15 votes
If your game is going to be remotely hardware intensive then you need threads to cope with all modern hardware; future CPUs coming out in the next year or two are starting to make 4 cores the minimum and up to 16 cores common for enthusiast/performance markets. If you're doing any multi-threading at all, definitely do a task-oriented architecture as any other threading model is inherently broken for forward-looking game engines.

Now keep in mind that by "tasks" I mean "jobs" and not "separate threads for different engine subsystems." You absolutely completely do not want to do something like having one graphics thread, one physics thread, one AI thread, etc. That doesn't scale beyond a tiny handful of cores and it doesn't actually gain you any real parallelism anyway. Physics shouldn't run more than one update per AI update (you want your AI to be able to react to physics events), and graphics has almost nothing new to render if physics hasn't run, so each subsystem naturally runs in a sequenced order. You don't even get any benefits out of having physics update the next iteration of the simulation while graphics is running the current iteration because there is so much data shared between the two that you either need lots of duplicated data structures (and the costs of copying from one to the other) or you end up with bad lock contention in shared data structure synchronization code.

What you want is to do is this. Create a thread spool. Run your game loop with the classic sequence of subsystem updates. However, for each subsystem, separate the workload into distinct separable batches, and distribute those to the thread pool. Wait for all jobs to complete before running the next state of the game update loop. Some subsystems may have multiple substages; e.g., graphics may issue a series of jobs to do culling and then a second series of jobs to do render queue creation. This approach avoids the synchronization problem of the first approach, scales to much larger numbers of cores, and frankly is just easier to code, debug, and maintain.

# Answer
> 0 votes
there are two uses in multithreading, one is to enhance your program performace and the other is to let the program run when there is a large process in progress. for example when you are trying to load some data it's bothering if your program hangs up, so you may use another thread for loading and keep the main Thread free to continue main loop. enhancing performance using threads is on the other hand somthing really hard. since usually you do every thing in a linear process and that is something in contrast with parallel processing. and you always have to use your main thread for graphical device updates that makes it even harder to split tasks between threads.

---
Tags: multithreading
---


title: Drawing a depth map properly

text:
# Question
Title: Drawing a depth map properly
I want to render a depth map by importing it from a file, then creating an array of vertices and indices, and then displaying it using a basic shader (just apply the view and projection matrices on it and then display). I'm aware of GPU-based solutions, however, I want to perform additional calculations using the CPU on the vertices before rendering them.

So, basically what I do is that I have my vertices with there depth in a grid, and then I import my triangles as follows:

```
+--+--+--+--+--+--+
¦ \¦ \¦ \¦ \¦ \¦ \¦
+--+--+--+--+--+--+   meaning that I simply split every quad spanned by four pixels
¦ \¦ \¦ \¦ \¦ \¦ \¦   into two triangles.
+--+--+--+--+--+--+
¦ \¦ \¦ \¦ \¦ \¦ \¦
+--+--+--+--+--+--+

```

When I took the first best depth map that I've found on google, I've got this result:

However, as soon as I'm moving the camera up, strange things happen:

The problem seems to only arise when multiple triangles are rendered behind each other. In this case, a triangle from the back (a black one at infinity depth or a wall behind the front object) seems to shine through. Also, when I use "PIX for Windows", and I use the "Debug this pixel" functionality, I get two triangles for each of the buggy pixels I've checked.

The rendering is done as follows:

`Initialize`

```
graphics.PreferredBackBufferWidth = 1280;
graphics.PreferredBackBufferHeight = 720;
graphics.IsFullScreen = false;
graphics.ApplyChanges();
IsMouseVisible = true;

```

`Draw`

```
GraphicsDevice.Clear(ClearOptions.DepthBuffer | ClearOptions.Target, Color.Black, 0, 0);
DrawModel();
spriteBatch.Begin();
DrawControls();
DrawFileBrowser();
spriteBatch.End();
base.Draw(gameTime);

```

`DrawModel`

```
GraphicsDevice.RasterizerState =
    new RasterizerState {
        CullMode = CullMode.None
    };
// [...]
// set up view and projection matrix
// [...]
GraphicsDevice.DrawUserIndexedPrimitives(
    PrimitiveType.TriangleList,
    vertices,
    0,
    vertices.Length,
    indices,
    0,
    indices.Length / 3);

```

What could be the problem in my rendering method? Do I have to somehow order my triangles from back to front? (no alpha-values are used) If yes, how can I order them?

Is it maybe some problem with the depth buffer? How can I fix it?

Any other ideas on how to fix the problem?

**Edit**

Shader code is basic:

```
float4x4 View;
float4x4 Projection;

void VS_Model(in  float4 inPosition            : POSITION,
              in  float4 inColor               : COLOR,
              out float4 outPosition           : POSITION,
              out float4 outColor              : TEXCOORD0)
{
    outPosition = mul(mul(inPosition, View), Projection);
    outColor = inColor;
}

void PS_Model(in  float4 inColor               : TEXCOORD0,
              out float4 outColor              : COLOR)
{
    outColor = inColor;
}

technique Model
{
    pass
    {
        VertexShader = compile vs_3_0 VS_Model();
        PixelShader = compile ps_3_0 PS_Model();
    }
}

```

# Answer
You seems to render without depth test on. This might make triangles further away render on top of closer triangles since they might be rendered afterwards.

The solution is to turn on depth testing in your render setup and set the depth compare function to Less or LessEqual. Remember to turn on depth write too if you happen to have that turned off.
> 2 votes

---
Tags: xna, c#, rendering, heightmap, depth-buffer
---


title: HD video capture gameplay?

text:
# Question
Title: HD video capture gameplay?
> **Possible Duplicate:**
> Tools to make a trailer…

I've developed some 3d experiences using unity3d and they are pretty much experimental at this level. Now the problem is that I need to make video captures in HD to showcase them. I've tried Camtasia 7 with divx compression, and still the quality is not Up to standard and number of dropframes are quite high. I'm running on a Core i7 cpu with geforce GT240. So I was thinking If it's possible to capturing the video remotely so one pc is in charge of capturing and one running the application. Or is there any better way to get the highest quality with least dropframes? Number of draw calls are around 2k(I know sounds crazy, but I can't make changes right now.)

Grazies.

# Answer
Everyone that I know (me included) uses FRAPS. It's generally very good but unfortunately not very free... We used FRAPS for our end of year project (shameless plug), no mocking!

Heart of Paper
> 2 votes

# Answer
If Fraps doesn't cut it, a hardware capture card should - something like the famous Blackmagic Intensity Pro card (or Shuttle USB 3.0) that can capture HDMI (hence also DVI) up to 1080i50/60 at a bargain-bin $199 price point.

It's actually a lot more expensive to try and capture a VGA signal as far as I know... analog VGA capture beyond very low resolutions tend to be a lot more expensive than an Intensity card and not produce anywhere near as good a result.
> 1 votes

# Answer
I don't know if there are any good capturing program or not but there are two ways to minimize framedrop:

one is to attach your pc vga output to another device (like dvdplayer or satelite receiver or any other device that can capture video) and use that as a capturing device.

second one is something that i won't go with it myself and it's to get a copy of video buffer in your code back to cpu and then save it. it also slows your program but much less compared to capturing applications.
> 0 votes

---
Tags: video, game-design
---


# Question
Title: Should there be a limit to how many in game models there is for a 3d MMORPG?
I was considering building a character creator/customizer program that would enable a player to create their own 3d model based off of a series of preset body parts. i.e. A player could choose to add the legs of a horse, the body of a man, wings of a falcon and the head of a snake. From there the player can then customize each body part by tweaking sliders responsible for length, thickness, color, position, etc.

Ultimately this will give players the ability to customize their characters with infinite degrees of freedom (not like preset customizations we see in some MMORPGs i.e. 8 hair cuts, 10 faces, 8 body types, etc.). So as you can imagine this would most likely lead to ever player having a different character.

**Would having thousands upon thousands of separate 3d character models some how slow the game down?**

*I consider that it would not because the most characters that would be rendered in the game I am working on would be 25 to 50 if that.*

# Answer
City of Heroes and Champions Online already do the things you are talking about.

Yes, it adversely affects performance in many areas - notably rendering and animation - as well as the art team (financial) budget. If you're trying to do this, you should make sure you have good performance budgeting tools throughout the entire art process, and good test cases.
> 5 votes

# Answer
You don't need to generate unique models in each case. Instead you can render a character as several models, one for each of the interchangeable parts you mention, with the tweakable aspects being applied to animation bones, or to shaders, etc.

However, to answer your question more generally, it is almost always quicker to render the same model twice than to render 2 separate models. Obviously this is mitigated if you are only rendering a subset of those in a given time frame because the other ones effectively do not exist at that stage. But rendering 25 different models will almost always be slower than rendering 3 or 4 each duplicated 6 or 7 times over.

But speed is relative - when does 'slower' become 'too slow'? If your characters are quite simple (ie. low number of polygons and small textures), then 50 on-screen at once is not a big deal. On the other hand, if they are complex, then even just 25 at once may be too much on some cards. It would be a shame to cancel a good feature because of performance concerns, so you need to know which end of the scale you would be at.

Luckily this is something you can test quite easily, by generating sample geometry of the sort of complexity you expect to use (which can be any simple object tessellated appropriately), and performing some test rendering to observe the real-world performance.

Interestingly, although you mention rendering as a bottleneck, potentially a worse problem is the networking aspect. Most MMOs store the majority of renderable assets on the client side and deploy them as part of the original install or the patching procedure. In your case, this would be impractical due to the number of permutations, so you'd have to stream them down during play. But this in turn means you can't easily render a character until all this data is on the client, which may be a problem when entering a busy area quickly (eg. teleporting or spawning in town). Again, this problem is reduced a bit if you just send a list of pre-existing model-parts that a character uses character instead of having to send a full model for each one.
> 4 votes

# Answer
I don't think so. Oblivion and Sims 3 both featured more models than you can even imagine.
> 0 votes

---
Tags: 3d, rendering, mmo, character
---


title: XNA - Non perspective projection?

text:
# Question
Title: XNA - Non perspective projection?
For a section of my game, instead of having a perspective projection, i would like to display an isometric view of an object.

So i don't want things to appear smaller if in a distance, etc.

Basically a proper isometric image.

Is there any way to do this in XNA?

# Answer
> 5 votes
You can assign any arbitrary matrix to the pipeline's projection matrix in XNA, even one that doesn't perform a useful projection (you probably won't see useful results doing that, but you *can*).

So you can construct an orthographic projection matrix yourself or use one of XNA's helper methods and use that. You'll also have to adjust the view matrix to position the camera from the angle you want, of course.

# Answer
> 1 votes
Matrix.CreateOrthographic should do the trick.

---
Tags: xna, isometric, projection
---


title: Exclusive ownership of game artwork

text:
# Question
Title: Exclusive ownership of game artwork
I'd like to pay an artist to create art assets for my game. Is it common for the client (myself in this case) to exclusively own all the artwork that I pay the artist to create and deliver? How can I make sure of this?

# Answer
> 6 votes
**I am not a lawyer; this is not legal advice.**

As long as the contract you agree states that you own the artwork and you make it clear to the artist that this is the case, you will have no problems.

I believe it is common for the client to own it. **But with everything: explicit is better than implicit. If you are not 100% certain you will own the assets, make sure it is written in the agreement.**

# Answer
> 3 votes
Dependant on the country you or your artist are in, the artist can still have certain rights to reproduce and use the work as he sees fit. The law applied will obviously depend on the country and hence there can be conflicting laws. Some countries stipulate that any creation remains the intellectual property of a person, and they cannot sell their intellectual property (at least not in it's entirety). I would recommend seeking a lawer's advice to make sure your contract is waterproof, and try to contract people in the same country as you.

See : http://en.wikipedia.org/wiki/Authors%27\_rights

Common law: employer owns the copyright in work created by employees

Civil law: employer enjoys an exclusive licence to the economic rights in work created by employees

# Answer
> 3 votes
What's common isn't nearly as important as what you and the other party agree to. It may be important, however, because an artist may wish to earn more if they also have to give all their rights away to their works.

You might also consider some sort of joint ownership agreement where there are some restrictions on what the author does with their work, such as a limit on who they can sell to in order to prevent them from selling their same work to a competitor of yours while also leaving them free to sell it for uses that are not in the same industry (e.g., for packaging on some instant noodles), but this can get very complicated (e.g., the instant noodles are targeted at gamers -- this may or may not be beneficial to you).

Hiring a competent lawyer with suitable experience in contract law would certainly be a wise choice on your part.

---
Tags: art, legal, outsourcing
---


# Question
Title: android game - how to store game elements so gc wont fire
I'm developing a android game and I have a question about storing the game elements without firing garbage collector.

My game needs a collection where the game elements are stored according to x,y positions (all game elements have x,y,width and height). The collection is then called every frame to retrieve the elements according to cameraX, cameraY, camera width and height (user can scroll around the game).

Example:

```
 function draw() {
   tmp = collection.getElements(tmp,cameraX,cameraY,cameraWidth,cameraHeight);
     for(int i = 0; i < tmp.size(); i++) {
        tmp.get(i).draw();
     }
  }

```

I'm currently using the Vector class to represent the collection elements, but the gc keeps firing every couple of minutes. I do all my allocations up front. I've also modified the getElements function to accept 1 more parameter - a temp vector(allocated upfront) which is filled with elements and then returned.

**How should I store the game elements so the gc wont fire (I prefer never if possible)?**

**I also add elements to the collection during runtime, do I have to allocate them upfront also?**

# Answer
Yes, if you allocate *anything* at runtime, it will eventually trigger the GC. Generally, you get around this by implementing an object pool ... that way, you can preallocate (or at least collect new instances for reuse) all objects like bullets and other entities to avoid triggering the GC.

*edit:* You also might want to use a memory profiler (like the eclipse memory analyzer) which can help you figure out what routine is generating objects at runtime.
> 3 votes

# Answer
I also suggest reading through the source code for Replica Island, which was developed by an Android engineer. He has a generic object pool class which can be extended for pools of custom objects. He also has a custom array class (with add/delete/search capabilities) to avoid having to use an iterator when traversing through an array of objects.

Also would like to mention that the DDMS on the Android SDK in Eclipse can track memory allocations (see Allocation Tracker tab in the image).
> 2 votes

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


# Question
Title: What designs are there for a component based entity system that are user friendly but still flexible?
I've been interested in the component based entity system for a while, and read countless articles on it (The Insomiac games, the pretty standard Evolve Your Hierarchy, the T-Machine, Chronoclast ... just to name a few).

They all seem to have a structure on the outside of something like:

```
Entity e = Entity.Create();
e.AddComponent(RenderComponent, ...);
//do lots of stuff
e.GetComponent<PositionComponent>(...).SetPos(4, 5, 6);

```

And if you bring in the idea of shared data (this is the best design I've seen so far, in terms of not duplicating data everywhere)

```
e.GetProperty<string>("Name").Value = "blah";

```

Yes, this is very efficient. However, it isn't exactly the easiest to read or write; it feels very clunky and working-against-you.

I personally would like to do something like:

```
e.SetPosition(4, 5, 6);
e.Name = "Blah";

```

Though of course the only way to get to that kind of design is back in the Entity-\>NPC-\>Enemy-\>FlyingEnemy-\>FlyingEnemyWithAHatOn kind of hierarchy this design tries to avoid.

Has anyone seen a design for this kind of component system which is still flexible, yet maintains a level of user friendliness? And for that matter, manages to get around the (probably the hardest problem) data storage in a good way?

**What designs are there for a component based entity system that are user friendly but still flexible?**

# Answer
> 13 votes
One of the things that Unity does is provide some helper accessors on the parent game object to provide a more user friendly access to common components.

For example, you might have your position stored in a Transform component. Using your example you would have to write something like

```
e.GetComponent<Transform>().position = new Vector3( whatever );

```

But in Unity, that gets simplified to

```
e.transform.position = ....;

```

Where `transform` is literally just a simple helper method in the base `GameObject` class (`Entity` class in your case) that does

```
Transform transform
{
    get { return this.GetComponent<Transform>(); }
}

```

Unity also does a few other things, like setting a "Name" property on the game object itself instead of in its child components.

Personally I don't like the idea of your shared-data-by-name design. Accessing properties by name instead of by a variable and having the user *also* have to know what type it is just seems really error prone to me. What Unity does is that they use similar methods as the `GameObject` `transform` property within the `Component` classes to access sibling components. So any arbitrary component you write can simply do this:

```
var myPos = this.transform.position;

```

To access the position. Where that `transform` property does something like this

```
Transform transform
{
    get { return this.gameObject.GetComponent<Transform>(); }
}

```

Sure, it's a *little* more verbose than just saying `e.position = whatever`, but you get used to it, and it doesn't look as nasty as the generic properties. And yes, you would have to do it the roundabout way for your client components, but the idea is that all your common "engine" components (renderers, colliders, audio sources, transforms, etc) have the easy accessors.

# Answer
> 3 votes
I would suggest some kind of Interface class for your Entity objects would be nice. It could do the error handling with checking to make sure an entity contains a component of the appropriate value as well in one location so you would not have to do it everywhere you access the values. Alternately, most of the designs I have ever done with a component based system, I deal with the components directly, requesting, for example, their positional component and then accessing/updating the properties of that component directly.

Very basic at a high level, the class takes in the entity in question and provides easy-to-use interface to the underlying component parts as follows:

```
public class EntityInterface
{
    private Entity entity { get; set };
    public EntityInterface(Entity e)
    {
        entity = e;
    }

    public Vector3 Position
    {
        get
        {
            return entity.GetProperty<Vector3>("Position");
        }
        set
        {
            entity.GetProperty<Vector3>("Position") = value;
        }
    }
}

```

# Answer
> 2 votes
In Python you can intercept the 'setPosition' part of `e.SetPosition(4,5,6)` via declaring a `__getattr__` function on Entity. This function can iterate through the components and find the appropriate method or property and return that, so that the function call or assignment goes to the right place. Perhaps C# has a similar system, but it might not be possible due to it being statically typed - it presumably can't compile `e.setPosition` unless e has setPosition in the interface somewhere.

You could also perhaps make all your entities implement the relevant interfaces for all components you might ever add to them, with stub methods that raise an exception. Then when you call addComponent, you just redirect the entity's functions for that component's interface to the component. A bit fiddly though.

But perhaps easiest would be to overload the \[\] operator on your Entity class to search the attached components for the presence of a valid property and return that, so it can be assigned to like so: `e["Name"] = "blah"`. Each component will need to implement its own GetPropertyByName and the Entity calls each one in turn until it finds the component responsible for the property in question.

# Answer
> 2 votes
To expand on Kylotan's answer, if you're using C# 4.0, you can statically type a variable to be dynamic.

If you inherit from System.Dynamic.DynamicObject, you can override TryGetMember and TrySetMember (among the many virtual methods) to intercept component names and return the requested component.

```
dynamic entity = EntityRegistry.Entities[1000];
entity.MyComponent.MyValue = 100;

```

I wrote a bit about entity systems over the years, but I assume I can't compete with the giants. Some ES notes (somewhat outdated and do not necessarily reflect my current understanding of entity systems, but it's worth a read, imho).

# Answer
> 1 votes
I see a lot of interest here in ES on C#. Check it out my port of the excellent ES implementation Artemis:

https://github.com/thelinuxlich/artemis\_CSharp

Also, a example game to get you started on how it works(using XNA 4): https://github.com/thelinuxlich/starwarrior\_CSharp

Suggestions are welcome!

# Answer
> 0 votes
I decided to use C#'s excellent reflection system. I based it off the general component system, plus a mixture of the answers here.

Components are added very easily:

```
Entity e = new Entity(); //No templates/archetypes yet.
e.AddComponent(new HealthComponent(100));

```

And can be queried either by name, type, or (if common ones like Health and Position) by properties:

```
e["Health"] //This, unfortunately, is a bit slower since it requires a dict search
e.GetComponent<HealthComponent>()
e.Health

```

And removed:

```
e.RemoveComponent<HealthComponent>();

```

Data is, again, accessed commonly by properties:

```
e.MaxHP

```

Which is stored component-side; less overhead if it doesn't have HP:

```
public int? MaxHP
{
get
{

    return this.Health.MaxHP; //Error handling returns null if health isn't here. Excluded for clarity
}
set
{
this.Health.MaxHP = value;
}

```

The large amount of typing is aided by Intellisense in VS, but for the most part there is little typing - the thing I was looking for.

Behind the scenes, I am storing a `Dictionary<Type, Component>` and having `Components` override the `ToString` method for name checking. My original design used primarily strings for names and things, but it became a pig to work with (oh look, I have to cast everywhere as well the lack of easy to access properties).

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


# Question
Title: How Often do you change Vertex/Index/etc Buffers?
So im still learning but I think i've got a grasp of most things DX11 (Well....beginner things) And I REALLY do apologize for all the questions.....but I'd rather understand EVERYTHING before I move on. I have 2 main functions (well 3 technically) that set up everything. I have Initgraphics(), InitD3D(), and Initpipeline()

D3D sets up the swap chain, viewport, depth buffer and back buffer. Initgraphics() Creates the Verticies (for the cube/whatever im drawing) and then creates the vertex buffer and copies it in.

```
// create the vertex buffer
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));

bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(VERTEX) * 24;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

dev->CreateBuffer(&bd, NULL, &pVBuffer);

// copy the vertices into the buffer
D3D11_MAPPED_SUBRESOURCE ms;
devcon->Map(pVBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms);    // map the buffer
memcpy(ms.pData, OurVertices, sizeof(OurVertices));                 // copy the data
devcon->Unmap(pVBuffer, NULL);

```

it also does the same thing for the Index buffer.

I also have initpipeline() (see code below)

```
// compile the shaders
ID3D10Blob *VS, *PS;
D3DX11CompileFromFile(L"shaders.hlsl", 0, 0, "VShader", "vs_5_0", 0, 0, 0, &VS, 0, 0);
D3DX11CompileFromFile(L"shaders.hlsl", 0, 0, "PShader", "ps_5_0", 0, 0, 0, &PS, 0, 0);

// create the shader objects
dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &pVS);
dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &pPS);

// set the shader objects
devcon->VSSetShader(pVS, 0, 0);
devcon->PSSetShader(pPS, 0, 0);

// create the input element object
  D3D11_INPUT_ELEMENT_DESC ied[] =
{
    {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0},
};

// use the input element descriptions to create the input layout
dev->CreateInputLayout(ied, 3, VS->GetBufferPointer(), VS->GetBufferSize(), &pLayout);
devcon->IASetInputLayout(pLayout);

// create the constant buffer
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));

bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = 176;
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;

dev->CreateBuffer(&bd, NULL, &pCBuffer);

devcon->VSSetConstantBuffers(0, 1, &pCBuffer);

```

Which from my understanding, compiles the shaders, makes the shader objects, creates the elements object and descriptions (Can someone explain what exactly this is?) and the Constant Buffer (which I only somewhat understand).

I guess my question(s) is.....when do these things need to change. I have a grip on the vertex and index buffers.....like I understand WHAT they are, but when would you change them? Same goes for Depth buffer, when would I ever want to change that (I understand back buffer). I know in my RenderFrame() function I select which ones to use using: right?

```
   devcon->IASetVertexBuffers(0, 1, &pVBuffer, &stride, &offset);
   devcon->IASetIndexBuffer(pIBuffer, DXGI_FORMAT_R32_UINT, 0);

```

Secondly, Do I only need to compile the shaders once and make the objects once? (unless I use different shader files presumably...maybe one for lights for one object and one for textures for a different object)....and what the heck does this:

```
// create the input element object
  D3D11_INPUT_ELEMENT_DESC ied[] =
{
    {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0},
};

// use the input element descriptions to create the input layout
dev->CreateInputLayout(ied, 3, VS->GetBufferPointer(), VS->GetBufferSize(), &pLayout);
devcon->IASetInputLayout(pLayout);

```

Stuff mean?. Also what is a Stencil Buffer.....im not really sure I understand why you create it (Does it ever need to change for that matter?)

# Answer
I'd recommend reading the Direct3D documentation as it will do a fantastic job at explaining most of your questions. For example, the page on Constant Buffers.

Stencil Buffers are described very elequantly on Wikipedia. You only need to create one if you plan on doing operations that involve creating and using masks to control the pixels to apply an operation to (much like a stencil in painting).

As with most API calls, the less you can call them the better. Most static resources (i.e. those that don't change during the course of the application running) are created once (for vertex buffers this can also involve populating with the vertices) and then set whenever they're needed. There are dynamic resources (again such as vertex buffers) that you might want to create the resource, but then you may change the contents of on a regular basis (such as for rendering UI or dynamic particles among other things).

You might want to change to a different depth buffer if you want to render to a different render target such as a dynamic cubemap, reflection, etc.

That last part where you create the InputLayout, you're basically telling D3D where to find the vertex data inside the vertex buffer. You can put whatever you want in the buffer, all D3D asks is you tell it how many bytes it needs to skip to the next vertex and what offset important bits are from the start of the vertex (such as position, normal and texture coordinates).
> 1 votes

# Answer
I am a newbie to directx, but as I have been learning it I find it helpful that I do already know a little bit about video cards and that might be relevant.

Directx makes you feel like you are creating typical programming resources, but I expect under the hood the important copies of those resources reside on the video card, i.e. your vertex buffer is probably created in memory, then copied to the video cards memory when you set it as the current vertex buffer. Your effect is probably loaded onto the video card.

Moving stuff to and from the video card causes a certain performance hit. That's probably why directx is set up as a state machine, because by and large it represents states of your video card.
> 0 votes

---
Tags: directx, directx11
---


# Question
Title: How do I generate projectiles toward the mouse pointer?
I'm making a top-down space shooter where the player controls a ship and can aim and shoot using the mouse cursor. How can I fire bullets *from the ship* at the *angle from the ship to the mouse cursor*?

# Answer
> 19 votes
If I understood your problem properly, you just want to shoot a bullet towards a mouse position. Here is how I would do:

First of all, you must find the movement required for the bullet to get to the mouse, like so:

```
Vector2 movement = mousePosition - bulletStartPosition;

```

Then, you should normalize it to have a vector with a length of 1 so that you can hold a vector which tells you in which direction to go, like so:

```
movement.Normalize();

```

But here you have a little problem, if the direction is equal to `(0, 0)` (meaning that the mouse is on the bullet start position), then you'll divide by zero, so make sure you check for that with the last piece of code:

```
if (movement != Vector2.Zero)
    movement.Normalize();

```

So, you've got the movement required to move towards the mouse. You have to keep a `Vector2` within your bullet class which holds the `Direction` of the bullet.

What's next? You have to actually move the bullet!

In your bullet update code, do the following:

```
bullet.Position += bullet.Direction * bullet.Speed * gameTime.ElapsedGameTime.TotalSeconds; // multiply by delta seconds to keep a consistent speed on all computers.

```

Where `bullet.Speed` is a float representing the bullet's speed in units per second.

Basically, here are the things to change:

Inside you bullet class, add a `float Speed` and a `Vector2 Direction`.

When shooting, set your `bullet.Direction` to `mousePosition - bullet.Position` and safely normalize it (by checking for equality with `Vector2.Zero` first).

When updating your bullet, do the following: `bullet.Position += bullet.Direction * bullet.Speed * gameTime.ElapsedGameTime.TotalSeconds;`.

It should work.

# Answer
> 6 votes
If you're having trouble calculating the angle, you can use this:

```
Vector2 target = mousePos - startPos;
float angle = Math.Atan2( target.Y, target.X );

```

---
Tags: xna, c#, mouse, control, trigonometry
---