# Question
Title: Did Badland introduce the concept of "swarm", or is it already present in earlier games?
I've noticed the concept of swarm (there called "clones") in **Badland**, and I've never seen anything like it. Here's a video showing it.

I'll describe it:

* you start with one guy, and going on through the level you may "pick up" new guys, which are exactly like the one you already have (**there's no "main" one**, they are indistinguishable)
* **you can't control them individually**: your actions are applied to them all
* **you may lose a few of them along the way**, and you "die" if you lose them all

This is very different from **Lemmings**, were you control the single guys.

At most it could be considered somewhat similar to **Cannon Fodder** (or **Syndacate** or some **RTS**), but even there you had the ability to control a single guy: crowd movements were only a convenience were "it did not matter" to control specific individuals. Here you are forced to control them all together and this is a core feature of the game.

Someone could argue that **Pele's Soccer** had a similar movement system, but it doesn't have the concept that you could lose some guys and go on (and maybe pick new ones), and anyway it's not a core feature of the game, it's just a simplification due to the capabilities of the console.

**Patapon** could be considered to have a similar mechanic, but AFAIK being it a rhythm game you don't really get to chose what to do, unless I'm mistaken (I never got to play it).

Games were you have random sidekicks don't really count, since they are very different from you: usually when *you* get hit you die (like in shooters), or they are just a "second chance" but they almost aren't part of the game as long as they are in the background (like in **Donkey Kong Country**).

So, is this a novel idea, or did I miss something?

# Answer
> 2 votes
It's certainly not a new idea in itself. Technically, side scrolling shooters as far back as Galaga, or Breakout-style games where you gain extra paddles, already had clones that you could gain or lose and fit your definition of clones. In Pikmin, or Overlord, picking up a crowd was an essential part of gameplay, although granted, they were not exactly clones, but a crowd nonetheless that are influenced by the movement of the main character.

# Answer
> 1 votes
It definitely did not. In my youth, I had a CD with a bunch of Mac game demos on it (came from an old MacAddict magazine issue, if I remember correctly). One of those demos was for Crystal Caliburn, a pinball game that supported a multi-ball mode that behaves exactly like Badland's swarm: each ball is interchangeable and has no more relevance than any other, and the players control mechanism and authority over the swarm is not changed.

I'm pretty sure the multi-ball mechanic is older than that game, of course, it was probably present on real pinball tables. I doubt it's possible to trace the origin of this mechanic, but I'm positive it's been around for longer than Badland.

---
Tags: game-design
---


title: FPS limit function

text:
# Question
Title: FPS limit function
I try to cap the animation at 30 fps. So I design the functions below to achieve the goal. Unfortunately, the animation doesn't behave as fast as no condition checking for setFPSLimit() function when I set 60 fps (DirectX caps game application at 60 fps by default). How should I fix it to make it work?

getGameTime() function counts the time like stopwatch in millisecond when game application starts.

```
// Called once at the start of the game
void initGameTime()
{
    // We need to know how often the clock is updated
    if( !QueryPerformanceFrequency((LARGE_INTEGER *)&ticksPerSecond) )
        ticksPerSecond = 1000;

    // If timeAtGameStart is 0 then we get the time since
    // the start of the computer when we call GetGameTime()
    timeAtGameStart = 0;
    timeAtGameStart = getGameTime();
}

//Called every time you need the current game time
float getGameTime()
{
    UINT64 ticks;
    float time;

    // This is the number of clock ticks since start
    if( !QueryPerformanceCounter((LARGE_INTEGER *)&ticks) )
        ticks = (UINT64)timeGetTime();

    // Divide by frequency to get the time in seconds
    time = (float)(__int64)ticks/(float)(__int64)ticksPerSecond;

    // Subtract the time at game start to get
    // the time since the game started
    time -= timeAtGameStart;

    return time;
}

```

With fps limit http://www.youtube.com/watch?v=i3VDOMqI6ic

```
void update()
{
    if ( setFPSLimit(60) )
        updateAnimation();
}

```

With No fps limit http://www.youtube.com/watch?v=Rg\_iKk78ews

```
   void update()
    {
        updateAnimation();
    }

bool setFPSLimit(float fpsLimit)
{
    // Convert fps to time
    static float timeDelay = 1 / fpsLimit;

    // Measure time elapsed
    static float timeElapsed    = 0;

    float currentTime = getGameTime();
    static float totalTimeDelay = timeDelay + getGameTime();

    if( currentTime > totalTimeDelay)
    {
        totalTimeDelay = timeDelay + getGameTime();
        return true;
    }
    else
        return false;
    }

```

# Answer
Sorry, I would apply this as a comment if I had that privilege. Depending on what precisely timeGetTime() returns, you may run into some serious, and easily addressable floating point rounding errors.

Right now, your getGameTime function converts these int64's to floats, then divides, then subtracts. The issue is you're losing precision in the lower digits where it really matters when you do this. Try storing the int64 value you get at launch, rather than converting it and storing the float. Then invert the order of your operations there. The final product should look something like this:

```
float getGameTime()
{
    UINT64 ticks;
    float time;

    // This is the number of clock ticks since start
    if( !QueryPerformanceCounter((LARGE_INTEGER *)&ticks) )
        ticks = (UINT64)timeGetTime();

    // Subtract the ticks at game start to get
    // the ticks since the game started
    ticks -= ticksAtGameStart;

    // Now ticks is going to be a much smaller number
    // Divide by frequency to get the time in seconds
    time = (float)(__int64)ticks/(float)(__int64)ticksPerSecond;

    return time;
}

```

Again, with high enough framerate this could be causing more serious problems. Even without that, you're likely losing some time, and the sum of your Delta-T's won't actually be equal to the time since execution.
> 1 votes

# Answer
`getGameTime()` returns the time since the game started running, not the time since the last update. I assume `timeAtGameStart` is some global constant created while the game is launched, what you want to use instead is a `timeAtLastUpdate` value. This may not be perfect, but it should look more like:

```
void update()
{
    if ( setFPSLimit(60) )
    {
        timeAtLastUpdate = getGameTime();
        updateAnimation();
    }
}

bool setFPSLimit(float fpsLimit)
{
    // Convert fps to time
    static float timeDelay = 1000 / fpsLimit;  // assumes getGameTime returns milliseconds - you don't want to check 1/60 when it should be 1/60 * 1000

    if( getGameTime() - timeAtLastUpdate > timeDelay)
        return true;
    else
        return false;
}

```
> 0 votes

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


# Question
Title: Javascript game to Phonegap for android game?
me and a friend of mine are in the process of building a javascrip/HTML5 game and I'm running into a few questions about the process of using converting it to an android game. I plan on using Phone gap as it appears to be fairly simple and does what I'm looking for it to do. I've done a little research, but there is still a few questions I have about the whole process.

1. Can I run the app offline? I want to be able to post the app to app store and allow people to download and play offline. Given the fact there will be no server requests can I make the game function offline?
2. As I make the game for the computer I'm relying on the keyboard as input to move around. Obviously, once I port it to mobile this won't be practical. What is the easiest way to go about doing this? I'm considering simply changing the game to have a click on screen which moves the character to that location or even a simple movement pad in the corner of the screen. Would these on screen clicks change correctly over to mobile.
3. Lastly, what is the easiest way to handle save data. On the computer side I plan to use HTML5 local storage to store game data. Does this convert to mobile or is there a better way?

I appreciate any help in this matter.

# Answer
Phonegap is known to be slow, and isn't ideal for games. I've published several games on Google Play using CocoonJS and highly recommend it. For both platforms, the answers are:

1. Yes, you can run the app offline. Your HTML files (and images, JavaScript, etc.) are bundled with your application.
2. If you're targeting mobile, you should move to click/touch events. (You'll need to either handle both or use a lib/engine that does that for you.)
3. localStorage should just work (it does in CocoonJS).

Good luck!
> 2 votes

---
Tags: javascript, html5, mobile
---


title: Android Game Idea loop

text:
# Question
Title: Android Game Idea loop
So I'm a beginner in developing android gaame. I already developed a game, it's intended for kids. Basically, the game has 4 stages. In each stage, it has 15 questions. If the user chooses the correct answer, he will proceed to the next question, otherwise, will be given 3 trials to choose the correct answer/object.

Below is the structure of my game:

```
Home
Menu
    >>> Stage 1 | Stage 2 | Stage 3 | Stage 4

Stage 1_1.class
Stage 1_2.class
....

Stage 2_1.class
Stage 2_2.class
....

Stage 3_1.class
Stage 3_2.class
....

Stage 4_1.class
Stage 4_1.class

```

I know it's very noob, that's why I ask for your help to translate this to a more consistent, and efficient game or just give me an idea. I want to put each stage's main loop only in ONE ACTIVITY. Help is truly appreciated. Thanks.

# Answer
> 1 votes
I don't know if this is what you need, but you should write just one general class Stage and all of your questions are defined in some XML. When your game starts, it will create for example array of stages, which it will go through. And in each stage you can have loop which will just increment question number.

---
Tags: java, android
---


title: Recasting and Drawing in SDL

text:
# Question
Title: Recasting and Drawing in SDL
I have some code that essentially draws a column on the screen of a wall in a raycasting-type 3d engine. I am trying to optimize it, as it takes about 10 milliseconds do draw a million pixels using this, and the vast majority of game time is spent in this loop. However, I don't quite understand what's occurring, particularly the recasting (I modified the "pixel manipulation" sample code from the SDL documentation). "canvas" is the surface I am drawing to, and "hello" is the surface containing the texture for the column.

```
    int c = (curcol)* canvas->format->BytesPerPixel;
    void *canvaspixels = canvas->pixels;
    Uint16 texpitch = hello->pitch;
    int lim = (drawheight +startdraw) * canvpitch +c + (int) canvaspixels;
    Uint8 *k = (Uint8 *)hello->pixels + (hit)* hello->format->BytesPerPixel;

    for (int j= (startdraw)*(canvpitch)+c + (int) canvaspixels; (j< lim); j+= canvpitch){
        Uint8 *q = (Uint8 *) ((int(h))*(texpitch)+k);
        *(Uint32 *)j = *(Uint32 *)q;
        h += s;
    }

```

