title: Triple buffering causes input lag?

text:
# Question
Title: Triple buffering causes input lag?
Consider some time in between two vsyncs. Suppose the first display buffer is being used to display the current image, and suppose the game was really fast and computed and rendered the next image to the second display buffer and the next one after that to the third display buffer. That is the rendering to the second and third display buffer happens so fast that it occurs before the next vsync.

Suppose input from the user comes in now. What you would like is for the results of the input to show up on the next vsync or (probably more typical) the vsync after that. However, with the third display buffer already rendered the input can only effect the image after that. Meaning the input will only take effect at best 3 vsyncs later.

I wish i had an image to show the exact timings of what I mean.

# Answer
Double buffering was invented (if that's the right term to use) to avoid the user seeing a complex scene being drawn in front of them, instead you draw to an offscreen buffer, and then flip the one being displayed.

There's two ways you can do this, the first is to simply swap them whenever you're done with drawing the scene, but this has the drawback of causing tearing, if the game is drawn a lot faster than the screen update frequency (which is quite possible with even moderately complex looking games) you can even have multiple tears showing at the screen at any given moment in time.

The solution to avoid this is to synchronize the flipping to the vertical sync of the monitor. This means that you only swap the buffers when the screen is ready to draw a new screen update (in CRT monitors this was when it was physically re-targeting the top of the screen, hence vertical sync or vsync).

The downside with *this*, however, is that you spend a lot of time waiting for the vertical sync to happen. While this is going on you cannot draw at all since both buffers are needed for this.

To solve that problem you add a third buffer, thus allowing the graphics card to continue drawing immediately, as if you were flipping the buffers regardless of vsync. You now have three buffers, the first is being read by the graphics card and sent to the actual screen, the second is waiting for vsync to be swapped in, and the third one is being drawn on by your game.

**Now to the real question**, what happens if the game finishes rendering the scene to this third buffer before the vsync has been reached? Simple, the graphics card puts this one as the new one to be flipped in at vsync, and give you back the one that was waiting for vsync.

This means that if you have very simple graphics you can draw many more frames into a buffer than you ever actually see on the screen itself. But the upside is that the age of this drawn image that is being shown is less than it would have been for simple double buffering with vsync.

On a 60Hz (which is mostly standard on modern screens) monitor it takes 16.6667 ms between each vsync, lets call it 16ms for simplicity. If your game is simple enough so it only takes 2ms to render a scene then you would get the following results for double buffering:

1. Vsync, back-buffer is flipped with front-buffer
2. Game accepts input and does logic
3. Game is rendered (total time spent so far, 2ms)
4. Game stalls waiting for vsync (for another 14ms)
5. Vsync
6. Game accepts input...

So it only looks at the player input every 16ms. With tripple buffering:

1. Vsync
2. Accepts input
3. Rendered (total 2ms)
4. Swap back-buffers
5. Accepts input
6. Rendered (total 4ms)
7. Swap back-buffers
8. ...
9. Rendered (total 16ms)
10. Swap back-buffers
11. Vsync, latest rendered back-buffer is flipped with front-buffer

As you can see, you spend a lot more time rendering the simple scene, but the upside is that you accept player input every 2ms and does the game logic, and the image you see is only 2ms old, instead of 14ms as with double buffering, thus giving you less input lag and the feeling of more snappy controls. Keep in mind that the thrown away back buffers would never have been seen by the player in either case, so this isn't as much of a loss as it seems.
> 13 votes

---
Tags: opengl, directx, performance, double-buffering
---


title: Best peer-to-peer game architecture

text:
# Question
Title: Best peer-to-peer game architecture
Consider a setup where game clients:

1. have quite small computing resources (mobile devices, smartphones)
2. are all connected to a common router (LAN, hotspot etc)

The users want to play a multiplayer game, without an external server.

One solution is to host an authoritative server on one phone, which in this case would be also a client. Considering point 1 this solution is not acceptable, since the phone's computing resources are not sufficient.

So, I want to design a peer-to-peer architecture that will distribute the game's simulation load among the clients. Because of point 2 the system needn't be complex with regards to optimization; the latency will be very low. Each client can be an authoritative source of data about himself and his immediate environment (for example bullets.)

**What would be the best approach to designing such an architecture? Are there any known examples of such a LAN-level peer-to-peer protocol?**

**Notes:**

Some of the problems are addressed here, but the concepts listed there are too high-level for me.

*Security*

I know that not having one authoritative server is a security issue, but it is not relevant in this case as I'm willing to trust the clients.

*Edit:*

I forgot to mention: it will be a rather fast-paced game (a shooter).

Also, I have already read about networking architectures at Gaffer on Games.

# Answer
Take a look at this article about the networking architecture of Age of Empires II.

They managed to create a multiplayer game that ran great on a Pentium 90 with 16 MB RAM and a 28.8 kB/s modem connection. They did this by having each player run their own simulation, but synchronize their commands.

They have some clever tricks in there, I highly recommend it.
> 10 votes

# Answer
I've done this for a commercial PSP racing game, which worked both over an ad hoc network, and via a wireless hotspot. (Or to a static server on the Internet, if desired)

> Because of point 2 the system needn't be complex with regards to optimization

In my experience, this is not true. Wireless devices (especially small portable ones) are not like computers with wired network connections -- smartphones and wireless game consoles tend to have slow network interfaces for game purposes.

Don't get me wrong -- their throughput is usually good (that is, the amount of data per second; great for streaming movies or etc), but the latency on delivery of a particular packet can be extremely bad, and can be so highly variable that it's difficult to even estimate how long any individual packet will take to deliver. This variation becomes even worse as more wireless devices are packed together into one general area, as their signals start to interfere with each other. As a result of this, quite a lot of my time was spent in reducing the number of packets that needed to be sent, so we would have fewer packet collisions. (Note that this is somewhat less of a problem in the case where a powered network hotspot is involved, rather than having the devices talk to each other directly over an ad hoc network)

As an example of this sort of optimisation, our racing game took place in a world which had traffic lights. Thousands of them. And we needed to make sure that their signals were in synch between all the players in a network session. Rather than try to send packets around telling everyone which lights were in what state, we defined a static schedule for all of the traffic lights, and then just made sure that all the clients agreed on the current "game time". Since they all knew the game time, and all the traffic lights' states could be determined from the game time, we synchronised all that state data without actually sending any special data. This one change made a huge difference for our networking performance.

What that said, establishing a reliable clock synch between multiple wireless devices (with highly varying ping times due largely to packet loss) was a huge challenge. Happy to talk more about that if you've an interest.

> Each client can be an authoritative source of data about himself and his immediate environment (for example bullets.)

This is what we did, and it worked well for us in our situation (cars). The problematic part, of course, is when an object stops being closer to player 'a' than to player 'b', and its ownership therefore transfers from one player to another.

This is actually a surprisingly complex negotiation between players, where game 'a' proposes to game 'b': "I think this object is closer to you. You should take control of it." And then game 'b' may either accept, or may decline, based upon its own view of the situation. Differences in the perceived game state between 'a' and 'b', and the change in time between when the request and response are sent and received makes this a particularly nasty little negotiation to get reliable, and it can easily degenerate into a game of "hot potato", with object ownership bouncing around continually between multiple players. And even when it does work properly, when viewed from the vantage point of game 'c', there's often a small visual discontinuity when an object switches from the ownership of one player to the ownership of another, just due to the different ping times that game 'c' has to the other two players.

My intuition is that this sort of "object ownership" approach is likely to be too cumbersome for small, short-lived objects like bullets. We used it for traffic cars and AI racers, which tended to live in the simulation for a relatively long time. It seems like a more performant approach, if you're willing to trust the clients, would be to have each player's game own their position and their projectiles, and declare when that player has been hit by someone else's projectile. (So as "game A", I'm responsible for saying where player A and player A's projectiles are, but player B is responsible for saying whether I've hit player B). With some good dead-reckoning, you should be able to get pretty reasonable behaviour out of a system like this.
> 5 votes

# Answer
I recommend you use lock step peer to peer architecture.

You start by counting your game frames after the game starts. One client render the 1st frame then send the ready message to other clients and wait to receive ready message from other clients.

Now all clients can go for 2nd frame. Render the frame, send and receive commands, update world, update physics and ... after that sending ready message to each other.

This solution is very good for LAN games and all of your clients will be in sync.

with this type of networking you can be sure all of your clients are in sync so you can test the best way that suits your need.

1st way is only send the inputs to others and each client simulate running, firing , collision detection and etc the 2nd way is each client send the information about his character to others like position, rotation, state, animation frame and etc so other clients only calculates their stuff and send them over network but first way is more secure.
> 1 votes

---
Tags: architecture, networking, multiplayer, mobile, peer-to-peer
---


title: Using 2d collision with 3d objects

text:
# Question
Title: Using 2d collision with 3d objects
I'm planning to write a fairly basic scrolling shoot 'em up, however, I have run into a query with regards to checking for collision. I plan to have a fixed top down view, where the player and enemies are all 3d objects on a fixed plane, and when the enemy or player fires at the other, their shots will also be along this fixed plane.

In order to handle the collision, I have read up a bit on collision detection in 3d, as it is not something I have looked into previously, but I'm not sure what would be ideal for this situation. My options appear to be:

* Sphere collision, however, this lacks the pixel precision I would like
* Detection using all vertexes and planes of each object, but this seems overly convoluted for a fixed plane of play
* Rendering the play screen in black and white (where white is an object, black is empty space), once for enemies and once for the player, and checking for collisions that way (if a pixel is white on both, there is a collision)

Which of these would be the best approach, or is there another option that I am missing?

I have done this previously using 2d sprites, however I can't use the same thinking here as I don't have the image to refer to.

**Edit:** For clarity, I just wanted to add some additional information.

One of the things that I would like to account for is if the player or enemy is rotated in some way, which would mean intersecting along 1 Z plane would not be completely accurate. For example, if there is banking on the player's ship when they move from side to side, the tips of their ship would be above and below the central plane, but I would still like these parts to be possible to hit.

Secondly, I plan to have different sizes and shapes for the player's craft, where the size and shape affects the hit box and is one of the properties the player can use to choose which ship they would like to use.