We have void pointers (not sure how those are even represented), 8, 16, and 32 bit ints (h and s are floats), all being intermingled, and while it works, it is quite confusing.

# Answer
Don't try to handle arbitrary surface formats inside your loop. If for some reason you can't just assume a fixed surface format, write wholly separate loops for each format. Write one loop that handles 24-bit source textures on a 24-bit output, a 32-bit source on a 24-bit output, etc., *as needed*. Libraries like liboil are meant to make this much easier if you need to handle a very large variety of formats, though I've no experience with that particular library myself.

You could also consider using SIMD instructions where appropriate. Also, you could probably split the screen into separate batches and use threading. You're massively under-utilizing your hardware with such a naive approach. Removing all the heavy casting might also help a lot; on a 32-bit machine, use nothing but 32-bit values in loops like these. Convertizing back and forth between 8-bit, 16-bit, and 32-bit values is not free. That also plays back into the "don't try to support arbitrary formats" inside your loop piece of advice. If you know your loop is handling only a particular format, you can make it much much faster. (16-bit or 32-bit is a wise choice; 24-bit does not align well).

There's also the obvious bit about how you're not using the GPU. Even if you want to avoid modern polygonal rendering, you could write this raycasting renderer as a compute shader. Which of course implicitly gives you SIMD and threading, but on a much larger and more capable scale than the CPU can provide.

As a bit of speculation: trying to use an early 90's rendering technique for a - by 90's standards - massive resolution (1,000,000 pixels is huge compared to the resolutions raycasting was used for, around 320x240 to 640x480, iirc). Also recall that these older games typically ran at a max of 16-bit color if not 8-bit paletted formats. The algorithm simply wasn't meant for today's market expectations. CPUs are significantly faster, of course, but I simply wouldn't be surprised if what you're trying to do is unfeasible; could be wrong.

So far as your note about void pointers, they're "represented" the same as any other pointer. There is no difference between a `void*` and an `int*` until you try to *dereference* the pointer or perform pointer arithmetic. Essentially, `int* p; int i = p[20];` is roughly equivalent to `void* p; int i = *(int*)((char*)p + 20 * sizeof(int));`, excepting any potential aliasing violations (casting pointers like you're doing is technically undefined behavior, though most compilers do exactly what you'd expect).
> 0 votes

# Answer
What do you mean by 'recasting'? If you just mean that the same Uint32\* cast appears on both sides of an assignment then that's just to ensure that q, which is a UInt8 pointer, gets read from as if it were a UInt32 pointer, and written into j, which is an int, but needs to be treated as a UInt32 pointer (to accept the value from q). But it's just copying a 32-bit value across. The pitch values tell the routine how far to move to read/write the next value. That's about it really.

I have no idea why an int is being cast to a pointer - that looks like bad code to me - but it's not something that will affect the speed.

I would be surprised if you can optimise that loop as it looks fairly optimal to me. (Although drawing columns like that is rarely optimal, which is why blitting typically does it by rows.)
> 1 votes

---
Tags: sdl, optimization
---


# Question
Title: I know that my super simple multiplayer setup is probably not a good idea, but why?
I'm making a simple little MOBA just for fun. I was making everything single-player then I realized "oh crap I should probably add multiplayer, huh."

I've never done anything with networking before, so learning how to integrate Lidgren into my game was fun and awesome. The thing is, I pretty much know the way I'm doing things is wrong, because it's not robust enough for mainstream games to use, as far as I know, but what's wrong with it?

What I'm doing is, basically, whenever a player does an action, it sends a message to the server saying "hey, I just did this thing." The server and the client are both running the same simulation. The server then sends a message to all other clients telling them that that guy did that thing.

For the most part, except in a few cases, when a player does a thing, the client assumes it's cool and goes ahead with it on its own. So when you right-click somewhere to move there, that player's client just starts moving his guy there, and *then* sends a message to the server telling it about it.

So basically:

* Player 1 casts a spell to make him move 100% faster for six seconds
* Player 1's local client adds that buff to his Unit object
* Player 1's client sends a message to the server saying "hey I just cast this spell"
* The server makes sure he really did have enough mana to cast that spell, and if so, adds that buff to the server's copy of that Unit object
* The server sends a message to all other clients saying "hey this guy just cast this spell"
* Every other client receives the message and goes "ah okay cool," and adds that buff to their local Unit object for that player

I've been skimming through stuff to see how big games do multiplayer, and it's kind of confusing for someone who's just starting to dabble in this stuff, but it looks like the Source engine sends a packet containing all of the changes to everything in the world every tick? Again, totally new to this stuff, but can you really push that much data that frequently?

Sorry if this is a bit rambly, but basically, I was wondering why my simpler system isn't the right way to go, because if it was, other games would use it, right?

# Answer
> 12 votes
In addition to Byte56's answer, there are a couple more things to consider:

How are you going to communicate between the clients about player movement? Unlike most other player actions, which tend to be isolated events and likely somewhat infrequent, movement is continuous. There is a limit to the rate at which you can (and want to, for that matter) send and receive updates. The Client-side prediction that Byte56 mentioned typically involves periodic updates about client position and velocity. The client then locally interpolates between them, using something like a Cubic Spline.

A second issue, which connects back to the previous ones, is that UDP does not have guaranteed delivery. You can not be certain that every message you send arrives, or even arrives in the right order. You could send packets 1, 2, and 3, and the server receives 3 then 1 and not 2. Often they'll be in the right order, and often they will arrive, but not always. So, you need a system that is robust to losing packets. A simple confirmation system is sufficient. Typically used is a bitfield telling the other node whether it has received the last 32 messages (for a 32bit int), and what the last message received was. This way, you can label messages as critical or not, and resend if they don't receive critical ones. There is a pretty decent discussion of it here.

You also need to keep in mind, when doing this, that your clients will be out of sync with eachother. Each will be showing the other players interpolating between their previous two network frames while you're working on the next one, in the best case scenario. So you need a system that takes into account (fairly) that what a player saw when he performed an action was not the actual state of the game when he did that action. He was reacting to an old, out-of-sync game state.

Finally, if this game is intended to be competitive, you also need to worry about cheating. Thus, to the extent possible (and reasonable), you must distrust the clients and verify their actions were possible. "No, you can't walk through that wall. No you can't walk faster than your run velocity. No, you can't claim to have hit that target." etc.

For more ideas, I recommend browsing the other articles in that second link.

Good luck!

# Answer
> 7 votes
What you're describing is essentially client-side prediction, but you don't say what happens when the server and client disagree.

It evolved from the days when the client was just a dumb terminal, sending its input to the server, and the server told the client the outcome. However, once games moved beyond the LAN (and frequently before) the latency was noticeable in this situation. What you're describing, client-side prediction was introduced to fix that. Now the client also simulates the movement while waiting for the server to respond. Then they come to an agreement on the outcome. With the server being the authority.

The next steps are how you respond to disagreements. If you don't have anything in place for that, you'll get the client rubber-banding or tele-porting when the client and server disagree.

# Answer
> 5 votes
Timing. The other answers don't mention the timing of events on the server and the different clients. Depending on the game, this could be something to watch out for. Latency (aka Lag) introduces a variable delay between when a packet is sent and when it is received. Time can be tricky, but I'll try to explain the potential issues as best I can. There are some games that can get by without worrying about this, but here's a simple example of where it can cause problems.

Assume that everyone acts on packets as soon as they arrive.

```
@ Time 0 (wall time), Player 1 puts up a shield   (Message has been sent, but not received by anyone)
@ Time 1, Player 2 shoots player 1   (Message has been sent, but not received by anyone)

```

Assume Time 0 (T0) and T1 are close together.

What happens next depends on who is looking at this, and on the order in which the packets arrive on the server. The server should always have the final say. IF the server receives the packets in the order given above, then the server will apply the shield before the shot and player 1 (P1) will survive. From P1's perspective, having put up the shield himself, he will see the shield before the shot and survive. But what about P2? They will see the shot right away because they shot it, but will they see the shield first? If `(T0 + latency between P1 and the server + the latency between the server and P2) > T1`, the shield will come up after the shot, and P2 will think their shot has killed P1. The server will have to correct this situation somehow.

If however, the server receives the packets in the reverse order (which is quite possible, even if T0 \< T1), then the opposite occurs. P1 is wrong (and dead), while P2 is correct (and victorious).

There are a few ways to deal with situations like this, but the easiest is to let the server do everything. You can attempt to simulate this on the client, but don't allow any permanent actions, like death. The players will have to wait for important game-changing confirmations from the server.

Sending a timestamp with actions can be beneficial. IF you mostly trust the clients, then you can use these timestamps can be used to determine which action happened first, instead of following our first assumption. This can be tricky, because receiving messages from the past usually means you need to be able to reverse time.

Time is fun eh? No matter what you end up doing, it's helpful to be aware of these time issues.

---
Tags: networking, multiplayer
---


title: Volume raycaster problems HLSL

text:
# Question
Title: Volume raycaster problems HLSL
I can't seem to get my volume raycaster to work properly. I've been poking around changing things for days trying to get it to display my volume correctly but I seem only to get distorted mutations of it.

What I tried to do was a 1-pass renderer because the 2-pass one I made wasn't good enough for my purposes. I'm using C# XNA and the renderer wont have to handle transparency so it only has to get in and fetch the first color it bumps into.

How it should look:

How it looks:

```
float4 OnePassPS(OnePassVSOutput input, float2 pixelCoord : VPOS) : COLOR0 {

float3 rayDir = normalize(mul(float3(((pixelCoord / WindowSize) * 2) - 1.0, -FocalLength), ModelView));

float4 pos = float4(RayOrigin + (rayDir * (input.pos.z / input.pos.w)), 0);
float3 Step = rayDir * StepSize;

float4 color = float4(0, 0, 0, 0);
for(int i = 0; i < Iterations; i++)
{
    color = tex3Dlod(VolumeS, pos);

    if(color.a > 0)
        break;

    pos.xyz += Step;
}
return color; }

```

# Answer
```
float3 rayDir = normalize(mul(float3(((pixelCoord / WindowSize) * 2) - 1.0, -FocalLength), ModelView));

```

this code is defintly wrong, i see the following problem here:

* (a) You use a usual matrix operation to transform a direction, which is plainly wrong (you need different matrices for transforming positions and directions)

Your Matrix looks like this (from your comment)

```
Matrix.CreateTranslation(-Vector3.One / 2) * Matrix.CreateScale(10) * Matrix.CreateLookAt(camera.Position, Vector3.Zero, Vector3.Up);

```

to illustrate the problem here we take as an example a `(0.7, 0.7, 0.0)` unity normalized vector, when i multiply it with `Matrix.CreateTranslation(5.0, 0.0, 0.0)` i get as direction `(5.7, 0.0, 0.0)` which is no more normalized and wrong.

After showing why it is wrong i give you the advice, let (most of) the matrix stuff out of it and do the following (a version using matrices exists too for sure but i do it with vectors):

* calculate the (normalized) direction of the look direction `lookDir` with rotating a unity vector
* calculate the `HorizontalVector` using the cross product `HorizontalVector = lookDir.cross(UpVector).normalized()`
* calculate the vertical vector `VerticalVector = HorizontalVector.cross(lookDir).normalized()`

now you can calculate the direction for each pixel with the following formula

`Dir = (lookDir + VerticalVector.scale(pixelCoord.X / WindowSize.X - 0.5f) + HorizontalVector.scale(pixelCoord.Y / WindowSize.Y - 0.5f)).normalized()`

Note that you have to check that the Vertical and Horizontal Vectors point in the right direction, if not switch the cross product.
> 0 votes

---
Tags: xna, c#, rendering, hlsl, raycasting
---


title: What makes a game "casual?"

text:
# Question
Title: What makes a game "casual?"
I've seen the term "casual" used to describe games at times, and have seen people refer themselves or others as "casual gamers."

What exactly is a "casual" game? Is there any real difference between them and regular games? If so, what makes a game "casual?"

# Answer
> 28 votes
Time investment is the main criteria. If a game can be rewarding to players who only pop in every so often and only for short time periods, it is casual. "Hardcore" games are those which require either a lot of time investment into skill (possibly from playing other similar games) or time investment into game sessions in order to enjoy the experience.

An FPS is "hardcore" in that a player must spend time learning and mastering the FPS controls. Games like Baldur's Gate are hardcore in that they require extensive time playing and exploring the story to properly enjoy. FarmVille is "casual" as anyone can pick up the core game in minutes and only require a few minutes per day to enjoy (though some people can certainly spend way more time playing and mastering the game).

# Answer
> 7 votes
I think the wikipedia article on casual games answers the question pretty well as to *what* casual games are.

It should be noted that people who describe themselves as "casual gamers" don't necessarily play casual games. "Casual" can describe their dedication to games or the amount of time spent playing them. The games they play could easily be the same games someone who describes themselves as a "hardcore" gamer plays. In this sense, they use the term "casual" to tell you it's not something they're really serious about.

However, it's likely that statistics relating to gamers may have a category of "casual gamers", that would identify a group of people who play casual games.

Just be aware of the context these terms are used in and they should be easy enough to distinguish.

# Answer
> 6 votes
"Casual games" are targeted at a wider audience than other (often considered more "hardcore") games are.

Typically this is accomplished by having simpler game mechanics and controls that are easier to pick up and understand for people who might otherwise not play very many games, and by being much easier to pick up and play for brief periods of time (such as while travelling on a bus).

Early casual games were primarily played through web browsers (via Flash portals). While such games are still around, the rise of the smartphone platform has allowed many casual games to migrate to those devices.

---
Tags: terminology, casual-games
---


title: FBX models into Directx 11

text:
# Question
Title: FBX models into Directx 11
I've just ported over and updated a bunch of FBX model loading code I had that worked with Direct X 10 to try and make it work with Direct X 11. Since that time, the FBX SDK I was using has been updated.

In my old program I linked to the following lib:

```
fbxsdk-2012.2-mdd.lib

```

Now, clearly I can't link to this as I don't have 2012.2 on my system. So, my thinking would be simply changing 2012.2 to 2014.1, but this didn't work and lead to the following error:

```
error LNK1104: cannot open file 'fbxsdk-2014.1-mdd.lib'

```

So I tried to some googleing to see what the updated version of fbxsdk-2012.2-mdd.lib is. But I can't find anything. I tried taking out linking ot the 2014.1 lib but I get the following errors:

> Error 36 error LNK2019: unresolved external symbol "void \__cdecl fbxsdk\_2014\_1::FbxAssert(char const \*,char const \*,unsigned int,char const \*)" (?FbxAssert@fbxsdk\_2014\_1@@YAXPBD0I0@Z) referenced in function "public: int & \__thiscall fbxsdk\_2014\_1::FbxArray::operatorconst " (??A?$FbxArray@H@fbxsdk\_2014\_1@@QBEAAHH@Z)

So, looking in the FBX sample directory I opened up the ViewScene sample to see what it lib it linked to and I see that it wanted the following:

```
libfbxsdk-md.lib

```

So I did the same. But, my program claims it cannot open the file. And I'm at a loss as to what to do next.

Has anyone successfully managed to load FBX models into a Directx 11 application using 2014.1? If so, what do I need to do to get the correct lib linked?

# Answer
> 1 votes
For debug configurations just add:

> C:\Program Files\Autodesk\FBX\FBX SDK\2014.1\lib\vs2012\x86\Debug\libfbxsdk-md.lib

To your project properties:

> Properties -\> Linker -\> Input -\> Additional Directories

---
Tags: c++, fbx
---


title: Multilayer game HTML5 canvas

text:
# Question
Title: Multilayer game HTML5 canvas
I've have a problem with HTML5 canvas and using multiple layers.

I'm using 3 layers. The first layer is where the player and the collision base objects are. And the second and the third layer have the rest of that objects, and that are suppose to cover the character if is behind them. But I have this problem:

The tile in the upper layer than the character cover him, even if he is in front of that object.

And I have other problem:

When is a the back of the element, there's a part of the character that appears in the middle of the poster.

How can I resolve this? I don't know how exactly do this, and I think that use layers is not very convenient.

Here's how I render the map:

```
function drawMap () {

for (var rowCtr = 0; rowCtr < map.tileMap[0].length; rowCtr++) {

    for (var colCtr = 0; colCtr < map.tileMap[0][0].length; colCtr++){

        var tileId  = map.tileMap[0][rowCtr][colCtr] - 1;
        var sourceX = Math.floor(tileId % 8) * 32;
        var sourceY = Math.floor(tileId / 8) * 32;

        ctx.drawImage(map.sprite.img, sourceX, sourceY, 32, 32, colCtr * 32, rowCtr * 32, 32, 32);

    }

}

finn.movement(this.ctx, this.world);

if (map.tileMap.length > 1) {

    for (var capa = 1; capa < map.tileMap.length; capa++) {

        for (var rowCtr = 0; rowCtr < map.tileMap[0].length; rowCtr++) {

            for (var colCtr = 0; colCtr < map.tileMap[0][0].length; colCtr++){

                var tileId  = map.tileMap[capa][rowCtr][colCtr] - 1;
                var sourceX = Math.floor(tileId % 8) * 32;
                var sourceY = Math.floor(tileId / 8) * 32;

                ctx.drawImage(map.sprite.img, sourceX, sourceY, 32, 32, colCtr * 32, rowCtr * 32, 32, 32);

            }

        }

    }

  }

}

```

And here's an example of the map:

```
  `[
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 1, 1, 0]
   ],
   [
    [0, 0, 0, 0],
    [0, 1, 1, 0],
    [0, 1, 1, 0],
    [0, 0, 0, 0]
   ]`

```

That's the array of the layers. The first is the first layer, where the character moves, and the second element is the layer where the part of the objects which cover are drew.

Is there any solution for this without using any external Engine, only using canvas and javascript?

Thanks advance!

# Answer
> 4 votes
## Issue 1: Headless avatar

This issue is caused by the draw order of the layers. From your pasted code, the draw order is:

1. Draw the background and objects in the collision grid (ie: the bottom half of the sign)
2. Call finn.movement() which I assume is when the character is drawn
3. Draw the remaining object layers, in this case the top half of the sign.

I have added this jsfiddle to attempt to illustrate the draw order and how the issue occurs. http://jsfiddle.net/WxmpG/

To fix this problem I suggest that you loop each row and draw all layers per row from base to highest floating instead of looping layers in rising order and drawing the rows.

## Issue 2: Toes in the sign.

I believe that this is an issue with your collision detection or avatar rendering. I think that your avatar is a pixel or two too low and is drawn over the top of the bottom of the sign. Here is another jsfiddle to hopefully exaggerate the point. http://jsfiddle.net/c7sS7/

When I first started looking at tilemaps I found a resource that helped me understand the core concepts of rendering tilemaps. Among the articles is #10 Javascript tile engine: speed, tile size & **floating tiles**. Although his engine only works when the avatar is the same size as the tiles.

* nielsgrootobbink.com/wokflok/jte/
* nielsgrootobbink.com/wokflok/jte/jte\_article\_10.html

Sorry that the last links are incomplete, I do not have enough rep to post more than 2 links.

---
Tags: javascript, html5, html-canvas
---


title: Importing and Displaying .fbx files

text:
# Question
Title: Importing and Displaying .fbx files
I have a little problem with importing/displaying .fbx files.

I checked the examples but the ones which I am intrested the most (animation and texture) are badly documented for understanding by someone who is new to this like I am.

This is what I have tried: I managed to get the vertices and the normals but I'm stuck on getting the texture coords for each vertex.

Here is my code so far:

3dModelBasicStructs.h

```
struct vertex
{
float x,y,z;
};

struct texturecoords
{
float a,b;
};

struct poligon
{
int a,b,c;
};

```

Model.h