# Answer
> 1 votes
Your gameplay is 2D, so your collision detection should be too. Pixel-perfect collision is an unusual approach for shmups - generally these use hitboxes (often considerably smaller than the entities, for the player at least).

I'd generally go for circle-circle collisions, possibly with circle-poly collisions to allow more complex boss shapes (using an aggregation of circles and convex polys) for a game like yours. That would, of course, mean you'd need to specifically define your hitboxes for each entity.

---
Tags: xna, 2d, collision-detection
---


# Question
Title: Why use 3d matrix and camera in 2D world for 2d geometric figures?
I'm working in XNA on a 2d isometric world/game and I'm using DrawUserPrimitives to draw some geometric figures...

I saw some tutorials about creating dynamic shadows but I didn't understood why they use a "3d" matrix to control the transformations since the figure I'm drawing is in 2d perspective.

I know I'm drawing a 2d figure in 3d but I still can't understand if I really need to work with the matrix.

Is there any advantage in using a 3d Matrix to control camera and view?

Any reason why I can't just update my vertex's positions by using a regular method since the view is always the same... And since I want to work only with single figures, won't this cause all the geometric figures have the same transformations simultaneously?

To understand better what I mean here's a video http://www.youtube.com/watch?v=LjvsGHXaGEA&feature=player\_embedded

# Answer
> 4 votes
> Is there any advantage in using a 3d Matrix to control camera and view?

You don't have a choice. It's not really about advantage or disadvantage; it's the only way to go.

XNA doesn't have a 2D graphics API; it's rendering API is *only* 3D. You can implement 2D in terms of 3D by simply only considering your X and Y dimensions, and you can abstract this out to provide wrapper interfaces that look like they are fully 2D, but in order to submit any kind of rendering operations to the XNA API you're going to have to speak it's language (the language of the underlying Direct3D implementation), which is 3D.

> Any reason why I can't just update my vertex's positions by using a regular method since the view is always the same... And since I want to work only with single figures, won't this cause all the geometric figures have the same transformations simultaneously?

Constantly updating the vertex buffer every frame is less efficient, because that data must be copied back and forth to the GPU repeatedly. Conversely, initializing your vertex buffer once and simply transforming it on the GPU is much more efficient.

---
Tags: xna, c#, 2d, camera, matrix
---


# Question
Title: Implmenting RLE into a tilemap or how to create a large 3D array?
Currently I've been using a 3D array for my tiles in a 2D world but the 3D side comes in when moving down into caves and whatnot. Now this is not memory efficient and I switched over to a 2D array and can now have much larger maps. The only issue I'm having now is that it seems that my tiles cannot occupy the same space as a tile on the same z level. My current structure means that each block has its own z variable. This is what it used to look like:

map.blockData\[x\]\[y\]\[z\] = new Block();

however now it works like this

map.blockData\[x\]\[y\] = new Block(z);

I'm not sure why but if I decide to use the same space on say the floor below it wont allow me to.

Does anyone have any ideas on how I can add a z-axis to my 2D array?

I'm using java but I reckon the concept carries across different languages.

Edit: As Will posted, RLE sounds like the best method for achieving a fast 3D array. However I'm struggling to understand how I would even start to implement it? Would I create a 4D array the 4th being something which controls how many to skip? Or would the x-axis simply change altogether and have large gaps in between - for example \[5\]\[y\]\[z\] would skip 5 tiles? Is there something really obvious here which I am missing?

The number of z levels I'm trying to have is around 66, it would be preferable that I can have up to or more than 1000 in x and y.

# Answer
> 6 votes
It sounds like most of your cells are unoccupied.

You can dramatically reduce memory if you store only occupied cells; this is termed "sparse" and is straightforward using a simple run-length-encoding (RLE) scheme (the runs of occupied and unoccupied cells are length-encoded).

For example, you could have an array of block instances:

```
Block[] blocks; // block[0] might be Grass, block[4] might be Water etc

```

Imagine that each X row on the 3D map is an integer array:

```
int[][][] data = new int[MAX_Z][MAX_Y][];
data[4][4] = new int[]{ 3, 2, 1, 1, 2, 1, 2, 3, 2, 2, 1 }; // some test row

```

The first integer says how many cells to skip, then how many cells are occupied, then the integer indices of the blocks in them, and so on. So that test row is:

```
  | (x=0)
3 | skip 3 (x=3)
2 | occupied 2
1 | block[1]
  | (x=4)
1 | block[1]
  | (x=5)
2 | skip 2 (x=7)
1 | occupied 1
2 | block[2]
  | (x=8)
3 | skip 3 (x=11)
2 | occupied 2
2 | block[2]
  | (x=12)
1 | block[1]

```

Its straightforward to iterate over, and not too complicated to insert into:

```
void debug_line(int z,int y) {
   int[] row = data[z][y];
   if(row == null) return; // nothing on that line
   int x = 0;
   for(int i=0; i<row.length; ) {
      int skip = row[i++], occupied = row[i++];
      for(int j=0; j<skip; x++, j++) System.out.print("-");
      for(int j=0; j<occupied; x++, j++) System.out.print(row[i++]);
   }
}

```

This debug function iterates over all `x` in that row and emits this:

```
---11--2---21

```

You can likely use shorts or pack into bytes to dramatically reduce RAM further. And completely empty rows, rather than having an empty array (allocated and taking up space), can simply be `NULL`.

(I picked X rows rather than Z because its likely that you are drawing on the XY plane; you always want to be skipping along on the ground plane)

You can also likely share actual block instances; you don't need 100 instances of the 'grass' block if the properties are the same.

This will allow you to use 3D again.

More complicated structures like sparse octrees can reduce memory requirements much further. I'd recommend simple RLE first and then something 'better' if you hit performance or memory problems.

# Answer
> 2 votes
From what I understood you're now storing the `Z` value as part of the `Block`, but you need the ability to store more than one `Block` in each array position.

```
class Block
{
    int z;
}

```

**Option 1**

One possibility is to create a 2D array of `ArrayList<Block>` instead of `Block`. This way each position in the array can store more than one `Block` if needed. So you would create the data structure like this (I think, it's been many years since I've used Java):

```
ArrayList<Block>[][] data = new ArrayList<Block>[width][height];
for(int x=0; x!=width; ++x)
    for(int y=0; y!=height; ++y)
        data[x][y] = new ArrayList<Block>();

```

And add a new block with the `add` method of the `ArrayList` such as:

```
data[x][y].add(new Block(z));

```

This way you can have as many `Block` as you need in a single position. You could also use a jagged array instead of an `ArrayList` if you already from the start how many elements will be in that position, and it will probably have less overhead than the `ArrayList`.

**Option 2**

Another possibility is instead of using the `ArrayList`class, to make the list of blocks *implicit* to the `Block` class. You could do this by adding a `Next` property to the class that points to the next `Block` that is shared by the same position. I also added an helper method that recursively adds a new `Block` to this implicit list:

```
class Block
{
    int z;
    Block next;

    void Add(Block block)
    {
        if(next== null)
            next= block;
        else
            next.Add(block);
    }
}

```

With this you can keep using the same structure as before:

```
Block[][] data = new Block[width][height];

```

But when adding a new `Block` you'd do this instead:

```
Block block = new Block(z);
if(data[x][y] == null)
    data[x][y] = block;
else
    data[x][y].Add(block);

```

# Answer
> 1 votes
Ok first things first. map.blockData\[x\]\[y\] points to a place in memory so when you assign a new object reference to map.blockData\[x\]\[y\] the old one is overwritten so you can't use it multiple times.

Now I'm not sure why you can use larger levels when using a 2D array instead of 3D array, are you having memory problems? This seems unlikely because it looks like Block is a class so the 3D-Array only stores pointers. However if most of the times there is only one block at (x,y) you can save space the following way.

Store the Z component in the block. Then create a new array like this:

```
Block[][][] map = new Block[Width][Height][];

```

Then populate the array like this:

```
map[x][y] = new Block[]{block1, block2};
map[x+1][y] = new Block[]{block3};

```

This is called a jagged array, and it uses less memory because we can vary the size of the array for the 3rd component. You can get the size by using map\[x\]\[y\].length.

Now when rendering you get the block(s) for (x,y) as usual and you check map\[x\]\[y\].Length to see how much blocks are stacked on each other. Finally you can check with map\[x\]\[y\]\[z\].Z how high that particular block should be placed.

# Answer
> 0 votes
You don't give enough detail for me to conclude if this is a viable method but I'll throw it in there anyway as a possible solution. Someone else may find it useful if you don't.

You don't say how many zlayers there are and if there are only very few layers then this may be an option.

What you can do is store more one tile data in a long variable by using bits.

Let say you have 4 layers and 255 tiles per layer to keep my explanation simple.

You can do that in a single long by using bitwise AND and rotation.

first 8 bits could be layer 1, second 8 bits could be layer 2, and so on.

in order to get the right tile in this particular data format for the layers you would do something like

```
tile1 = (map.blockData[x][y] & 0x000000FF);
tile2 = (map.blockData[x][y] & 0x0000FF00) >> 8;
tile3 = (map.blockData[x][y] & 0x00FF0000) >> 16;
tile4 = (map.blockData[x][y] & 0xFF000000) >> 24;

```

Of course this all depends on how many layers and tiles you have for this method to work.

---
Tags: java, tilemap
---


title: Fog with Blend in OpenGL

text:
# Question
Title: Fog with Blend in OpenGL
I want to add fog in my scene which contain transparent textures made by Blend ,

when i enable the fog the transparent textures appear white From a distance but when i disable it the textures appear well.

What is the solution to the problem of whiteness?

Fog Code:

```
GLfloat fogColor[4]= {0.5f, 0.5f, 0.5f, 1.0f};
glClearColor(0.5f,0.5f,0.5f,1.0f);
glFogi(GL_FOG_MODE, GL_LINEAR);
glFogfv(GL_FOG_COLOR, fogColor);
glFogf(GL_FOG_DENSITY, 0.35f);
glHint(GL_FOG_HINT, GL_DONT_CARE);
glFogf(GL_FOG_START, 1.0f);
glFogf(GL_FOG_END, 1000.0f);
glEnable(GL_FOG);

```