```
#ifndef MODEL_H
#define MODEL_H
#define FBXSDK_NEW_API

#define MAX_VERTICES 80000

#include "3dModelBasicStructs.h"

#include <fbxsdk.h>
#include <iostream>
#include <GL/glut.h>
using namespace std;

class Model
{

     public:

         Model(char*);
         ~Model();

         void ShowDetails();

         char* GetModelName();
         void  SetModelName( char* );
         void  GetFbxInfo( FbxNode* );
         void  RenderModel();

      private:

          char Name[25];

          vertex vertices[MAX_VERTICES];
          texturecoords txt[MAX_VERTICES];

          float *normals;
          int numNormals;

          int *indices;
          int numIndices;

          int numVertices;

};
#endif

```

Model.cpp

```
#include "Model.h"

Model::Model(char *filename)
{
cout<<"\nA model has been built!";

numVertices=0;
numIndices=0;

FbxManager *manager = FbxManager::Create();

FbxIOSettings *ioSettings = FbxIOSettings::Create(manager, IOSROOT);
manager->SetIOSettings(ioSettings);

FbxImporter *importer=FbxImporter::Create(manager,"");
importer->Initialize(filename,-1,manager->GetIOSettings());

FbxScene *scene = FbxScene::Create(manager,"tempName");

importer->Import(scene);
importer->Destroy();

FbxNode* rootNode = scene->GetRootNode();
this->SetModelName(filename);
if(rootNode) { this->GetFbxInfo(rootNode); }

}

Model::~Model()
{
cout<<"\nA model has been destroyed!";
glDisableClientState(GL_VERTEX_ARRAY);
}

void Model::ShowDetails()
{
cout<<"\nName:"<<Name;
cout<<"\nVertices Number:"<<numVertices;
cout<<"\nIndices Number:"<<numIndices;

}

char* Model::GetModelName()
{
return Name;
}

void Model::SetModelName(char *x)
{
strcpy(Name,x);
}

void Model::GetFbxInfo( FbxNode* Node )
{

int numKids = Node->GetChildCount();
FbxNode *childNode = 0;

for ( int i=0 ; i<numKids ; i++)
{
    childNode = Node->GetChild(i);
    FbxMesh *mesh = childNode->GetMesh();

    if ( mesh != NULL)
    {
//================= Get Vertices ====================================
        int numVerts = mesh->GetControlPointsCount();

        for ( int j=0; j<numVerts; j++)
        {
            FbxVector4 vert = mesh->GetControlPointAt(j);
            vertices[numVertices].x=(float)vert.mData[0];
            vertices[numVertices].y=(float)vert.mData[1];
            vertices[numVertices++].z=(float)vert.mData[2];
    //      cout<<"\n"<<vertices[numVertices-1].x<<" "<<vertices[numVertices-1].y<<" "<<vertices[numVertices-1].z;
        }
//================= Get Indices ====================================
        numIndices=mesh->GetPolygonVertexCount();
        indices = new int[numIndices];
        indices = mesh->GetPolygonVertices();
        cout<<numIndices;
//================= Get Normals ====================================

        FbxGeometryElementNormal* normalEl = mesh->GetElementNormal();
        if( normalEl)
        {
            numNormals = mesh->GetPolygonCount()*3;
            normals = new float[numNormals*3];
            int vertexCounter=0;
            for(int polyCounter = 0 ; polyCounter<mesh->GetPolygonCount(); polyCounter++)
            {
                for(int i=0;i<3;i++)
                {
                    FbxVector4 normal = normalEl->GetDirectArray().GetAt(vertexCounter);
                    normals[vertexCounter*3+0] = normal[0];
                    normals[vertexCounter*3+1] = normal[1];
                    normals[vertexCounter*3+2] = normal[2];
                    cout<<"\n"<<normals[vertexCounter*3+0]<<" "<<normals[vertexCounter*3+1]<<" "<<normals[vertexCounter*3+2];
                    vertexCounter++;
                }
            }
        }

    }
    this->GetFbxInfo(childNode);
}
}

void Model::RenderModel()
{
int i,j;
for(i=0;i<numIndices-3;i++)
{
    glBegin(GL_TRIANGLES);
    glNormal3f(normals[i*3+0],normals[i*3+1],normals[i*3+2]);
    for(j=i;j<=i+2;j++)
            glVertex3f(vertices[indices[j]].x,vertices[indices[j]].y,vertices[indices[j]].z);
    glEnd();
}
}

```

My questions are:

1. How do I get the texture coords?
2. How do I make blender export the texture in a photo format? (like .jpg or .tga)
3. Are there any mistakes in my displaying way so far?
4. Is there a project in the .fbx samples which only display a scene (including animation and texture; I couldn't find one myself)?

# Answer
> 3 votes
*Regarding #1*: The method GetTextureUV of FbxMesh should get the trick done.

**EDIT:** The following code is untested and rougly copied from here:

```
int polygonCount = mesh->GetPolygonCount();
for (int i = 0; i < polygonCount; ++i) {

  FbxLayerElementArrayTemplate<KFbxVector2>* uvVertices= 0;
  mesh->GetTextureUV(&uvVertices, KFbxLayerElement::eTextureDiffuse);

  for (int j = 0; j < mesh>GetPolygonSize(i); ++j) {

     FbxVector2 uv = uvVertices[mesh->GetTextureUVIndex(i, j)];

     texturecoords.a = uv[0];
     texturecoords.b = uv[1];

  }
}

```

**EDIT 2:** I went through some other examples I found: There seems to be two similar classes: FbxVector2 and KFbxVector2 where the latter one has the direct access to the included double values. Compare that example:

```
KFbxLayerElementArrayTemplate<KFbxVector2>* lUVArray = NULL;
pMesh->GetTextureUV(&lUVArray, KFbxLayerElement::eDIFFUSE_TEXTURES);

lUVArray->GetAt(mesh->GetTextureUVIndex(i, j)).mData[0];

```

Can you use those K\* types?

**EDIT3:** Those K\* types are apparently from an older FBX SDK, so not relevant for everyone.

# Answer
> 2 votes
I am no expert in FBX but I have some experience with it, here are my suggestions

> How do I get the texture coords? Is there a project in the .fbx samples which only display a scene (including animation and texture; I couldn't find one myself)?

I would suggest going over the example in $(FBXSDK)\samples\ImportScene

This will show you how to get the UV Coords and other data

> How do I make blender export the texture in a photo format? (like .jpg or .tga)

I have not work with blender exporting FBX, sorry

> Are there any mistakes in my displaying way so far?

I had a quick look at your code, so can't say 100% if you have mistakes, but I will give you some suggestions that I learn working with FBX SDK.

Depending on the 3D Software you have to check if you need to convert your UV Coords. For example it could be the same as what your software expects or you need to do this

mine.U = fbx.U

mine.V = 1 - fbx.V

Also FBX depending on the exporter (my experience with 3ds max) it will change Y & Z for translations only, rotation will be inverted. What I want to say is if you export (in 3ds max) Y-UP, lclTranslation will match 1:1 but lclRotation will be like this

myRot.x = fbxRot.x

myRot.y = fbxRot.z

myRot.z = fbxRot.y

Also remember to check to check if the coordinate system is Left or Right and if it matches what your software expect, if not correct it.

Creating and custom importer for FBX is challenging do not give up!

# Answer
> 2 votes
Getting texture coordinates for models with one UV set Using FBX SDK 2013:

```
// UV Container
std::vector<float[2]> UVList;

// Loop for each poly
for ( int Poly(0); Poly < fbxMesh->GetPolygonCount(); Poly++ )
{
    // Get number of verts in this poly
    const int NumVertices = fbxMesh->GetPolygonSize( Poly );

    // Loop for each vert in poly
    for( int Vertex(0); Vertex < NumVertices; Vertex++ )
    {
         FbxVector2 fbxTexCoord;
         FbxStringList UVSetNameList;

         // Get the name of each set of UV coords
         fbxMesh->GetUVSetNames( UVSetNameList );

         // Get the UV coords for this vertex in this poly which belong to the first UV set
         // Note: Using 0 as index into UV set list as this example supports only one UV set
         fbxMesh->GetPolygonVertexUV( Poly, Vertex, UVSetNameList.GetStringAt(0), fbxTexCoord );

         // Convert to floats
         float UVCoord[2];
         UVCoord[0] = static_cast<float>( fbxTexCoord[0] );
         UVCoord[1] = static_cast<float>( fbxTexCoord[1] );

         // Store UV
         UVList.push_back( UVCoord );
     }
}

```

---
Tags: c++, opengl, 3d, models, fbx
---


# Question
Title: Engine Rendering pipeline : Making shaders generic
I am trying to make a 2D game engine using OpenGL ES 2.0 (iOS for now). I've written Application layer in Objective C and a separate self contained RendererGLES20 in C++. No GL specific call is made outside the renderer. It is working perfectly.

But I have some design issues when using shaders. Each shader has its own unique attributes and uniforms that need to be set just before the main draw call (glDrawArrays in this case). For instance, in order to draw some geometry I would do:

```
void RendererGLES20::render(Model * model)
{
    // Set a bunch of uniforms
    glUniformMatrix4fv(.......);
    // Enable specific attributes, can be many
    glEnableVertexAttribArray(......);
    // Set a bunch of vertex attribute pointers:
    glVertexAttribPointer(positionSlot, 2, GL_FLOAT, GL_FALSE, stride, m->pCoords);

    // Now actually Draw the geometry
    glDrawArrays(GL_TRIANGLES, 0, m->vertexCount);

    // After drawing, disable any vertex attributes:
    glDisableVertexAttribArray(.......);
}

```

As you can see this code is extremely rigid. If I were to use another shader, say ripple effect, i would be needing to pass extra uniforms, vertex attribs etc. In other words I would have to change the RendererGLES20 render source code just to incorporate the new shader.

Is there any way to make the shader object totally generic? Like What if I just want to change the shader object and not worry about game source re-compiling? Any way to make the renderer agnostic of uniforms and attributes etc?. Even though we need to pass data to uniforms, what is the best place to do that? Model class? Is the model class aware of shader specific uniforms and attributes?

Following shows Actor class:

```
class Actor : public ISceneNode
{
    ModelController * model;
    AIController * AI;
};

```

Model controller class: class ModelController { class IShader * shader; int textureId; vec4 tint; float alpha; struct Vertex * vertexArray; };

Shader class just contains the shader object, compiling and linking sub-routines etc.

In Game Logic class I am actually rendering the object:

```
void GameLogic::update(float dt)
{
    IRenderer * renderer = g_application->GetRenderer();

    Actor * a = GetActor(id);
    renderer->render(a->model);
}

```

Please note that even though Actor extends ISceneNode, I haven't started implementing SceneGraph yet. I will do that as soon as I resolve this issue.

Any ideas how to improve this? Related design patterns etc?

Thank you for reading the question.

# Answer
> 12 votes
It's possible to make your shader system more data-driven, so that you don't have so much shader-specific code laying around for uniforms and vertex formats, but rather set them programmatically based on metadata attached to the shaders.

First the disclaimer: a data-driven system can make it easier to add new shaders, but on the other hand it comes with costs in terms of the increased complexity of the system, which makes it harder to maintain and debug. So it's a good idea to think carefully about just how much data-drivenness will be good for you (for a small project, the answer might well be "none"), and don't try to build a system that's overly generalized.

Okay, let's talk about vertex formats (attributes) first. You can create a data description by making a struct that contains the data to pass to `glVertexAttribPointer` \- the index, type, size, etc. of a single attribute - and having an array of those structs to represent the whole vertex format. Given this information, you can programmatically set up all the GL state related to the vertex attributes.

Where does the data to populate this description come from? Conceptually, I think the cleanest way is to have it belong to the shader. When you build the vertex data for a mesh, you would look up which shader is used on the mesh, find the vertex format required by that shader, and build the vertex buffer accordingly. You just need some way for each shader to specify the vertex format it expects.

There are a variety of ways to do this; for instance, you could have a standard set of names for the attributes in the shader ("attrPosition", "attrNormal", etc.) plus some hard-coded rules like "position is 3 floats". Then you use `glGetAttribLocation` or similiar to query which attributes the shader uses, and apply the rules to build the vertex format. Another way is to have an XML snippet defining the format, embedded in a comment in the shader source and extracted by your tools, or something along those lines.

For uniforms, if you can use OpenGL 3.1 or later it's a good idea to use uniform buffer objects (the OpenGL equivalent of D3D's constant buffers). Alas, GL ES 2.0 doesn't have those, so uniforms have to be handled individually. One way to do it would be to create a struct containing the uniform location for each parameter you want to set - the camera matrix, specular power, world matrix etc. Sampler locations could be in here too. This approach depends on there being a standard set of parameters shared across all shaders. Not every shader has to use every single parameter, but all parameters would have to be in this struct.

Each shader would have an instance of this struct, and when you load a shader you'd query it for the locations of all the parameters, using `glGetUniformLocation` and standardized names. Then whenever you need to set a uniform from code, you can check if it's present in that shader, and just look up its location and set it.

---
Tags: opengl, shaders, scene-graph, pipeline
---


# Question
Title: Minimizing amount of comparisons for collisions?
In my 'Terraria' based game I am having lag issues. The cause of the lag is as follows:

* Every update loop through all the tiles in the world:
* If the rectangle that was passed as an arg intersects with the current tiles rectangle return true. If not go to the next tile.
* If the rectangle that was passed as an arg doesn't intersect with any of the tiles rectangles then return false.

My solution is to only check collisions for the tiles that are on the screen. At the moment my code renders all of the tiles regardless of the position. I know that this is a very lag-filled approach and I have no idea at all what the maths is to only get the tiles the player can see. If it helps the world is stored in a hash map that is initialised like this:

```
public Map<Integer, Tile> world = new HashMap<Integer, Tile>();
// numeric id = key , tile = value

```

I have tried looping through the tiles in 2 ways:

```
public boolean checkCollision(Rectangle argRect)
{
    for(int i = 0; i < world.size(); i++){
        Tile tile = world.get(i);
        Rectangle tileRect = new Rectangle(tile.rect);

        if(tileRect.intersects(argRect)){
            return true;}
    }
    return false;
}

```

And:

```
public boolean checkCollision(Rectangle argRect)
{
    for (Entry<Integer, Tile> entry : world.entrySet()) {
          Object key = entry.getKey();
          Tile tile =  world.get(key);
          Rectangle tileRect = new Rectangle(tile.rect);
          if(tileRect.intersects(argRect)){return true;}
    }
    return false;
}

```

Could I pass the players position to this method and have it only loop through tiles in the area? Would this approach have to loop through the tiles to see which ones are in the area?

# Answer
> 5 votes
There are a couple things you can do.

First, don't update every tile every tick of the game. Games like Terraria do periodic updates on only parts of the world at any time. Sub-divide your tile grid into chunk. Update one chunk each tick. You don't need to do it any more. You might even need to do it less. Things like growing grass and such are literally just a random check each time a tile is updated. You can control the rate of growth by altering how often ticks are done and how rare the random chance is.

For collision, you can limit it even further than what's on screen. In fact, for enemies near the edge of the screen, using only tiles on screen may be incorrect.

Instead, check the tiles that your rectangle could possibly be colliding with. You have a grid world. This is super easy. Take the upper left position of your rectangle, determine which tile that's in. Take the bottom right and do the same. Now you have the exact rectangle worth of tiles you can possibly be colliding with. This is probablyl (hopefully) what you do for drawing. Check against those. You could even with a little extra work determine which *new* tiles you could be colliding with (say, if you move right, and you can only move so fast each update, at most you have to check the right edge's worth of tiles), though there's probably no reason to do that.

Note that breaking your world into chunks can have further performance advantages. Generally, there will be one-four chunks visible at any given time. If you lay out the whole world in rows, each tile in each row is entire world's width away in memory. This can cause some (very slight) overhead. Keeping things in chunks means that a whole rectangle of tiles (left to right, top to bottom) are relatively close together in memory. If you process tiles in whole chunks at a time, this means your code runs slightly faster because more of the interesting data will be in cache at any given time.

Don't use a hashmap for your world. A hashmap is cheaper than many data structures, but your world (or a chunk in the world) is a 2D grid. Just use an array, which is always the absolute cheapest data structure when it is an option (and will be orders of magnitude more efficient than a hashmap in this case, I'd bet). I don't recall if Java supports 2D arrays automatically, but if not, just remember that `array[y][x]` is the same thing as `array[y * width + x]` and carry on.

Also avoid using full objects for your tiles. A simple integer will do if you are clever, do the world update trick I mentioned, and maybe a little bit packing. Objects are heavy-weight heap-allocated things in Java and a big grid of tiles will be inefficient as full objects. Likewise, avoid using operator `new` anywhere you don't strictly need it. Consider passing in rectangles to collision as simpler values (either explicit, `x`, `y`, `w`, `h` or using existing vectors and rectangles from your entities). `new` is not the cheapest operation, increases pressure on the garbage collecto

---
Tags: java, collision-detection, tiles, lwjgl
---


# Question
Title: sharing preferences between two apps on android with libgdx
I am making an android game with both a demo version and a paid version. I want users who decide to buy the paid version to continue from where they left off, with all their old data and settings.

I've set a shared user id between both applications, and now I'm wondering if it's possible to use libgdx preferences across both versions.

I am also open to other ideas on how to implement this.

# Answer
> 2 votes
You will not be able to do this with the libgdx API because this is more closely related to how android handles preferences.

Internally, libgdx uses android.content.SharedPreferences to store the preference data. You will have to write android code to make the preferences globally readable and then you will be able to access it across applications. An example of how to do this can be found on a stackoverflow question here.

---
Tags: android, libgdx, savegame
---


title: Library like ENet, but for TCP?

text:
# Question
Title: Library like ENet, but for TCP?
I'm not looking to use boost::asio, it is overly complex for my needs.

I'm building a game that is cross platform, for desktop, iPhone and Android.

I found a library called ENet which is pretty much what I need, but it uses UDP which does not seem to support encryption and a few other things. Given that the game is an event driven card game, TCP seems like the right fit.

However, all I have found is WINSOCK / berkley sockets and bost::asio.

Here is a sample client server application with ENet:

```
#include <enet/enet.h>
#include <stdlib.h>
#include <string>
#include <iostream>

class Host
{
    ENetAddress address;
    ENetHost * server;
    ENetHost* client;
    ENetEvent event;
public:
    Host()
        :server(NULL)
    {
        enet_initialize();
        setupServer();
    }

    void setupServer()
    {
        if(server)
        {
            enet_host_destroy(server);
            server = NULL;
        }

        address.host = ENET_HOST_ANY;
        /* Bind the server to port 1234. */
        address.port = 1721;

        server = enet_host_create (& address /* the address to bind the server host to */,
            32      /* allow up to 32 clients and/or outgoing connections */,
            2      /* allow up to 2 channels to be used, 0 and 1 */,
            0      /* assume any amount of incoming bandwidth */,
            0      /* assume any amount of outgoing bandwidth */);

    }

     void daLoop()
     {
         while(true)
         {
             /* Wait up to 1000 milliseconds for an event. */
             while (enet_host_service (server, & event, 5000) > 0)
             {
                 ENetPacket * packet;

                 switch (event.type)
                 {
                 case ENET_EVENT_TYPE_CONNECT:
                     printf ("A new client connected from %x:%u.\n",
                         event.peer -> address.host,
                         event.peer -> address.port);

                     /* Store any relevant client information here. */
                     event.peer -> data = "Client information";

                     /* Create a reliable packet of size 7 containing "packet\0" */
                     packet = enet_packet_create ("packet",
                         strlen ("packet") + 1,
                         ENET_PACKET_FLAG_RELIABLE);

                     /* Extend the packet so and append the string "foo", so it now */
                     /* contains "packetfoo\0"                                      */
                     enet_packet_resize (packet, strlen ("packetfoo") + 1);
                     strcpy ((char*)& packet -> data [strlen ("packet")], "foo");

                     /* Send the packet to the peer over channel id 0. */
                     /* One could also broadcast the packet by         */
                     /* enet_host_broadcast (host, 0, packet);         */
                     enet_peer_send (event.peer, 0, packet);
                     /* One could just use enet_host_service() instead. */
                     enet_host_flush (server);

                     break;

                 case ENET_EVENT_TYPE_RECEIVE:
                     printf ("A packet of length %u containing %s was received from %s on channel %u.\n",
                         event.packet -> dataLength,
                         event.packet -> data,
                         event.peer -> data,
                         event.channelID);

                     /* Clean up the packet now that we're done using it. */
                     enet_packet_destroy (event.packet);

                     break;

                 case ENET_EVENT_TYPE_DISCONNECT:
                     printf ("%s disconected.\n", event.peer -> data);

                     /* Reset the peer's client information. */

                     event.peer -> data = NULL;
                 }
             }
         }

     }

        ~Host()
    {
        if(server)
        {
            enet_host_destroy(server);
            server = NULL;
        }

        atexit (enet_deinitialize);
    }
};

class Client
{
    ENetAddress address;
    ENetEvent event;
    ENetPeer *peer;
    ENetHost* client;
public:
    Client()
        :peer(NULL)
    {
        enet_initialize();
        setupPeer();
    }

    void setupPeer()
    {

        client = enet_host_create (NULL /* create a client host */,
            1 /* only allow 1 outgoing connection */,
            2 /* allow up 2 channels to be used, 0 and 1 */,
            57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */,
            14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */);

        if (client == NULL)
        {
            fprintf (stderr,
                "An error occurred while trying to create an ENet client host.\n");
            exit (EXIT_FAILURE);
        }

        /* Connect to some.server.net:1234. */
        enet_address_set_host (& address, "192.168.2.13");
        address.port = 1721;

        /* Initiate the connection, allocating the two channels 0 and 1. */
        peer = enet_host_connect (client, & address, 2, 0);

        if (peer == NULL)
        {
            fprintf (stderr,
                "No available peers for initiating an ENet connection.\n");
            exit (EXIT_FAILURE);
        }

        /* Wait up to 5 seconds for the connection attempt to succeed. */
        if (enet_host_service (client, & event, 20000) > 0 &&
            event.type == ENET_EVENT_TYPE_CONNECT)
        {
            std::cout << "Connection to some.server.net:1234 succeeded." << std::endl;
        }
        else
        {
            /* Either the 5 seconds are up or a disconnect event was */
            /* received. Reset the peer in the event the 5 seconds   */
            /* had run out without any significant event.            */
            enet_peer_reset (peer);

            puts ("Connection to some.server.net:1234 failed.");
        }
    }

    void daLoop()
    {
        ENetPacket* packet;

        /* Create a reliable packet of size 7 containing "packet\0" */
        packet = enet_packet_create ("backet",
            strlen ("backet") + 1,
            ENET_PACKET_FLAG_RELIABLE);

        /* Extend the packet so and append the string "foo", so it now */
        /* contains "packetfoo\0"                                      */
        enet_packet_resize (packet, strlen ("backetfoo") + 1);
        strcpy ((char*)& packet -> data [strlen ("backet")], "foo");

        /* Send the packet to the peer over channel id 0. */
        /* One could also broadcast the packet by         */
        /* enet_host_broadcast (host, 0, packet);         */
        enet_peer_send (event.peer, 0, packet);
        /* One could just use enet_host_service() instead. */
        enet_host_flush (client);

        while(true)
        {
            /* Wait up to 1000 milliseconds for an event. */
            while (enet_host_service (client, & event, 1000) > 0)
            {
                ENetPacket * packet;

                switch (event.type)
                {
                case ENET_EVENT_TYPE_RECEIVE:
                    printf ("A packet of length %u containing %s was received from %s on channel %u.\n",
                        event.packet -> dataLength,
                        event.packet -> data,
                        event.peer -> data,
                        event.channelID);

                    /* Clean up the packet now that we're done using it. */
                    enet_packet_destroy (event.packet);

                    break;
                }
            }
        }
    }
    ~Client()
    {
        atexit (enet_deinitialize);
    }
};

int main()
{
    std::string a;
    std::cin >> a;
    if(a == "host")
    {
        Host host;
        host.daLoop();
    }
    else
    {
        Client c;
        c.daLoop();
    }

    return 0;
}

```

I looked at some socket tutorials and they seemed a bit too low level.

I just need something that abstracts away the platform (eg, no WINSOCKS) and that has basic ability to keep track of connected clients and send them messages.

Thanks

# Answer
> 2 votes
If you control the coding of both server and client, RakNet could be something you might want to look into. It is not strictly TCP only. So if you decide that later you want to switch back to UDP, for whatever reason, it would be a painless transition.

# Answer
> 0 votes
Perhaps the Unicomm library will be suitable for you. It wraps Boost.Asio and provides high-level abstraction for the communication setup.

# Answer
> -1 votes
Well Enet is even use by league of legends. And it work pretty fine. Keep it and use blowfish as encryption.

---
Tags: c++, networking
---


title: Heightmap and Textures

text:
# Question
Title: Heightmap and Textures
Im trying to find the "best way" to apply a texture to a heightmap with opengl 3.x.

Its really hard to find something on google because tutorials are olds and they're all using different methods, im really lost and i dont know what to use at all.

Here is my code that generates the heightmap (its basic)

```
    float[] vertexes = null;
    float[] textureCoords = null;

    for(int x = 0; x < this.m_size.width; x++)
    {
        for(int y = 0; y < this.m_size.height; y++)
        {
            vertexes ~= [x, 1.0f, y];
            textureCoords ~= [cast(float)x / 50, cast(float)y / 50];
        }
    }

```

As you can see, i dont know how to apply the texture at all (i was using / 50 for my tests).

Result of that code :

I would like to have something very basic like :

(you can find more pics in his blog)

Edit : my texture size is 1024x1024.

# Answer
> 2 votes
Basicly it's all the same method.

You have a texture at the same size of your grid. lets go with your 1024x1024. that would be ideal to have a grid that is 1024 x 1024 then.

The first thing you do is to get a pointer or some access to the texture, so you can iterate over it.

The second thing you do is to have access to the vertex buffer. from there you iterate all of the vertices and give them values corresponding to the texture.

So, lets say this:

```
For x < 1024; ++x
for y < 1204; ++y
vertex[ y * 1024 + x ] = float4( x, textureArray[ y * 1024 + x].value, y );

```

This is the most simplest way i can explain this to you. but that is the basic idea. and the code will go thrue all the vertices and find the exact same pixel from the texture.

And from there you can add spacing, and what ever you want!

---
Tags: opengl, textures, heightmap
---


title: Set up indie game studio (UK) - how?

text:
# Question
Title: Set up indie game studio (UK) - how?
I am UK based and am looking to set up my own game studio - essentially, just myself working from home, looking to build casual game apps. I want to ask you guys what steps or process i need to go through and do to make this happen, specifically the legal side of things. Will be great to hear from those who have been through this themselves! Need to register with HRMC as self employed is the only thing i know i have to do but what else?:

1. Do i need to register/trademark my own company/studio name? If so, where do i do this and does it cost money? Or can i just simply start using a name as is?
2. Do i need to also do this for any games/apps IP i make? Or is copyright automatically assumed?
3. I gather acting as sole trader is more appropriate at this stage? At what point, if ever, should i consider moving to an actual limited company setup?
4. Is it wise to open a new bank account solely for this business?

I think my plan was simply to: 1. Find a suitable domain name and create website based on my company name - assuming available and different enough from similar competitor names 2. Register as self employed with HRMC 3. Sell my game on app store

And thats it! Is this ok or do i need consider other stuff as well such as the questions above?

Thank you for reading and any advice you have!

# Answer
> 8 votes
The short answer is "it depends" but let me explain.

First off I am not a Lawyer (nor would I want to be) so this is information I found.

## Company Registration

OK Assuming you wish to set up as a sole-trader (which is the comparably lowest start-up cost). You have to consider that the area in which you do your "work" could be charged business rates (kinda like council tax on your house) also you tax assessment has to be handled by yourself. VAT also has to be managed by you.

To register go to Companies House which cost at time of writing £15.00

## Copyright

From intellectual property office suggests that all works will be protected automatically. UK is extremely strict with patents so do not expect to get one of those for your games.

## When to "Upgrade" company

Well you are allowed to hire employees as sole trader and all the usual... I believe however after 35k revenue you start being taxed hard and are advised to change to limited company.

## Bank Account

As a sole trader you are solely liable for all debts your company gets so your personal finances will be affected. That being said simply having a new account makes it easier to manage and track.

*Personally from your question it suggests you as yet to have a product to market then you may wish to put this on hold until you do as it a lot of work to manage and will negate from your time actually developing the products.*

# Answer
> 3 votes
I think you're going about this backwards and possibly haven't done enough research into the feasibility of "going indie". Try this before quitting your job...

* Make a complete game that isn't a low quality tech demo
* Sell it
* See how much you earn
* Keep a log of how long it takes to make
* Figure out how much your time is worth per hour

If it's less than minimum wage, go work at McDonalds instead.

Seriously, "sell it on the AppStore" is not going to fund your future. People moan and begrudge paying 69p for a game that might take you two years to make, and unless your game is something special I bet it already exists for free on the AppStore already.

# Answer
> 1 votes
First of all, all of this information will vary from country to country.

1: To have exclusive rights to that name(in your country) you will need to register your company with the government. While I suppose you could use it without registering your company, it would hold no legal authority. In my country(New Zealand), you do this at the Companies register with a small one time fee. I assume it's the same or very similar in all developed countries.

2: I think copyright is automatic, though at least in the US you can get copyright for your game by applying for it even though it isn't required.

3: I am unsure of the advantages and disadvantages of sole trade vs company, but in my country it seems very simple to set up a company and you only need to do a small amount of extra work each year, somewhere around 30 minutes. I imagine the UK is similar to mine, whereas the US has some whacked-out tax system that might be rather complex to use.

4: If you start a company, I imagine it would be better to have a bank account attached to that instead of having it in your own name, although I am not certain it would matter too much either way early on.

# Answer
> 0 votes
If you live in the UK there's always the Citizen's Advice Bureau whom I believe you can contact with any issues like these and they'll point you in the right direction. I'd also disagree with others in that if you honestly want to make games, go for it, don't quit your job straight away but if you're making enough income off of a game I see no reason why you can't work on that full time.