Screenshot

# Answer
The fog is working as it should work in fixed pipeline. It won't change, because fixed-pipeline support has been dropped.

Today is rendering done with shaders - GLSL.

Fog can be easily implemented in fragment shader:

```
uniform float fogStart;
uniform float fogEnd;

void main()
{
    ....

    fogFactor = (gl_FragDepth-fogStart)/(fogEnd-fogStart);
    fogFactor = 1 - clamp( fogFactor, 0.0, 1.0 );

    gl_FragColor = vec4(gl_FragColor.xyz, gl_FragColor.w * fogFactor);

}

```
> 4 votes

---
Tags: c++, opengl, graphics, c
---


# Question
Title: Handling commands or events that wait for an action to be completed afterwards
Say you have two events: Action1 and Action2. When you receive Action1, you want to store some arbitrary data to be used the next time Action2 rolls around. Optimally, Action1 is normally a command however it can also be other events. The idea is still the same.

The current way I am implementing this is by storing state and then simply checking when Action2 is called if that specific state is there. This is obviously a bit messy and leads to a lot of redundant code. Here is an example of how I am doing that, in pseudocode form (and broken down quite a bit, obviously):

```
void onAction1(event) {
    Player = event.getPlayer()
    Player.addState("my_action_to_do")
}

void onAction2(event) {
    Player = event.getPlayer()

    if not Player.hasState("my_action_to_do") {
        return
    }

    // Do something
}

```

When doing this for a lot of other actions it gets somewhat ugly and I wanted to know if there is something I can do to improve upon it.

I was thinking of something like this, which wouldn't require passing data around, but is this also not the right direction?

```
void onAction1(event) {
   Player = event.getPlayer()
   Player.onAction2(new Runnable() {

       public void run() {
           // Do something
       }

   })
}

```

If one wanted to take it even further, could you not simply do this?

```
void onPlayerEnter(event) { // When they join the server
    Player = event.getPlayer()
    Player.onAction1(new Runnable() {

       public void run() {

           // Now wait for action 2
           Player.onAction2(new Runnable() {
               // Do something
           })

       }

    }, true) // TRUE would be to repeat the event,
             // not remove it after it is called.
}

```

Any input would be wonderful.

# Answer
> 1 votes
I think your initial example is the simplest. If I were to do anything I would have a central ActionManager. Actions could post data to it for other actions to pick up later. I would almost be like an Event system except that "Messages" aren't delivered to an entity, they simple sit, waiting for an Action to pick them up.

That would help decouple Action1 from Action2 so that if you wanted to connect Action3 to Action2 as well you could. Action2 doesn't know or care about 1 or 3, all it cares about is to look for an Action2Message.

# Answer
> 0 votes
It's hard to come up with a solution without knowing how your ActionListener/Handler/Manager.. looks like

the way i would do it (i'm a c# developer, but i think the same is possible in java):

instead of registering the state

> ```
> Player.addState("my_action_to_do")
>
> ```

i would have a Stack of ActionListeners for Action2 events, to which the void onAction1() event would add a handler that will be called if Action2 is invoked:

(i'll try in java, might not be executable though):

```
Stack<ActionListener> onAction2Events = new ...;

void onAction1(event) {
    Player = event.getPlayer();
    onAction2Events.add(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
          // this code will be called if onAction2 is invoked
      }
    });
}

void onAction2(event) {
    Player = event.getPlayer()

    InvokeEvent(onAction2Events); // calls all ActionListeners / states that ware added

    // ...
}

void InvokeEvent(Stack<ActionListener> listenerStack) {

    while(listenerStack not empty)
    {
        listenerStack.pop().actionPerformed(...);
    }
}

```

---
Tags: java, events
---


# Question
Title: How do I make camera move at same speed when rotating and moving forward
I made a camera in DX9. To move forward I press the Up arrow. To rotate on the Y axis I use the mouse. When I perform these movements on their own the camera moves at the speed I want.

However, if I hold down Up and move the mouse at the same time then the camera moves a lot faster than it should. I want it to move at the same speed as it does when only the Up arrow is pressed.

I think I need to normalize something somewhere but not sure what and not sure where. Have tried various combinations without success so if anyone can point me in the right direction that would be great. Thanks.

I've post code below.

```
#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)

LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    if( KEY_DOWN(VK_UP))    MovePlayer(D3DXVECTOR3(0, 0, -1.0f));
    if( KEY_DOWN(VK_DOWN))  MovePlayer(D3DXVECTOR3(0, 0, 1.0f));

    switch( msg )
    {
        case WM_MOUSEMOVE:
        ProcessMouseInput();
    }
}

void  MovePlayer( D3DXVECTOR3 in_vec )
{
    D3DXMATRIX CameraRot;
    D3DXMatrixRotationY(&CameraRot,D3DXToRadian(AngleY));
    D3DXVECTOR3 CameraRotTarget;
    D3DXVec3TransformNormal(&CameraRotTarget,&in_vec,&CameraRot);
    CameraPos +=  (m_timeElapsed * CameraRotTarget);
}

void ProcessMouseInput()
{
    GetCursorPos( &CurrentMouseState );

    if ((CurrentMouseState.x != GameMouseState.x) || (CurrentMouseState.y != GameMouseState.y))
    {
        int dx = CurrentMouseState.x - GameMouseState.x;
        int dy = CurrentMouseState.y - GameMouseState.y;
        AngleY+=m_timeElapsed*dx*7.0f;
    }
    GameMouseState = CurrentMouseState;
    // Set back to window center in Render function
}

VOID UpdateCamera()
{
    D3DXVECTOR3 CameraOrigTarget(0, 0, -1);
    D3DXVECTOR3 CameraOrigUp(0, 1, 0);

    D3DXMATRIX CameraRot;
    D3DXMATRIX CameraRotX;
    D3DXMatrixRotationX(&CameraRotX,D3DXToRadian(AngleX));
    D3DXMATRIX CameraRotY;
    D3DXMatrixRotationY(&CameraRotY,D3DXToRadian(AngleY));
    CameraRot = CameraRotX * CameraRotY;
    D3DXVECTOR3 CameraRotTarget;
    D3DXVec3TransformNormal(&CameraRotTarget,&CameraOrigTarget,&CameraRot);

    D3DXVECTOR3 CameraTarget;
    CameraTarget = CameraPos + CameraRotTarget;

    D3DXVECTOR3 vUpVec( 0.0f, 1.0f, 0.0f );
    D3DXMatrixLookAtLH( &matView, &CameraPos, &CameraTarget, &vUpVec );
    g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

    D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI / 4, 1.0f, 1.0f, 100.0f );
    g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );
}

```

# Answer
> 1 votes
the problem is that the key functions are inside the message proc:

```
if( KEY_DOWN(VK_UP))    MovePlayer(D3DXVECTOR3(0, 0, -1.0f));

```

the MsgProc will probably be called a lot of times if the mouse is moved a lot and cause mutliple WM\_MOUSEMOVE events during a single tick/frame/update.

the

```
if( KEY_DOWN(VK_UP))    MovePlayer(D3DXVECTOR3(0, 0, -1.0f));
if( KEY_DOWN(VK_DOWN))  MovePlayer(D3DXVECTOR3(0, 0, 1.0f));

```

should not be inside the msgproc.

You mixed up the GetAsyncKeyState function that might only be called once per frame, with the WM\_KEYDOWN, WM\_KEYUP events

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


# Question
Title: Detect if square in grid is within a diamond shape
So I have a game in which basically everything is a square inside a big grid. It's easy to check if a square is inside a box whose center is another square:

```
*** x
*o*      --> x is not in o's square
***

**x
*o*      --> x IS in o's square
***

```

This can be done by simply subtracting the coordinates of o and x, then taking the largest coordinate of that and comparing it with the half side length.

Now I want to do the same thing but check if x is in o's diamond, like so:

```
  *
 **x
**o**    --> x IS in o's diamond
 ***
  *

```

What would be the best way to check if a square is in another square's surrounding diamond-shaped area, given the diamond's half width/height?

# Answer
> 3 votes
The diamond shape here has 2 useful properties:

1. A diamond that has a width of *x* fits completely within the square of width *x*
2. A diamond like this (ie. a square rotated through 90 degrees) based on a grid pattern can be defined by the Manhattan distance from the centre of the diamond.

So, an efficient check to see if a value is within this diamond would be this:

1. Iterate through each position in the containing square of the equivalent size. You can quickly calculate these bounds by subtracting/adding the square size to the centre position.
2. For each of those possible positions, it is in range if the Manhattan distance to the centre is less than or equal to the half-width/height of the diamond.

---
Tags: c++, vector, coordinates, grid
---


title: Find nearest tile of type x

text:
# Question
Title: Find nearest tile of type x
I currently have an array of tiles which makes up the tilemap (stored as an int array) and I want an NPC to be able to move itself to the nearest tile of type X (ie find the nearest tree and chop it down). What's the best algorithm to use to find the nearest tile of a certain type given a location (x,y)?

# Answer
> 5 votes
Problems like this can easily be solved by using Dijkstra's algorithm. See this answer for an explanation of how it works.

The others suggested a flood-fill, but that won't work (or at least won't be optimal) if there are obstacles (not trees) somewhere along the path. If there are only a few items to find, you could also use A\* with an appropriate heuristic (eg. min. straight-line distance to items).

**Update:** If you don't want to implement Djikstra's algorithm yourself but have an A\* implementation in your path-finding library, you could also set the A\* heuristic to a constant value (eg. that it always returns 0). That way, A\* will behave the same as Djikstra's.

Also note that in the examples I linked to, there's usually one goal-node to find. But it works just as well when searching for a "type" of node (just end the search whenever you find a tile of your desired type).

# Answer
> 4 votes
If you know absolutely nothing about where such a tile could be I would suggest a sort of breadth first style floodfill:

```
PathNode start;
PathNodeType query; // the type we are looking for
Queue<PathNode> queue; // gives us a breadth first style search
HashSet<PathNode> visited; // tiles we already visited
queue.Push(start)

while(queue.Count > 0){
    PathNode current = queue.Pop();
    foreach(PathNode neighbour in current.Neighbours)
    {
        if(!visited.Contains(neighbour))
        {
            visited.Add(neighbour);
            if(neighbour.Type == query)
            {
                return neighbour;
            }
            else if(neighbour.IsWalkable)
            {
                queue.Push(neighbour);
            }
        }

    }
}

```

This algorithm first searches the tiles closest to start and then starts circling wider and wider over the walkable tiles until a tile of the given tile is found. By first checking if a neighbour tile is of the given type and only then checking if it is walkable we can also found tiles that are next to walkable tiles but arent walkable itself.

# Answer
> 0 votes
One approach is a simple breadth first search. If you've heard of A\*, this is sort of the basis for that algorithm. Except you don't have a known goal location, so you can't direct the search in any one direction So you search all directions at once! There's some implementation details and nice little examples for tile based games here.

# Answer
> 0 votes
Could you add some more details like what language you are in? I mean I guess there could be a general algorithm.

If you have these different tiles in classes per se, you could add a move function in your NPC class or method. It would have to "see" the tile, so you could give it a tile radius and say if anything within X amount of squares of the NPC is this ID type of tile, then move to its x and y location.

An example in an OO language like Java:

```
    public Tile Tree;

    Tree.cutTree(NPC.getX, NPC,getY, Tree.getX, Tree.getY)

    public void cutTree(int NPCX, int NPCY, int treeX, int treeY)
    {
      if(treeX >= NPCX >= 5)
      {
         if(treeX >= NPCX >= 5)
         {
            NPC.move(treeX - 1, treeY - 1);
         }
      }
    }

```

Again I don't know EXACTLY what numbers to add and whether you have a move() function, but basically I would use the x and y position of the two tiles (if you can access each tree tile in the array).

The if statements are where I would use like the edge of the frame or screen but you have to remember if the map of tiles is big enough you could be accessing a tree tile across the map.

---
Tags: algorithm, ai, tiles, path-finding, tilemap
---


# Question
Title: Discovering path through unknown territory
Let's say all the AI knows about it's surroundings is a pixel-map that it has which clearly shows walkable terrain and obstacles. I want the AI to be able to traverse this terrain until it finds an exit point.

There are some restrictions:

* There is always a way to the exit in the entire map that the AI walks around in, but there may be dead ends. The path to the exit is always pretty random, meaning that if you stand at crossroads, nothing indicates which direction would be the right one to go.
* It doesn't matter if the AI reaches a dead end, but it has to be able walk back out of it to a previously not inspected location and continue its search there.
* Initially, the AI starts out knowing only the starting area of the whole map. As it walks around, new points will be added to the pixel-map as the AI corresponding to the AIs range of sight (think of it like the AI is clearing the fog of war)
* The problem is in 2D space. All I have is the pixel map.
* There are no paths in the pixel map which are "too narrow". The AI fits through everything.
* The AI does not know where the endpoint is (it is hidden in the map)
* The AI traverses the terrain in real time
* It shouldn't be a brute force solution. E.g. it would be possible to simply find a path to each pixel in the pixel map that is yet undiscovered (with A\*, for example), which will lead to the AI discovering new pixels. This could be repeated until the end is reached.
* The path doesn't have to be the shortest path (this is impossible without knowing the entire map beforehand), but when movements within the visible area are calculated, the shortest and from a human standpoint most logical path should be taken (e.g. if you can see a way out of your room into a hallway, you would obviously go there instead of exploring the corner of your current room).

What kind of approaches to solve this problem are there?

# Answer
> 5 votes
Since finding the exit is the first goal, then the process will have two phases: clearing fog, then finding a path.

When clearing fog, the goal should be to clear it as efficiently as possible. A simple way to do this is to pick the next step that will clear the most fog, or pick the next step that will take you toward the nearest fog if no immediate fog is available to clear. More complex algorithms will depend on the type of terrain... a hedge maze has a different optimal exploration method than a wargame hex map with fields, forests, and rivers.

When the exit is found, then just path to it, with the obvious 'fogged terrain has a moderate cost that gets updated to the real cost once explored'. The fog cost can be adjusted to whatever level you desire... very high costs will have the AI take long backtracks to follow explored paths to the exit, while lower costs encourage the AI to attempt to find new shorter routes. Which is better depends on your terrain generator.

# Answer
> 3 votes
You may want to look at a game called Brouge. It's an open source game and is has an "auto explore" feature. From what I can tell, essentially the algorithm is:

1. Pick a random direction and start going
2. Continue exploring, choosing random directions at intersections
3. Once you've reached a dead end, path towards the nearest "fog of war"
4. Loop to 2 until exit is discovered.

In Brouge, I believe the character will keep exploring until all the fog of war is gone, but you'd cut out early. It's worth downloading and watching it work so you can get a better idea.

There's also some other links on the RogueBasin that might be helpful. They don't describe your exact problem, but they'd be useful to break parts of them off and use those in your solution.

How to create an anticipating wall-following pathfinder

# Answer
> 1 votes
Generate waypoints from a god perspective and let the AI have a collection of waypoints it knows of (add them as the AI discovers them). Now whenever the AI has reached its temporary goal score all the reachable Waypoints by a few factors like distance and probability that it doesn't lead to already discovered area (if the path goes to the left and you already discovered a large area to the left it's likely that it will lead there, for example). Having that score you can now go to the waypoint with the highest score. This can be repeated till the AI has found the exit.

---
Tags: ai, path-finding
---


# Question
Title: How can I render a semi transparent model with OpenGL correctly?
I'm using OpenGL ES 2 and I want to render a simple model with some level of transparency. I'm just starting out with shaders, and I wrote a simple diffuse shader for the model without any issues but I don't know how to add transparency to it. I tried to set my fragment shader's output (gl\_FragColor) to a non opaque alpha value but the results weren't too great. It sort of works, but it looks like certain model triangles are only rendered based on the camera position... It's really hard to describe what's wrong so please watch this short video I recorded:

http://www.youtube.com/watch?v=s0JqA0rZabE

I thought this was a depth testing issue so I tried playing around with enabling/disabling depth testing and back face culling. Enabling back face culling changes the output slightly but the problem in the video is still there. Enabling/disabling depth testing doesn't seem to do anything.

Could anyone explain what I'm seeing and how I can add some simple transparency to my model with the shader? I'm not looking for advanced order independent transparency implementations.

edit:

```
Vertex Shader:
// color varying for fragment shader
varying mediump vec3 LightIntensity;
varying highp vec3 VertexInModelSpace;

void main()
{
    //
    vec4 LightPosition = vec4(0.0, 0.0, 0.0, 1.0);
    vec3 LightColor = vec3(1.0, 1.0, 1.0);
    vec3 DiffuseColor = vec3(1.0, 0.25, 0.0);

    // find the vector from the given vertex to the light source
    vec4 vertexInWorldSpace = gl_ModelViewMatrix * vec4(gl_Vertex);
    vec3 normalInWorldSpace = normalize(gl_NormalMatrix * gl_Normal);
    vec3 lightDirn = normalize(vec3(LightPosition-vertexInWorldSpace));

    // save vertexInWorldSpace
    VertexInModelSpace = vec3(gl_Vertex);

    // calculate light intensity
    LightIntensity = LightColor * DiffuseColor * max(dot(lightDirn,normalInWorldSpace),0.0);

    // calculate projected vertex position
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

}

Fragment Shader:
// varying to define color
varying vec3 LightIntensity;
varying vec3 VertexInModelSpace;

void main()
{
    gl_FragColor = vec4(LightIntensity,0.5);
}

```

# Answer
The problem is exactly what you say you aren't looking for. Drawing entirely transparent models is a non-trivial task, since to achieve correct blending closer polygons must be drawn after the further ones.

If you don't want to use more advanced techniques like depth peeling, try breaking your model in small pieces and draw them sorted from back to front, with depth writing disabled.
> 3 votes

# Answer
You draw your opaque scene (typically front to back, so the depth test fails increasingly often for the far away fragments which speeds it up).

You then *disable* writes to the depth buffer (`glDepthMask(GL_FALSE)`). The depth test remains enabled. Now draw your transparent polygons.

This ensures that the semi-transparent polygons are rendered in the right way.

(Direct3D users `SetRenderState(D3DRS_ZWRITEENABLE,FALSE)`)
> 2 votes

# Answer
Your problem may be backface culling. Google it.

EDIT: Now I see that you mentioned it, so nevermind.
> 0 votes

---
Tags: opengl, transparency
---


# Question
Title: Drawing texture does not work anymore with a small amount of triangles
When I draw lines, the vertices are well connected. But when I draw the texture inside the triangles, **it only works with `i<4` in the for loop**, otherwise with `i<5` for example, there is a EXC\_BAD\_ACCESS message, at `@synthesize textureImage = _textureImage`. I don't understand why. (The `generatePolygons` method seems to work fine as I tried to draw lines with many vertices as in the second image below. And textureImage remains the same for i\<4 or i\<5 : it's a 512px square image).

Here are the images :

What I want to achieve is to put the red points and connect them to the y-axis (the green points) and color the area (the green triangles) :

If I only draw lines, it works fine :

Then with a texture color, it works for i\<4 in the loop (the red points in my first image, plus the fifth one to connect the last y) :

But then, if I set `i<5`, the debug tool says EXC\_BAD\_ACCESS at the synthesize of `_textureImage`. Here is my code :

I set a texture color in HelloWordLayer.mm with :

```
CCSprite *textureImage = [self spriteWithColor:color3 textureSize:512];
_terrain.textureImage = textureImage;

```

Then in the class `Terrain`, i create the vertices and put the texture in the draw method :