Sorry I couldn't help out more than that and it seems this question is quite old but if it helps I'm glad to offer it.

---
Tags: legal, business
---


# Question
Title: Technologies and languages for Browser RTS game
I am trying to develop a multiplayer rts game. My question here is: which language is best suited for the server side of that game? My very first choices wolud be lower level languages, such as C++ or Java, but I'm afraid I'll have to pay way more than what I can afford for the hosting of a server app written in said languages. (Can you suggest me a free host for developing (or should I use my home PC?) and a cheap one for the first months of deployment?)

PHP at first seemed ok, but then I realized I needed an idle process running even as no user is connected and no pages are being requested. Although I managed to work around some of the issues related to this problem with AJAX requests, I still feel very limited about what I can do with this language; PLUS, even hosting the server locally with Wamp, I have very limited FPS, and the loop on the client which costantly pools the server does it at very unregular intervals (but this may be fault of the way I wrote the client...). Still, I belive that's not what PHP was meant for.

As regards the client, I'd like my game to be a browsergame, for the sake of semplicity (auto-updates, no dowloads and installations needed, portability), probably written in HTML5 (no complex 3d graphics) or flash, but if I have to fall back to a good old standard app in Java or C++ I guess I'll be fine anyway.

# Answer
If your game is an RTS (and not turn based), you are going to need a server and a client system that are geared towards fast communication.

This makes environments like PHP, and methods like AJAX unsuitable.

PHP because, as you said, it's not meant for this and because you will undoubtedly run into performance issues, and AJAX, because it is designed as a system that generally doesn't care how long it takes to complete a request or to post data, but only cares if the message arrives or not within a long timeout.

To write your game server, you're probably best off with a full blown programming language like JAVA or C++, (fun fact, Java is a high level language).

To keep the communication lightweight and fast, use websockets (though these are TCP, and may still be too slow for you).

Alternatively, you could use UDP by leveraging Flash, using a datagramsocket

If you're going to go down this road, and your home internet connection has some decent bandwidth, you should be fine running the server from your home.
> 1 votes

# Answer
Java and C++ are not a low level language?

Anyway, html5 is not really suited for multiplayer games since not all browsers support tcp sockets in html5. You could use ajax, but most webservers are stateless, so keeping track of statefull 'parts' of the game like a player inventory or player stats would require a lot of database read / writes.

Also, the framerates / javascript loop intervals on clients might differ causing player 1 to update on a different frequency then player 2.

That said, id go for either java or C# to produce the server. I would host it on my own pc or a small home server (using NAT) for development and testing purposes. When you find your game to be well enough you can go with an external server. If you use C# you could use Azure to put the server in the cloud and have extreme and global scaling available.

You could consider using phonegap to port a javascript client to all mobile devices, but i'm not sure how to implement tcp socket connections in this case.

My advice in short:

Don't use html5 or php for the client, make a native app

Use java or C# for the server

Develop on your own computers for as long as you can

Try to get people to like it before putting it on an external server
> 1 votes

# Answer
I've seen several games with 1M+ active users daily that use a Flash front-end and have Ruby on the server side.

Most of these applications have a database in the background and scaling horizontally in that aspect is very important as you'll want to be able to handle a large user base.

I've also seen games running PHP on the serverside, it won't matter as much what you use. Get it running first and optimize later. Hopefully by then you'll be making money and you'll be able to scale properly so the server-side code of things won't matter.

**UPDATE:**

Additionally with PHP, should your code ever become a bottleneck you can use hip-hop that will translate the code into C++.
> -2 votes

---
Tags: server, browser-based-games, rts
---


# Question
Title: Spell design and comunication with Player
Im trying to design Spell class that can modify almost anything, Player, Units, other spells, etc. I figured out two ways of doing it, but none of this seems proper for me. Thats mainly because of Player class that got a lot of parameters and setting spell is a bit troublesome.

First is:

Spell interface that Im adding to each class of spell, which have method: execute.

Pros:

* dont have to pass a lot of parameters, just call proper function of target class of a spell
* To use spell just pick spell Player.GetSpell("Fireball").Execute(targets)
* Big flexibility

Cons:

* A LOT OF CLASSES, like 30 or more. One for each spell type
* Each spell need to be wrote manually

Creating spell

```
class Fireball : SpellBase, ISpell
{
    public void Execute(Player caster, List<Object> target)
    {
        caster.Mana -= ManaCost;

        foreach (var o in target)
        {
            if (o.GetType() == typeof(Player))
            {
                var p = (Player)o;
                p.Health -= 10;
                Console.WriteLine("Player: {0} recieved 10 dmg, now has {1}",
                    p.Name, p.Health);
            }
            else if (o.GetType() == typeof(Spell))
            {
                var s = (Spell)o;
                s.Cooldown += 1;
                Console.WriteLine("Unit: {0} recieved 10 dmg, now has {1}",
                    s.Name, s.Health);
            }
        }
    }
}

```

Construction

```
spells.Add(new Fireball());

```

Executing

```
spells.First().Execute(caster, enemy);

```

---

Second approach:

Write one or few classes that can have different functionality depending on parameters set in constructor.

Pros:

* few classes
* loading parameters from file or data base

Cons:

* setting a lot of parameters for different classes(spells and player really dont have much common fields)
* One gigantic method, to handle spell execution

Creating spell

```
class Spell:SpellBase
    {
        public SpellData Data { get; set; }

        public Spell(SpellData param)
        {
            Data = param;
        }
    }

```

Construction

```
 spells.Add(new Frostball(params));
                {
                    HealthMod = -10
                });

```

Executing

```
public void CastSpell(Player caster, List<Object> enemy)
        {
            Caster.Mana -= ManaCost;

            foreach (var o in enemy)
            {
                if (o.GetType() == typeof(Player))
                {
                    var p = (Player)o;
                    p.Health += spell.Data.HealthMod;
                    //p.Defence += spell.Data.DefenceMod;
                    //and a lot of atributes and dependencies
                    //.
                    //.
                    //..........
                }
                else if (o.GetType() == typeof(Spell))
                {
                    var s = (Unit)o;
                    s.Cooldown += spell.Data.CooldownMod;
                    //s.Defence += spell.Data.DefenceMod;
                    //and a lot of atributes
                    //.
                    //.
                    //..........
                }
            }
        }

```

So... I need flexibility a lot. Im not saying its not possible to make it with second way but it will make one big Method with a lot of ifs, which I want to avoid, and i know that with time complexity of this will overwhelm me. Also setting parameters of all spells easily from DB would be nice.

Which one approach do you suggest? Maybe change sth or even you have ideas for whole different way of doing this? Please help me :)

Designin's hard... Sorry for english.

# Answer
> 3 votes
I'd like to preface by saying that you can make things less complicated but you cannot eliminate complexity. If you have N distinct types of spells, then somewhere in your code there has to be N functions (or one giant function with N parts, but that's hard to read). In this sense, your two approaches are more or less equally complicated, so it's not too big of a deal.

What your examples show however is the Open/Closed Principle: your class design should be **open for extension** but **closed for modification**. What this means is that, when you want to add new stuff, you should be able to just add new code, and modify existing code as little as possible. This both makes it easy to extend functionality, and hard to break existing functionality.

In this sense **the first approach is better**. With the first approach, adding a new spell is done by creating a new class, which is isolated from the existing classes, minimising the chance that you'll accidentally break existing code. With the second approach, you'll need to modify the `CastSpell` function, which contains code relating to all the other spells, increasing the chance of accidentally breaking something.

Having said that, your examples are not fully clear-cut, and there are a few other issues:

* A lot of classes is better than a big function that does a lot of things, but you can use multiple classes or functions with your second approach too
* Loading parameters is not dependent on approaches; you can parameterise different spells with the first approach too

# Answer
> 1 votes
I would definately go for option 1.

Why:

You could load all the different spells from an xml file / database procedurally. This would need to be a list with spell names, possible targets, damage / heal, cast time etc.

You will only have to write the logic only once using inheritance like:

determining if you can actually target the passed parameter targets with this spell, check the mana cost, check the player level starting the render loop, calculating the position in the world, taking hp from the enemy player etc. So I think this means you do not have to write each spell manually, just the class. (If you use C# you can use .tt files to generate lots of classes autimaticly. Maybe java has an equivalent?)

You can combine / chain spells and effects this way. You can execute spell B when spell A is done. for example, when fireball (spell A) hits an enemy, next, set him on fire (spell B).

You can use these spells also in combination with applied effects, like poison, fatigue, etc.

When you have ingame items like scrolls and weapons you can link the spell execution to the use of this weapon. This will separate all the logic nicely.

Having constructors with lots of parameters can get quite confusing.

---
Tags: game-design, data-structure
---


# Question
Title: How can I implement a "Nyan Cat" rainbow?
I'm currently making a game similar to this Nyan Cat flash game, although I'm using cocos2d. I'm having a hard time trying to make the rainbow effect:

Currently, every update call I add a piece of rainbow on screen and move it back, having also added it into a special array. When a player changes its `y` coordinate I rotate all the added spites by a certain calculated value.

Honestly, it looks... not perfect and I've been wondering if there is better way?

# Answer
There's a special class available in cocos2d that renders a ribbon of quads for you. At one point it was named `CCRibbon`, but I think it has been changed to `CCMotionStreak` (docs). It's designed to render trails or ribbons. I think using that class would be the most efficient way to create such an effect.
> 3 votes

---
Tags: cocos2d-iphone, objective-c, arcade
---


# Question
Title: Including files in an application using XNA
I'm making a game and I need to load some text files to create levels. After much frustration in trying to get them to work I placed the files in the debug folder of my project (I think this is a bad idea but I didn't really know how else to get the `StreamReader` to work).

The problem is that this means I can't get the project to run when I publish it because I don't know what to do with the text files. Where have I gone wrong and what can I do about it?

# Answer
> 3 votes
I can't verfiy this right now (no XNA installed), but I'm pretty sure the following should work:

* Add the text file to your project.
* Open the file's properties (within VS) and set the following values:
    + **Build Action:** `Content`
    + **Copy to Output Directory:** `Copy if newer` (or `Copy always`)

Then open the project properties, select the "Publish" tab and click on "Application Files...". In the new window you should see your text file being listed and you're able to change it's group or status (default one should be fine).

# Answer
> 1 votes
The StreamReader looks for the file in the current folder (if you just start your App it will be the folder of your ".exe") and in all `$path$` folders (e.g. in the Window folder). If you open a CMD window and enter `echo %path%`, you will see all of the valid paths.

To access your file at runtime you have to follow the following steps:

1) Get the Application-Path

```
System.Sting path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)

```

2) Add "\\" to the end

```
if (String.Compare(path.substr(path.lengh-1, 1), "\\") != 0)
{
    path = path + "\\";
}

```

3) Open file relative to the path:

```
FileStream fileStream = new FileStream(path + "data\\level.txt", FileMode.Open);

```

---

If your folder structure looks like this:

```
\bin\game.exe <- your program
\data\level.txt
\data\leve2.txt
\data\leve3.txt

```

Then you need to go up a folder level, so use use '..'

```
FileStream fileStream = new FileStream(path + "..\\data\\level.txt", FileMode.Open);

```

---
Tags: xna, c#, .net, deployment, build-process
---


# Question
Title: How can I position sprites in a Component-Entity engine?
I'm building my first component/entity engine and I'm not so sure about some of my choices. I'm here asking suggestions on my first doubt.

I draw objects with 2 different behaviours:

1. Position driven by Physics.
2. Position defined by other logics.

At the moment I've only built the first kind of object adding to some entities a `Render component` (which contains information about the sprite to draw) and a `Physic component` which contains body information. The `Rendering system` just attaches `Render components sprites` to the main view and the `Physic System` takes each entity that owns a `Physic component` and defines the sprite position for each entity.

**Question 1)**

Is it a valid choice to access (and modify) Sprites positions directly through the Physic System?

**Question 2)**

For the second type of object, should I manage the sprite position using a third component which is responsible only for that?

Is it a valid solution or I'm totally wrong?

I'm a bit confused about how to manage logic and positions with this kind of system... It seems a bit overwhelming to create a component for every behaviour that I need to define.

# Answer
Unity does this by having 3rd separate component, called Transform3D - which contains position.

So then you can have Physics system, that can use physics components (like Collider) and positon component (Transform3D). Physics system then does physics simulation using physics componets and position component and then update position component accordingly.

And Rendering system, that will use renderer component (like Model, or in your case Sprite). Rendering system then renders all renderer components where position component tells you.
> 1 votes

---
Tags: architecture, entity-system
---


# Question
Title: Is there a name for this kind of composited sprite animation technique?
Character avatars composed of different sprites for each component (arms, legs, head) connected together through a series of joints seem to be trending lately. For example, Scrolls, Candy Crush (in the cutscenes) and the iOS Agricola game.

This system allows the characters to have movements without having to author each frame on a sprite and can look much smoother.

For example, see how the characters seem to breathe in this video? I've checked the game files, they are indeed composed of static parts, linked together through some kind of skeleton.

What is this technique called?

# Answer
> 4 votes
You've pretty much already hit on the terms. What you're describing is just a variation on skeletal animation, constrained to 2D.

This allows a "skeleton" to be defined onto which various sprites representing individual body parts can be mapped and then transformed via translation, rotation or scaling manipulations (the last is probably how you'd implement the 'breathing' appearance).

An animation is represented as a series of transforms to particular bones of the skeleton, which are mapped at runtime to translations on the actual sprites being used to create the character composite.

You can search this site for questions about 2D skeletal animation for more details.

---
Tags: animation, sprites, terminology
---


# Question
Title: Pathfinding with 2D, non-grid based movement over uniform terrain
I'm looking for the best solution to pathfinding in my game. The map is ultimately grid-based, but entities are positioned using floats, and can move in any direction to any point on the map. The 'ground' in my game has a uniform movement cost, but of course there can be obstacles that block the way. The majority of obstacles will be static, and although there will be other animate entities in the game, I *may* get away with not considering them - it's an isometric *Theme Hospital* style strategy game, so no fighting.

Most of the path-finding articles I've seen cover 3D or grid-based 2D movement. Any suggestions for something that might cover my use-case? Many thanks.

# Answer
> 16 votes
This is called the "any-angle pathfinding problem." You basically have two choices:

1. Generate a navigation mesh for your map and search over that using A\*
2. Search over a grid using an algorithm meant specifically for any-angle pathfinding. Traditionally, the way to do this was A\* + path-smoothing *(linear interpolation, etc)*, but these days a more popular alternative is Theta\*, which is easier to implement, runs faster, and produces better results than path-smoothing.

All of the above methods generate *near* optimal results. If for some reason you **need** optimal results, this paper was released a few weeks ago. I haven't had a chance to read it yet, though, so I don't know how efficient it is, or how difficult it is to implement.

---
Tags: 2d, path-finding
---


# Question
Title: Preventing tunneling of small, fast objects
I'm making a basic shooter game with my friend and i have encountered a problem. I kind of know solution this but i just cant implement it. This is my first game made with XNA/MonoGame and i'm not too good with c# either. So my problem is collision detection between bullets and enemies. Sometimes bullets go trough enemies and sometimes they hit. Problem seems to be in my collision detection code because it only detects one item in my array list. This (sweep test) might be the solution as someone suggested but it looks too complicated for me. This might be so simple to fix but like i said i just cant figure out how to do it. I'll post my code and hope that someone can help. Thanks!

This is my main class where it should remove killed enemies:

```
                    foreach (enemy enem in enemies)
                    {

                        enem.Update(graphics.GraphicsDevice);

                    }

                    LoadEnemies();

                    foreach (bullet bull in bullets)
                    {

                        bull.Update();

                    }

                    //WSAD movement

                    if (Keyboard.GetState().IsKeyDown(Keys.D))
                    {
                        charRect.X += 6;
                    }

                    if (Keyboard.GetState().IsKeyDown(Keys.A))
                    {
                        charRect.X -= 6;
                    }

                    if (Keyboard.GetState().IsKeyDown(Keys.W))
                    {
                        charRect.Y -= 6;
                    }

                    if (Keyboard.GetState().IsKeyDown(Keys.S))
                    {
                        charRect.Y += 6;
                    }

                    if (Keyboard.GetState().IsKeyDown(Keys.Space))
                    {
                        LoadBullets();
                    }

                    //Screen collision detection

                    if (charRect.X <= -41)
                    {
                        charRect.X = -41;
                    }

                    if (charRect.Y <= 0)
                    {
                        charRect.Y = 0;
                    }

                    if (charRect.Y >= 400)
                    {
                        charRect.Y = 400;
                    }

                    if (charRect.X >= 632)
                    {
                        charRect.X = 632;
                    }

                    base.Update(gameTime);

                    break;

                }

            case State.Menu:
                {

                    playButton = new button(Content.Load<Texture2D>("playButton"), new Vector2(100, 100));

                    playButton.Update();

                    break;

                }

            case State.GameOver:
                {

                    break;

                }

            }

        }

    public void LoadEnemies()
    {

        if (enemySpawnInterval >= 1)
        {

            enemySpawnInterval = 0;

            if (enemies.Count < 4)
            {

                int randY = r.Next(1, 600);

                enemies.Add(new enemy(Content.Load<Texture2D>("enemyChar"), new Vector2(800, randY)));

            }

        }

        for (int i = 0; i < enemies.Count; i++)
        {

            if (!enemies[i].isOnScreen)
            {

                enemies.RemoveAt(i);
                i--;

            }

            if (enemies[i].enemyIsHit)
            {

                enemies.RemoveAt(i);
                enemyKilled.Play();
                i--;

            }

        }

    }

```

This is place where i spawn bullets and enemies:

```
    Texture2D enemyChar;
    Vector2 position;

    public static Rectangle enemyBox;

    public Boolean enemyIsHit = false;
    public Boolean isOnScreen = true;

    public enemy(Texture2D newEnemyChar, Vector2 newPos)
    {

        enemyChar = newEnemyChar;
        position = newPos;

    }

    public void Update(GraphicsDevice graphics)
    {

        enemyBox = new Rectangle((int)position.X, (int)position.Y, enemyChar.Width, enemyChar.Height);

        if (enemyBox.Intersects(bullet.bulletBox))
        {

            enemyIsHit = true;

        }

        if (position.Y <= 0 || position.Y >= graphics.Viewport.Height - enemyChar.Height)
        {

            position.Y = 100;

        }

        if (position.X < -80)
        {

            isOnScreen = false;

        }

        position.X -= 5;

    }

```

# Answer
You just need a double loop, something like (in pseudocode):

```
for each enemy{
    for each bullet{
        if bullet intersect enemy{
            //handle hit
        }
    }
}

```

Edit: Pseudocode for gradually moving bullets during collision detection, goes in place of moving bullets anywhere else:

```
for each bullet{
    loop 10 times{
        move bullet 1/10 of original speed
        for each enemy{
            if bullet intersect enemy{
                //handle hit
            }
        }
    }
}

```
> 1 votes

# Answer
It may be possible to treat your objects as singular points rather than polygons. By doing this you can draw a line between an objects last position and its current position and then do a line intersection check to see if they have passed through each other.

Eg.

Your enemy is at (0,0) and moves to (10,10) in 1 time step. Your Bullet is at (10,0) and moves to (0,10) in 1 time step.

create a line for the enemy from (0,0) to (10,10) and one for the bullet from (10,0) to (0,10)

if you do this on a piece of graph paper it is easy to see that they intersect. But how do we get our program to do that. I have found a very nice tutorial and code example at `Third Party Ninjas` that shows just that.

Check out the post: http://thirdpartyninjas.com/blog/2008/10/07/line-segment-intersection/

specifically the `processIntersection()` method in the `Game1.cs` file.
> 0 votes

# Answer
Why not use ray casting? If your bullets are moving too fast to be detected normally during your update you can check to see if there is something between their last location and current location. While this example may be a bit much to digest if you are not very familiar with C# it does include the source code which you can walk yourself through.

http://www.codeproject.com/Articles/15604/Ray-casting-in-a-2D-tile-based-environment
> 0 votes

---
Tags: c#, collision-detection
---