```
@implementation Terrain

@synthesize textureImage = _textureImage; //EXC_BAD_ACCESS for i<5

- (void)generatePath2{
    CGSize winSize = [CCDirector sharedDirector].winSize;
    float x = 40;
    float y = 0;
    for(int i = 0; i < kMaxKeyPoints+1; ++i) {
        _hillKeyPoints[i] = CGPointMake(x, y);

        x = 150 + (random() % (int) 30);
        y += 30;
    }
}

-(void)generatePolygons{

    _nPolyVertices = 0;
    float x1 = 0;
    float y1 = 0;
    int keyPoints = 0;

    for (int i=0; i<4; i++){ /* HERE : 4 = OK / 5 = crash */
        //V0: at (0,0)
        _polyVertices[_nPolyVertices] = CGPointMake(x1, y1);
        _polyTexCoords[_nPolyVertices++] = CGPointMake(x1, y1);

        //V1: to the first "point"
        _polyVertices[_nPolyVertices] = CGPointMake(_hillKeyPoints[keyPoints].x, _hillKeyPoints[keyPoints].y);
        _polyTexCoords[_nPolyVertices++] = CGPointMake(_hillKeyPoints[keyPoints].x, _hillKeyPoints[keyPoints].y);

        keyPoints++; //from point at index 0 to 1
        //V2, same y as point n°2:
        _polyVertices[_nPolyVertices] = CGPointMake(0, _hillKeyPoints[keyPoints].y);
        _polyTexCoords[_nPolyVertices++] = CGPointMake(0, _hillKeyPoints[keyPoints].y);

        //V1 again
        _polyVertices[_nPolyVertices] = _polyVertices[_nPolyVertices-2];
        _polyTexCoords[_nPolyVertices++] = _polyVertices[_nPolyVertices-2];

        //V2 again
        _polyVertices[_nPolyVertices] = _polyVertices[_nPolyVertices-2];
        _polyTexCoords[_nPolyVertices++] = _polyVertices[_nPolyVertices-2];

        //V3 = same x,y as point at index 1

        _polyVertices[_nPolyVertices] = CGPointMake(_hillKeyPoints[keyPoints].x, _hillKeyPoints[keyPoints].y);
        _polyTexCoords[_nPolyVertices] = CGPointMake(_hillKeyPoints[keyPoints].x, _hillKeyPoints[keyPoints].y);

        y1 = _polyVertices[_nPolyVertices].y;
        _nPolyVertices++;
    }
}

- (id)init {
    if ((self = [super init])) {
        [self generatePath2];
        [self generatePolygons];
    }
    return self;
}

- (void) draw {

    //glDisable(GL_TEXTURE_2D);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);

    glBindTexture(GL_TEXTURE_2D, _textureImage.texture.name);

    glColor4f(1, 1, 1, 1);
    glVertexPointer(2, GL_FLOAT, 0, _polyVertices);
    glTexCoordPointer(2, GL_FLOAT, 0, _polyTexCoords);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)_nPolyVertices);

    glColor4f(1, 1, 1, 1);
    for(int i = 1; i < 40; ++i) {
        ccDrawLine(_polyVertices[i-1], _polyVertices[i]);
    }

    // restore default GL states
    glEnable(GL_TEXTURE_2D);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

}

```

Do you see anything wrong in this code?

# Answer
> 0 votes
Ok, i had to put more space in the array that keep all the vertices, it works now, thanks

---
Tags: textures, opengl-es, iphone, cocos2d-iphone
---


# Question
Title: Is it legal to use the name of an existing game?
I'm planning on creating an iPhone game titled "Guess Who!". I know there is already a board game with the same title (linked here) so I'm wondering it is legal for me to use this title for my game. Will the game get pulled off of the App Store if I use it? Thanks in advance.

# Answer
You'll best find this answer by querying Apple and places where Apple app developers post. Well, that and contact a legal professional. The question is really quite independent of whether it's a game, a productivity app, or anything else.

That said, the fact that your game and a different game (even if it's a board game) have the same name is likely to create an issue, simply because consumers may confuse your game with the board game. Does Apple care about this? I don't know. But does the maker of the original game care? That's the big question (IMO). If they don't like it, they've got a fairly legitimate argument (in my mind) that your game's name creates confusion about their game, and I assume they have already legally protected their name in some way.

Best advice? Just pick a new name. Or be ready to argue that, "Guess Who!" is sufficiently generic enough that many games could have that name.
> 3 votes

# Answer
From personal experience, no it is not legal. Never ever use the name of a company or product in your product name. Examples of bad names:

* World of Warcraft Awesome Sauce App
* MGM Studios Actor Locator

On the Apple market, your game most likely won't pass review because they have a descent legal department and they will force you to change your name unless you can prove you have rights to Guess Who.

If you were actually published then the entity that owns rights to Guess Who would have the option of filing a DMCA takedown request on your app. Your app would then be shutdown permanently pending a counterfiling by yourself.

See the pretty info-graphic here for the remainder of the process: http://blog.nexcess.net/2012/02/22/dmca-process-infographic-flowchart/
> 1 votes

# Answer
Simply put ; that depends on what rights and trademarks have been registered for that other game's name.

For example, not too long ago, Bethesda sued Mojang becuase they were about to launch a game called "scrolls", and Bethesda's lawyers sued Mojang becuase they worried about their trademarks on "The Elder Scrolls".

So even a name that sounds like a famous game name *might* get you into trouble.
> 1 votes

---
Tags: iphone, ios, legal
---


title: What exactly can shaders be used for?

text:
# Question
Title: What exactly can shaders be used for?
I'm not really a 3D person, and I've only used shaders a little in some Three.js examples, and so far I've got an impression that they are only being used for the graphical part of the equation.

Although, the (quite cryptic) Wikipedia article and some other sources lead me to believe that they can be used for more than just graphical effects, ie, to program the GPU (Wikipedia).

So, the GPU is still a processor, right? With a larger and a different instruction set for easier and faster vector manipulation, but still a processor. **Can I use shaders to make regular programs (provided I've got access to the video memory, which is probable)?**

**Edit:** regular programs == "Applications", ie create windows/console programs, or at least have some way of drawing things on the screen, maybe even taking user input.

# Answer
> 13 votes
Originally, dedicated graphics processing hardware had a fixed, hardwired set of functions. It would take input geometry, do very specific things to it to transform and rasterize it, and then blast the results to the screen. Over time, this functionality became parameterized and eventually programmable. "Shaders" became the term used for the programs that ran on the GPU, since they controlled the transformation and shading of geometry.

As GPU hardware evolved, more and more of it has become programmable, so now the bulk of the kinds of shaders one can write only contribute indirectly to the actual shading of anything on screen (I'm referring to things like geometry and hull shaders here). With that came the generalization of the GPU as a device for doing large-scale highly-concurrent stream-based processing, such that while the *intent* of a GPU and of shaders is generally to implement some kind of fancy graphical effect, they can also be used to perform certain kinds of general-purpose computations (particularly those that are suited to being computed in parallel). This is often referred to as general purpose GPU programming, or "GPGPU."

However, the GPU is still highly specialized and can't do a lot of the things a CPU could do. It has limited connectivity to the rest of the hardware in a system, as well, so you can't really write "regular" programs (with console output or mouse input, et cetera) entirely on the GPU. You can perform calculations on the GPU that aren't intended to be interpreted as renders, but it isn't a standalone CPU in its own right.

# Answer
> 5 votes
GPU can't tell CPU what to do. It can just provide results in its memory which will CPU read.

Shaders/GPGPU **can't be used for**:

* taking user **input** directly **without CPU**, because they are implemented as CPU interrupts
* **creation** of any **application**, because applications are managed by kernel and that is executed by CPU
* **creation** of any **window**, because window manager/server is executed in CPU

Shaders/GPGPU **can be used for**:

* **drawing stuff** on screen/window, but it has to be controlled by CPU
* video **decoding/encoding**
* **image processing** in professional graphic editors - various effects parallel executable effects like blur, sharpen edges, ...
* **physics calculations**

See **OpenCL**. It can utilize shaders for non-graphic calculations.

**Edit based on comments:**

Shaders are used just for rendering graphics. Performing non-graphics computations in GPU is called GPGPU.

# Answer
> -4 votes
Simple. The graphics processing unit eventually got shaders, which a fancy pant effects for shading. This became programmable so the effects got more and more fancy. Eventually the entire GPU became a SIMD unit.

SIMD means Single Instrution Muliple Data. Currently the GPUs are like a tree. It has X many cores, each having Y many cores, having Z many cores. The further you go down the tree, the faster and smaller the memory, the more parallel and simpeler the calculations.

So the GPU has become sort of a General Purpuse GPU. It's not called a CPU because it's not the central processing unit, even though it can handle I/O, memmory management and scheduling.

Needless to say that the power from the GPGPU comes from having to do some dividable, parallel operations on a lot of data at once. While it's therefore useless to most general software stuff, nVidia is working on making the GPGPU a CPU. They believe that they can expose the GPU as an ARM CPU. This translation technique is also inside x86 CPUs, which are RISC at their core.

OpenCL, CUDA and DirectX are like a split personality programming language. OpenCL for example runs on the CPU, but offloads 'bombs' ("kernels") that are benefiting from SIMD, to the GPU.

It won't be long before it's all Fusion/Sandy Bridge CPU-GPU style.

---
Tags: 3d, shaders
---


# Question
Title: Game planning and software design? I feel that UML is not convenient
In my university, they always emphasize and hype about UML design and stuff, in which I feel it is not going to work well with game structure design. Now, I just want a professional advice on how should I begin my game designing? The story is I have some skill in programming and have done many minor game such as getting some 2D platformer working to some extend. The problems that I find about my program is the poor quality design. After coding for a while, things start to break down due to poor planning (When I add new feature, it tends to make me have to recode the whole program). However, to plan everything out without a single design flaw is a bit too ideal. Therefore, any advice to how should I plan my game? How should I put it into visible pictures, so that me and my friends are able to overview the designs?

I planned to start coding a game with my friend. This is going to be my first teamwork, so any professional advices would be a pleasure. Is there any other alternatives than UML?

Another question is how does "prototyping" normally looks like?

# Answer
> 19 votes
> I just want a professional advice on how should I begin my game designing?

Game design is the specification of the gameplay, the assets, the scoring systems, etc - these are not software-specific. As such, UML is the wrong tool for that task.

When it comes to designing the code to implement these systems, UML is a good tool for the task, providing your team know it, and stick to the more common diagram types. Normally, when trying to design a feature, you will know whether you need to use a description or a diagram. If you do need to use a diagram, UML gives you a standard way of drawing it, which is a good thing.

> After coding for a while, things start to break down due to poor planning (When I add new feature, it tends to make me have to recode the whole program).

That is generally a problem with the way you program, rather than how you plan. Good software usually is easy to extend and reuse. If you stick to good programming practices, this problem will decrease. But better planning will help also, and you don't need complex diagrams for this. Just having a list of features will mean that when you code one thing, you have the other features in mind and can consider them as you code.

> Therefore, any advice to how should I plan my game? How should I put it into visible pictures, so that me and my friends are able to overview the designs?

It sounds like you're mixing 2 problems here, the game design, and the code design.

I suggest first writing out a basic game design, specifying the features you need, the graphics and sounds you need, how the game is won and lost, etc. Look up 'design documents' if you need some help there.

From there, you will have an idea of the features that you need to code up. You can look at each feature in turn and try to think about how to implement them. Diagrams can help to show the relationships between different classes and objects in your game but the skill of knowing which objects need to exist is something that you have to learn through practice and/or further reading.

Also, try working on smaller, less ambitious projects. That will get you used to writing good, working code, without needing extensive planning or rewrites.

# Answer
> 2 votes
Not understanding something makes it easy to dismiss. The UML is an engineering tool used to communicate the ideas you have in a structured way. A game is a system which can be engineered like any other. If anything, a game's complexity and dynamism makes a visual representation of it's parts and their interactions invaluable.

The UML diagrams are different views of a model of the system under discussion. I start with use cases for a person sitting down in front of my program and starting it. In the case of a game there are two kinds of users: designers and players. I write a use case for each of the things I can see them doing. Then I make some CRC cards to figure out what services I need to provide. Then I make a class diagram for the interfaces that will provide these services and their relationships. This is based on the CRC cards. Next come dynamic diagrams for events like initialization which require planning and orchestration. Then more detailed static diagrams showing the classes implementing the interfaces.

All the while I am writing code and prototyping and evolving it in the direction of providing the services to support fulfilling the requirements of my game. Nothing gets built that doesn't support the user through the use cases. I write some useless diagram elements, but between the interface coding and the diagramming I write very little useless code. Diagramming gives me confidence that I understand the way the class I am writing fits into the whole system.

The point I am trying to make is that a trivial program can be written without plans, but a game is anything but trivial. Some time ago, when OOP was new, there was a lot of experimentation and some best practices came to the fore. The software development community agreed that we needed a language to write about and analyze software designs. The UML is the language we developed. We all know and understand it, so if you want to use other people's solutions to your problems (books, online discussions, articles, pattern catalogs, etc.) and not reinvent the wheel you must learn to read the standard notation. As a bonus, when you force yourself to think about your system in another language, you learn unexpected things.

Many different methodologies exist, but they all identify the problem and describe one solution in a systematic way. This is engineering. The UML is huge and complex, but no one model uses every construct. It is like a Swiss army knife. You have to get to know it and figure out how to use it to support your engineering process. The important thing is not which process or methodology but that you have one. Otherwise you will drown in complexity.

# Answer
> 2 votes
I'm also working on some independent game projects with a friend (2-person team). As someone in a similar situation to yours, I can offer a few tidbits that I've found helpful.

1. If your ideas are rough, try implementing them one at a time in super tiny prototyping projects. For example, I am making a 2D platform game now, and getting the player's jump right is extremely important to me. So, I made a new project where the only 2 things that happen are a) Drawing the player on the screen, and b) Detecting input, and redrawing the jump \[character cannot even move left or right\]
2. Some people might frown on this piece of advice, but think about writing the game manual first (to explain the concepts, controls, objectives). This can do 2 things for you -- generate a much needed document, but also outline the subsystems of your game and any necessary details for the player. If you know in advance what the player needs to know, then you know in advance what you need to do.
3. Write code in small enough (aka *modularized*) chunks that the factored pieces can be either moved around, or better organized without feeling like you're trying to remove all of the mid-sized pieces of spaghetti from a plate of pasta.

Hopefully you found at least one useful piece of information in there, and good luck!

# Answer
> 1 votes
UML is not one thing it is a collection of things some of them have value others not so much. the older style Use Cases (at least what we call use cases) that state

* name
* requirements
* preconditions
* triggers
* actions
* alternate actions
* exceptions

can be quite useful. though what you find for "Use Cases" if you do a web search (the pictures) are more for general software.

I would also put some credit to the Class diagram. this shows that you are able to show the relationship between all of your objects, and that you know the layout of your architecture.

what it comes down to is that your feature set should be all planned out, and locked int (at-leased in a need/want setup) before modeling, and diagramming is even started. these should be all in your Brief/Treatment/Script (sometimes referred to as pitch, features document, and story). then from there you would do up your tech doc stuff that has your models, and diagrams.

there are companies that use UML, but these are usually companies that have separate design and implementation teams. the companies that will create all of their documentation, and then give it to a team of code-monkeys to create an prototype/alpha. its said that if you can model your game accurately you should be able to give it to a completely different team and have them program it though this is more a pipe dream then an accuracy.

# Answer
> 1 votes
I think there are some valuable takeaways from UML that you can't deny. on the other hand, keep in mind that UML was built for *business processes*, you know, modelling systems that have *a lot of people* interacting with it, all with different wants and needs and desires. UML tries to make sure you don't leave anything out or get overwhelmed by detail.

UML is "a standard way to visualize a system's architecture"

UML describes

* activities
* actors
* business processes
* database schemas
* (logical) components
* programming language statements
* reusable software components

But if you're making a simple game, do you really need to model all this?

* **Actors: The player.**

How much does that help?

Modelling some of the other things though, is very helpful. For example if you're making a small MMO, you definitely want well designed data base schemas.

So while the take aways from UML are excellent (know what you're doing, write down the requirements, and sketch diagrams of flowcharts wherever it is needed), and elements of it are very useful, I tend to feel the full UML process is a bit of a square peg round hole for games.

# Answer
> 0 votes
They will be teaching you about UML at your university to help you communicate your ideas to the rest of your team, and show lecturers you have a good working knowledge of basic software engineering principles.

Like any discussion over language, tools or design - it usually comes down to how YOU use it. Pick the best tool/language/design for the job and back up your choice with a strong rationale. I'll admit UML is not so flexible for game production, although I can say that we have used it effectively to model engine features such as network communications and timing, parallel task management and use cases. There is nothing worse than explaining the same thing to 5 different team members 10 different times because they don't quite get it. Here's the documentation, read it.

Depending on how solid you designs are, and how disciplined your team is, it can be quite productive to be able to model your own constructs around those that haven't even been started yet, and yet know exactly how they will operate due to the documentation.

In spite of this, you will probably hear (and realise harshly) that these are LIVING DOCUMENTS, and unless they are reviewed and updated regularly, they will be become obsolete fast and effectively useless.

---
Tags: game-design
---


# Question
Title: Multiplayer tile based movement synchronization
I have to synchronize the movement of multiple players over the Internet, and I'm trying to figure out the safest way to do that.

The game is tile based, you can only move in 4 directions, and every move moves the sprite 32px (over time of course). Now, if I would simply send this move action to the server, which would broadcast it to all players, while the walk key is kept being pressed down, to keep walking, I have to take this next command, send it to the server, and to all clients, in time, or the movement won't be smooth anymore. I saw this in other games, and it can get ugly pretty quick, even without lag. So I'm wondering if this is even a viable option. This seems like a very good method for single player though, since it's easy, straight forward (, just take the next movement action in time and add it to a list), and you can easily add mouse movement (clicking on some tile), to add a path to a queue, that's walked along.

The other thing that came to my mind was sending the information that someone started moving in some direction, and again once he stopped or changed the direction, together with the position, so that the sprite will appear at the correct position, or rather so that the position can be fixed if it's wrong. This should (hopefully) only make problems if someone really is lagging, in which case it's to be expected. For this to work out I'd need some kind of queue though, where incoming direction changes and stuff are saved, so the sprite knows where to go, after the current movement to the next tile is finished. This could actually work, but kinda sounds overcomplicated. Although it might be the only way to do this, without risk of stuttering. If a stop or direction change is received on the client side it's saved in a queue and the char keeps moving to the specified coordinates, before stopping or changing direction. If the new command comes in too late there'll be stuttering as well of course...

I'm having a hard time deciding for a method, and I couldn't really find any examples for this yet. My main problem is keeping the tile movement smooth, which is why other topics regarding synchronization of pixel based movement aren't helping too much.

What is the "standard" way to do this?

# Answer
> 4 votes
I'm assuming you're talking about moving in real time. Trying to interpolate position is probably a lost cause; over a slow connection, your game state could fall further and further behind the actual game state. Unlike the other comment, I would advise against putting much game logic in the server side. When I've implemented these sort of solutions, the client has a TCP socket to the server constantly. When the game state changes, it sends a message to the server, like 'client is at x=10, y=20'. The server pushes the message to the other clients, who try to handle it based on their own internal logic. Using TCP ensures your messages arrive in order.

Unfortunately, even AAA games can't handle extreme lag; players will occasionally move very quickly, because their local and network states are far out of whack. Monitoring the round-trip ping and kicking users who are too far/slow will help with this.

# Answer
> 3 votes
Basically this is how you can do it in a simple and secure way (warning, extreme pseudocode):

A) Client (playerid=5) asks server to move 'right' (or better, to tile 73,18)

B) Server checks his big 2D map that contains players (or players ID for example):

```
 if(map[73][18] == occupied)
     Send back ('Not OK') to client (the case is blocked by another player)
else
    Set the new position as blocked: map[73][18]=5
    Release the old position: map[72][18]=0;
    Send a 'new position: 5, 73,18' message to all players who are nearby (moving client included)

```

C) Clients get an 'new position' message (well, or player 5 gets the 'Not Ok' message)

D) clients slowly moves the item which has playerid=5 towards its new position (or creates it if it doesn't have one item with playerid=5)

# Answer
> 1 votes
I think the method you described is pretty good, especially in a simplistic game where only 4 moves are allowed. Here is how I implemented it.

I don't know of any standards, but the first thing that came to mind was to only broadcast "input changes", changes in a player's input, from a player to the others. For example, you could broadcast only messages along the lines of \[key pressed, key ID, time\], or \[key released, key ID, time\], and let the players' game act upon these input changes. Including time will help with path correction (if the player has changed direction at time t, then the "going forward" at time t+1 will need to be fixed).

However, with this solution you may encounter the issue of lost messages; suppose the "key released" message was never sent? Something which can help this is periodically polling the game state of a player and return the current position of the player, as well as any key being pressed, or even return the entire game state. Depending on the number of players and commands, you can tweak this in order to balance message passing between clients/server for a good balance.

Another thing you can look into is path planning. For example, if the player has been moving forward for 5s, then in the next millisecond chances are the player will still move forward. In that case, you can create a semblance of path prediction in order to avoid lag. This is essentially what the method above is doing, although this can take into account circular paths.

I hope this helped!

---
Tags: networking, tiles, multiplayer, online, synchronization
---


# Question
Title: JOGL hardware based shadow mapping - computing the texture matrix
I am implementing hardware shadow mapping as described here.

I've rendered the scene successfully from the light POV, and loaded the depth buffer of the scene into a texture. This texture has correctly been loaded - I check this by rendering a small thumbnail, as you can see in the screenshot below, upper left corner. The depth of the scene appears to be correct - objects further away are darker, and that are closer to the light are lighter.

However, I run into trouble while rendering the scene from the camera's point of view using the depth texture - the texture on the polygons in the scene is rendered in a weird, nondeterministic fashion, as shown in the screenshot. I believe I am making an error while computing the texture transformation matrix, but I am unsure where exactly.

Since I have no matrix utilities in JOGL other then the `gl[Load|Mult]Matrix` procedures, I multiply the matrices using them, like this:

```
void calcTextureMatrix() {
  glPushMatrix();

  glLoadIdentity();
  glLoadMatrixf(biasmatrix, 0);
  glMultMatrixf(lightprojmatrix, 0);
  glMultMatrixf(lightviewmatrix, 0);
  glGetFloatv(GL_MODELVIEW_MATRIX, shadowtexmatrix, 0);

  glPopMatrix();
}

```

I obtained these matrices by using the `glOrtho` and `gluLookAt` procedures:

```
  glLoadIdentity()
  val wdt = width / 45
  val hgt = height / 45
  glOrtho(wdt, -wdt, -hgt, hgt, -45.0, 45.0)
  glGetFloatv(GL_MODELVIEW_MATRIX, lightprojmatrix, 0)

  glLoadIdentity()
  glu.gluLookAt(
    xlook + lightpos._1, ylook + lightpos._2, lightpos._3,
    xlook, ylook, 0.0f,
    0.f, 0.f, 1.0f)
  glGetFloatv(GL_MODELVIEW_MATRIX, lightviewmatrix, 0)

```

My bias matrix is:

```
float[] biasmatrix = new float[16] {
  0.5f, 0.f, 0.f, 0.f,
  0.f, 0.5f, 0.f, 0.f,
  0.f, 0.f, 0.5f, 0.f,
  0.5f, 0.5f, 0.5f, 1.f
}

```

After applying the camera projection and view matrices, I do:

```
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR)
glTexGenfv(GL_S, GL_EYE_PLANE, shadowtexmatrix, 0)
glEnable(GL_TEXTURE_GEN_S)

```

for each component.

Does anybody know why the texture is not being rendered correctly?

Thank you.

# Answer
> 0 votes
Multiplying the matrices that way does not work.

Instead, using the Java JAMA package for matrices:

```
  import Jama._

  Matrix bi = new Matrix(4, 4);
  Matrix lp = new Matrix(4, 4);
  Matrix lv = new Matrix(4, 4);
  Matrix cv = new Matrix(4, 4);

  // store the float arrays to matrices

  Matrix st = bi.times(lp).times(lv)

  // read matrix into float array and transpose.

```

Interestingly, the shadow texture matrix also had to be transposed.

Still, the resulting image is shown below - it has artifacts. Question is - how to get rid of them?

EDIT:

Apparently, the problem is erroneous self-shadowing.

I realized this while reading the suggested link - thanks for the pointer!

However, the links suggests adjusting the near and far planes - this is not the solution. The solution is to adjust the scaling factor of the depth matrix. To avoid peter-panning, the scale in the z-axis should be as big as possible, but less than `1.f`:

```
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glScalef(1.f, 1.f, 0.9999f)

```

The result:

I figured it out while going through this example.

---
Tags: opengl, java, shadows, jogl, shadow-mapping
---


# Question
Title: Which data structure should I use for  dynamically generated platforms?
I'm creating a platform type of game with various types of platforms. Platforms that move, shake, rotate, etc. Multiple types and multiple of each type can be on the screen at once. The platforms will be procedural generated.

I'm trying to figure out which of the following would be a better platform system:

1. Pre-allocate all platforms when the scene loads, storing each platform type into different platform type arrays( i.e. `regPlatformArray` ), and just getting one when I need one.
2. The other option is to allocate and load what I need when my code needs it.

The problem with 1 is keeping up with the indices that are in use on screen and which aren't.

The problem with 2 is I'm having a hard time wrapping my head around how I would store these platforms so that I can call the update/draw methods on them and managing that data structure that holds them. The data structure would constantly be growing and shrinking. It seems there could be too much complexity.

I'm using the cocos2d iPhone game engine.

Anyways, which option would be best or is there a better option?

# Answer
There's a few data structures that meet your requirements: growth, adding, removing, iterable.

1. Linked lists (doubly linked). Easy to implement, easy to iterate to perform operations on each node. Not as fast for selecting a specific element, since you have to step through.
2. Dynamic array. Easy to implement, easy to iterate to perform operations on each node, fast for indexing. Not so good for adding and removing items in the beginning or end.
3. Binary search tree (balanced) Fairly easy to step through. Average for "indexing", adding and removing.

Which one to choose depends on your game. For example, if it were side scroller and you're always just adding platforms on the end and removing them from the beginning (as you scroll), the linked list would work great for that. If you always have a small number of platforms in memory \< 100. Any of these structures will work just fine. You can always just pick on, and if it doesn't work out it should be simple to swap out for a more efficient structure.

If you're having trouble wrapping your head around these structures, I suggest you check out some free online courses for computer science. The introduction courses will introduce basic data structures. The MIT Opencourseware site is a good resource for this.
> 1 votes

---
Tags: ios, cocos2d, data-structure
---


title: Split Texture2D Across Line

text:
# Question
Title: Split Texture2D Across Line
## Background

I'm using a texture as a damage map represented by an array of floats for displaying damage effects on a space ship in a process.

An upside of this is being able to 'slice' ships in half, using an input damage map with a line down the middle, as shown in the diagram below.

## Question

However, I'm encountering problems separating this split ship into two different entities. I would like to be able to split the image down the 'damage line', in a process similar to this:

I don't have much idea where to start detecting the red line above. Any advice would be welcome.

# Answer
> 2 votes
Very interesting concept. The only thing I can think of is using Texture2D.GetData() to see the pixel data of your damage mask, iterate to find a sufficiently dark pixel, then use some basic maze-solving to follow it in a path through adjacent dark pixels. A stack-based algorithm (probably the simplest maze-solving ones) may work for this, but you're going to have to find something that's efficient enough for your desires. Basically, find the longest string of dark pixels you can.

Storing the start and end as a Vector2, you could calculate a line between them and use the angle and the distance to see if it bisects the rectangle area you define as your ship (not necessarily the whole texture, you'd need to manually define it I guess). To find out if it fully bisects the rectangle... I'll try to whip something up here, no guarantees:

```
float hypotenuse = damageLine.Length(); //this allows us to calculate trig stuff
float boxHeight = shipBoundingBox.Height;

//assuming the height of the box is its smallest dimension (i.e. long ships only, no fat
//ones). it's possible to adapt this if your ship types vary; just use the smallest
//dimension.
if (hypotenuse < boxHeight)
    return; //if the length is not long enough it could not possibly bisect it

float opposite = damageLine.X; //the x distance between start and end

float angle = (float)Math.Abs(Math.Asin(opposite/hypotenuse)); //this is the angle of the
                                                               //line from y-axis

//now we can use trig to calculate the largest angle, based on the hypotenuse and the
//vertical height of the bounding box, which would bisect the bounding box.
float largestAngle = (float)Math.Abs(Math.Acos(boxHeight / hypotenuse));

if (angle < largestAngle)
    doBisect(); //damage has bisected the rectangle
else
    return; //damage has not bisected the rectangle

```

Note that this would only check to see if you cut the ship in half width-wise (the way you've shown it in your example picture). You could easily use the dot product of the slice vector with Vector2.Right to see if the vector is actually length-wise on your ship, and switch a few values above for the calculations. Or, maybe there's a general formula you could adapt from that.

As for building new masks... perhaps extend the line you found so that the two points are at the edges of the texture, then use a RenderTarget2D to draw this new line on top of the existing damage texture. Using the equation of the line you could then fill in pixels above or below it for two successive draw calls, saving the RenderTarget2D as a different texture for both, then pass those on.

I'm sorry this is mostly ideas and less hard code, but I've never really thought about something like this before, and everything here would take some testing and tweaking to make it work. Hope it gives you something to go off of, though. The methods here would also only make straight cuts and not more complex ones, but I think that may be sufficient. If you use the damage texture with RenderTargets like I mentioned, it should retain the jagged edge.

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


# Question
Title: Design patterns for effects between actors and technology
I'm working on my first game, and taking the opportunity to brush up my C++ (I want to make as much of it as portable as I can.)

Whilst working on the technology tree and how it affects actors (spaceships, planets, crew, buildings, etc) I can't find a pattern that decouples these entities enough to feel like a clean approach.

Just as an idea, here's the type of effects these actors can have on one another (and techs too)

* An engineer inside a spaceship boosts its shield
* A hero in a spaceship in a fleet increases morale
* A technology improves spaceships' travel distance
* A building in a planet improves its production

The best I can come up with is the Observer pattern, and basically manage it more or less manually (when a crew member enters a spaceship, fire the event; when a new building is built in a planet, fire the event, etc etc.) but it seems to be too tightly coupled to me.

I would love to get some ideas about how to approach this better.

# Answer
I would say that you could probably approach this the same way that RPGs and MMOs handle 'buffs' and 'debuffs', as these are modifiers applied to a base value that can be added or removed based on some condition.

As such, the answers here may help: What's a way to implement a flexible buff/debuff system?

I would warn against an event-driven system for this situation as they are prone to 'drift' when trying to apply and remove complex modifiers. (eg. If you apply a x2 modifier, then a +10 modifier, remove the x2 modifier, then remove the +10 modifier, it's easy to accidentally end up 5 points below where you started.) For this reason, I don't think an Observer pattern is ideal.

Instead, I would poll the values when needed. When checking shields, count the engineers inside. When checking morale, look for heroes in the spaceships in the fleet. If this turns out to perform poorly, you can cache the values or precalculate these queries.
> 2 votes

---
Tags: c++, design-patterns, data-structure, effect-modifier
---


# Question
Title: Free vs. Paid: Picking a Financial Model
I finally embarked upon my first "paid" game. What this means is that I will incorporate some sort of monetization strategy in my game. This may mean making the app pay-to-download, making it "freemium" with paid content, or something else.

Having never done something like this, I'm at a complete loss as to how to figure out what I should do. I know a couple of models (pay to download, freemium, etc.) and I can brainstorm some ideas. But how do I figure out what strategy to use?

Perhaps there's some body of research on this? (I recall reading that MMOs popular in Korea use a model where cosmetic changes only are pay-to-buy; everything else is free).

# Answer
I don't see how that's different from asking "How do I figure out what kind of game to make?" It's totally up to what you want to do. It can't really be answered by someone else.

So it's like any other difficult choice, list out your choices and write down what you think are the pros (with a positive score) and cons (with a negative score). Sum the total scores for each item, then go with the item with the highest score. However, I imagine you'll figure out which one you want before you even get to that point.
> 2 votes

---
Tags: monetization
---


# Question
Title: I need advice on creating animal 3D walk cycles in XNA
I want to purchase a number of 3D models from TurboSquid and animate them in an XNA game.

I wrote a lot of games from 1985-1999 and have recently become involved with XNA. Now I would like to port one of my old games to the XBOX. I do have a background in 3D animation; but that was years ago.

What is the current method for animating a walk cycle with a 3D model and using it inside XNA?

Is there a book, software or a tutorial that you can recommend?

Thanks in advance and sorry for such a broad and currently naive question.

# Answer
This site:

https://sites.google.com/a/cgspeed.com/cgspeed/motion-capture/3dsmax-friendly-release-of-cmu-motion-database

Has TONS of free motion capture data that you can apply to a biped in 3DSMax or import into other tools. It's pretty useful for getting realistic walk, run, jump, etc.

My approach was (in 3DSMAX, but you could use just about anything)

1. Create a biped (basically, a skeleton with joint hierarchies in place - it's a predefined system type in 3DSMAX)
2. Import and assign the motion capture data
3. Export the result to FBX, and go crazy with it in XNA.

If you're looking for sprites ala Prince of Persia, you can just render them in MAX.
> 2 votes

# Answer
Microsoft has created animation skinning samples that, with all code included that you can look at. The sample works on PC, Xbox, and Windows Phone 7.

http://create.msdn.com/en-US/education/catalog/sample/skinned\_model
> 0 votes

---
Tags: xna, 3d
---


title: Simulating the effects of  wind

text:
# Question
Title: Simulating the effects of  wind
I am developing a mobile game for Android. It is a 3D jumping game (like ski jump) where wind plays a important role so i need to simulate it. How could I achieve this?

The game uses libgdx for rendering and a port of Bullet physics engine for physics. To simulate the jump I have 2 spheres which are placed at the start and at the end of the player and gravity is applied to them (they role down the hill and jump at the end). I use them to calculate the angle and the position of the player. If a button is pressed some extra y speed is applied to them (to simulate the jump before the end of the jumping ramp).

But now I have to add wind to it. How is this usually done? Which collision box/method should I use? The way I understand it I only have to apply some force with direction to the player while in mid air. How can I do this in Bullet?

# Answer
> 4 votes
> How is this usually done?

There is no usual way of simulating wind. It depends on your situation. First you have to decide how the wind interacts with the player, how is it seen by the player etc, and then you think of a way of implementing it.

For example, say we want the wind to randomly appear as dust/snow/leaves particles and it simply pushes the player a bit in that direction. That's easy to implement; This wind object will pop up some place, with its own visuals, and when the player enters its volume a force acts upon the player.

For something more complicated, like a glider simulator that needs to know how the wind flows around mountains, hills and valleys, you would need a much more complex simulator.. but even in this situation we are far from a fluid simulation!

# Answer
> -1 votes
If all you need is an adjustment to an object in flight, a quick and dirty solution would be to just add some gravity on the X axis to pull your man to the left or right.

---
Tags: 3d, physics, bullet-physics
---


title: How to convert Blender models for XNA

text:
# Question
Title: How to convert Blender models for XNA
I am creating my first game, I'm using Blender to create character models, is there any tutorial or guide to tell me what steps to convert a model into something animated and usable in XNA?

# Answer
> 4 votes
Well Blender 2.5 (maybe 2.5x) can export fbx models which are used in XNA. It even has an "XNA strict options" check. I noticed that it tends to export the models a bit small so you may want to set the scale to 100 or so but otherwise it is good to go.

---
Tags: xna, models, blender
---


title: Crash when trying to detect touch

text:
# Question
Title: Crash when trying to detect touch
I've got a character in a 2D game using `surfaceView` that I want to be able to move using a button (eventually a joystick), but my game crashes as soon as I try to move my sprite. This is my `onTouch-method` for my steering button:

```
public void handleActionDown(int eventX, int eventY) {
    if (eventX >= (x - bitmap.getWidth() / 2) && (eventX <= (x + bitmap.getWidth()/2))) {
        if (eventY >= (y - bitmap.getHeight() / 2) && (y <= (y + bitmap.getHeight() / 2))) {
            setTouched(true);
        } else {
            setTouched(false);
        }
    } else {
        setTouched(false);
    }

```

And if I try to put this in my update-method:

```
public void update() {
    x += (speed.getXv() * speed.getxDirection());
    y += (speed.getYv() * speed.getyDirection());
}

```

The sprite moves on its own just fine, but as soon as I add:

```
public void update() {
    if(steering.isTouched()){
        x += (speed.getXv() * speed.getxDirection());
        y += (speed.getYv() * speed.getyDirection());
    }

```

the game crashes.

Does anyone know why this is or how to fix it? I cannot figure it out. I'm using `MotionEvent.ACTION_DOWN` to check if the user if pressing the screen.

# Answer
I imagine that since the only thing you're changing is `if(steering.isTouched()){` then you're likely not instantiating your `steering` variable. I imagine your error is something to do with a null value?
> 1 votes

# Answer
I'm going to risk an answer based on my past experience with the platform.

Touch events come from the UI thread, and your GLSurfaceView is running its own renderer thread. This means that your touch handling code and rendering are clashing together, causing the app to crash immediately when both threads make concurrent access to a shared variable, in this case, the bitmap/sprite or what you're using.

To solve this, either use a mutex or lock or something like that to synchronize both threads, or cache the touch events, and handle them in the renderer thread instead. This last one is how I did it, without problems at all so far.

Hope it helps.
> 1 votes

---
Tags: 2d, android, sprites, movement, character
---


# Question
Title: How can I achieve UnrealEd's per-face texturing in Blender 2.6?
Using UnrealEd I can create geometry and assign a material to each face of that geometry. Each face can have its own UV settings. How can I achieve the same functionality using Blender?

I've seen the "Texture Face" option mentioned but that seems to be gone in Blender 2.59+?

# Answer
You should be able to select the face(s) in editmode and then in the Properties window under Materials, click Assign to apply the mat you choose from the list. See http://www.katsbits.com/tutorials/blender/learning-multiple-materials-textures-images.php
> 2 votes

---
Tags: textures, blender, udk
---


# Question
Title: OpenGL ES 2 shaders for drawing buildings and roads like Google Maps does
I'm trying to create a shader that'll give me an effect similar to what buildings and roads look like on 3D Google Maps. You can see the effect interactively if you enable WebGL at maps.google.com, and I also found a couple of screenshots that illustrate what I'm trying to achieve:

Thing I noticed:

* There's some kind of transparency thing going on with the roads/ground and the buildings, but not between the buildings themselves. It might be that they're rendering the ground and roads after the buildings with the right blend functions to achieve that effect.
* If you look closely, you'll see parts of the building profiles have an outline. The roads also have nice clean outlines. There are a lot of techniques for outlining things with shaders... but I'm curious to find out what might have been used in this case considering mobile hardware and a large number of entities with outlines (roads and buildings)
* I'm assuming that for the lighting, some sort of simple diffuse per-vertex shader is being used for the buildings though I could be wrong.

I'm especially curious about the 'look' they achieved with buildings (clean, precise outlines/shading). It reminds me a little of what you'd see when designing stuff with CAD applications like SolidWorks:

I'd appreciate any advice on achieving this kind of look with ES 2 shaders.

# Answer
Alright, I played around with it.

First, it seems the WebGL stuff is pretty US-centric (aren't all the cool toys?), so it doesn't work for my hometown. Here's an area that works: the White House in Washington D.C.

If you look at that with the WebGL rendering, you can see pretty clearly that the light is always coming from the north-east. All surfaces pointing towards that are lit white, the rest are lit gray. It seems to me that the rendering is done in three stages:

* The map is rendered using vector graphics. This is very visible in for instance the round road around the White House lawn, you can clearly see the circle being approximated.
* Next, the buildings are rendered using flat surfaces. What I mean by that: each surface only has one normal, which it uses to calculate the lighting. The light comes from the north-east, but it could also be fake. Note that only three colors are used: white, gray and dark gray. This could easily have been baked into the model.
* The outline of the building is rendered using lines. This is more visible here. Note the right side of the Anfiteatro Flavio, you can clearly see the outline of the triangles making up the model.

So, how would you display something similar?

* Render the map as you would normally.
* Either render the buildings to an FBO or turn off depth writing while rendering them.
* Render the outline off the buildings, optionally to the building FBO.
* Combine the FBO with the backbuffer by rendering it to a full-screen quad or turn depth writing back on.
> 2 votes

---
Tags: shaders, opengl-es2
---