title: How to design a replay system

text:
# Question
Title: How to design a replay system
So how would I design a replay system?

You may know it from certain games like Warcraft 3 or Starcraft where you can watch the game again after it has been played already.

You end up with a relatively small replay file. So my questions are:

* How to save the data? (custom format?) (small filesize)
* What shall be saved?
* How to make it generic so it can be used in other games to record a time period (and not a complete match for example)?
* Make it possible to forward and rewind (WC3 couldn't rewind as far as I remember)

# Answer
> 40 votes
This excellent article covers a lot of the issues.

A few things that the article mentions and does well:

* your game has to be deterministic.
* it records the initial state of the game systems on the first frame, and only the player input during gameplay.
* quantize inputs to lower # of bits. Ie. represent floats within various ranges (eg. \[0, 1\] or \[-1 , 1\] range within less bits. Quantized inputs have to be obtained during actual game play too.
* use a single bit to determine whether an input stream has new data. Since some streams won't change frequently, this exploits temporal coherence in the inputs.

One way to further improve the compression ratio for the majority of cases would be to decouple all your input streams and fully run-length encode them independently. This will be a win over the delta encoding technique if you encode your run in 8-bits and the run itself exceeds 8 frames (very likely unless your game is a real button masher). I've used this technique in a racing game to compress 8 minutes of inputs from 2 players while racing around a track down to just a few hundred bytes.

In terms of making such a system reusable, I've made the replay system deal with generic input streams, but also providing hooks to allow the game specific logic to marshal keyboard/gamepad/mouse input to these streams.

If you want fast rewinding or random seeks, you can save a checkpoint (your full gamestate) every N frames. N should be chosen to minimize the replay file size and also make sure the time that the player has to wait is reasonable while the state is replayed to the chosen point. One way to get around this is to ensure that random seeks can only be made to these exact checkpoint locations. Rewinding is a matter of setting the game state to the checkpoint immediately before the frame in question, then replaying the inputs until you get to the current frame. However, if N is too large, you could get hitching every few frames. One way to smooth these hitches is to asynchronously pre-cache the frames between the previous 2 checkpoints while you're playing back a cached frame from the current checkpoint region.

# Answer
> 24 votes
You can view your system as if it were composed of a series of states and functions, where a function `f[j]` with input `x[j]` changes the system state `s[j]` into state `s[j+1]`, like so:

```
s[j+1] = f[j](s[j], x[j])

```

A state is the explanation of your entire world. The locations of the player, the location of the enemy, the score, the remaining ammo, etc. Everything you require to draw a frame of your game.

A function is anything that may effect the world. A frame change, a keypress, a network packet.

The input is the data the function takes. A frame change may take the amount of time since the last frame passed, the keypress may include the actual key pressed, as well as whether or not the shift key was pressed.

For the sake of this explanation, I will make the following assumptions:

**Assumption 1:**

The amount of states for a given run of the game is much larger than the amount of functions. You probably have hundreds of thousands of states, but only a several dozen functions (frame change, keypress, network packet, etc). Of course, the amount of inputs must be equal to the amount of states minus one.

**Assumption 2:**

The spacial cost (memory, disk) of storing a single state is much greater that that of storing a function and its input.

**Assumption 3:**

The temporal cost (time) of presenting a state is similar, or just one or two orders of magnitude longer than that of calculating a function over a state.

Depending on the requirements of your replay system, there are several ways to implement a replay system, so we can start with the simplest one. I'll also make a small example using the game of chess, recorded on pieces of paper.

**Method 1:**

Store `s[0]...s[n]`. This is very simple, very straightforward. Because of assumption 2, the spacial cost of this is quite high.

For chess, this would be accomplished by drawing the entire board for each move.

**Method 2:**

If you only need forward replay, you can simply store `s[0]`, and then store `f[0]...f[n-1]` (remember, this is only the name of id of the function) and `x[0]...x[n-1]` (what was the input for each of these functions). To replay, you simply start with `s[0]`, and calculate

```
s[1] = f[0](s[0], x[0])
s[2] = f[1](s[1], x[1])

```

and so on...

I want to make a small annotation here. Several other commenters said that the game "must be deterministic". Anyone who says that needs to take Computer Science 101 again, because unless your game is meant to be run on quantum computers, ALL COMPUTER PROGRAMS ARE DETERMINISTIC¹. That's what makes computers so awesome.

However, since your program most likely depends on external programs, ranging from libraries to the actual implementation of the CPU, making sure that your functions behave the same between platforms may be quite difficult.

If you use pseudo-random numbers, you can either store the generated numbers as part of your input `x`, or store the state of the prng function as part of your state `s`, and its implementation as part of function `f`.

For chess, this would be accomplished by drawing the initial board (which is known) and then describe each move saying which piece went where. This is how they actually do it, by the way.

**Method 3:**

Now, you most likely want to be able to seek into your replay. That is, calculate `s[n]` for an arbitrary `n`. By using method 2, you need to calculate `s[0]...s[n-1]` before you can calculate `s[n]`, which, according to assumption 2, may be quite slow.

To implement this, method 3 is a generalization of methods 1 and 2: store `f[0]...f[n-1]` and `x[0]...x[n-1]` just like method 2, but also store `s[j]`, for all `j % Q == 0` for a given constant `Q`. In easier terms, this means that you store a bookmark at one out of every `Q` states. For example, for `Q == 100`, you store `s[0], s[100], s[200]...`

In order to calculate `s[n]` for an arbitrary `n`, you first load the previously stored `s[floor(n/Q)]`, and then calculate all the functions from `floor(n/Q)` to `n`. At most, you will be calculating `Q` functions. Smaller values of `Q` are faster to calculate but consume much more space, while larger values of `Q` consume less space, but take longer to calculate.

Method 3 with `Q==1` is the same as method 1, while method 3 with `Q==inf` is the same as method 2.

For chess, this would be accomplished by drawing every move, as well as one in every 10 boards (for `Q==10`).

**Method 4:**

If you want to reverse replay, you can make a small variation of method 3. Suppose `Q==100`, and you want to calculate `s[150]` through `s[90]` in reverse. With the unmodified method 3, you will need to make 50 calculations to get `s[150]` and then 49 more calculations to get `s[149]` and so on. But since you already calculated `s[149]` to get `s[150]`, you can create a cache with `s[100]...s[150]` when you calculate `s[150]` for the first time, and then you already `s[149]` in the cache when you need to display it.

You only need to regenerate the cache each time you need to calculate `s[j]`, for `j==(k*Q)-1` for any given `k`. This time, increasing `Q` will result in smaller size (just for the cache), but longer times (just for recreating the cache). An optimal value for `Q` can be calculated if you know the sizes and times required to calculate states and functions.

For chess, this would be accomplished by drawing every move, as well as one in every 10 boards (for `Q==10`), but also, it would require to draw in a separate piece of paper, the last 10 boards you have calculated.

**Method 5:**

If states simply consume too much space, or functions consume too much time, you can create a solution that actually implements (not fakes) reverse replaying. To do this, you must create reverse functions for each of the functions you have. However, this requires that each of your functions is an injection. If this is doable, then for `f'` denoting the inverse of function `f`, calculating `s[j-1]` is as simple as

```
s[j-1] = f'[j-1](s[j], x[j-1])

```

Note that in here, the function and input are both `j-1`, not `j`. This same function and input would be the ones you would have used if you were calculating

```
s[j] = f[j-1](s[j-1], x[j-1])

```

Creating the inverse of these functions is the tricky part. However, you usually can't, since some state data is usually lost after each function in a game.

This method, as is, can reverse calculate `s[j-1]`, but only if you have `s[j]`. This means that you can only watch the replay backwards, starting from the point at which you decided to replay backwards. If you want to replay backwards from an arbitrary point, you must mix this with method 4.

For chess, this cannot be implemented, since with a given board and the previous move, you can know which piece was moved, but not where it moved from.

**Method 6:**

Finally, if you can't guarantee all your functions are injections, you can make a small trick to do so. Instead of having each function return only a new, state, you can also have it return the data it discarded, like so:

```
s[j+1], r[j] = f[j](s[j], x[j])

```

Where `r[j]` is the discarded data. And then create your inverse functions so they take the discarded data, like so:

```
s[j] = f'[j](s[j+1], x[j], r[j])

```

In addition of `f[j]` and `x[j]`, you must also store `r[j]` for each function. Once again, if you want to be able to seek, you must store bookmarks, such as with method 4.

For chess, this would be the same as method 2, but unlike method 2, which only says which piece goes where, you also need to store where did each piece came from.

**Implementation:**

Since this works for all kinds of states, with all kinds of functions, for a specific game, you can make several assumptions, that will make it easier to implement. Actually, if you implement method 6 with the entire game state, not only you will be able to replay the data, but also go back in time and resume playing from any given moment. That would be pretty awesome.

Instead of storing all the game state, you can simply store the bare minimum that you require to draw a given state, and serialize this data every fixed amount of time. Your states will be these serializations, and your input will now be the difference between two serializations. They key for this to work is that the serialization should change little if the world state changes little as well. This difference is completely inversible, so implementing method 5 with bookmarks is very possible.

I've seen this implemented in some major games, mostly for instant replaying of recent data when an event (a frag in fps, or a score in sports games) occurs.

I hope this explanation wasn't too boring.

¹ This doesn't mean some programs act like they were non-deterministic (such as MS Windows ^^). Now seriously, if you can make a non-deterministic program on a deterministic computer, you can be pretty sure you will simultaneously win the Fields medal, Turing award and probably even an Oscar and Grammy for all that's worth.

# Answer
> 23 votes
Besides the "make sure the keystrokes are replayable" solution, which can be surprisingly difficult, you could just record the entire game state on every frame. With a little clever compression you can squeeze it down significantly. This is how Braid handles its time-rewinding code and it works pretty well.

Since you'll need checkpointing anyway for rewinding, you might want to just try implementing it the simple way before complicating things.

# Answer
> 10 votes
One thing that other answers have not covered yet are the danger of floats. You can't make a fully deterministic application using floats.

Using floats, you can have a completely deterministic system, but only if:

* Using the exactly same binary
* Using the exactly same CPU

This is because the internal representation of floats varies from one CPU to another - most dramatically between AMD and intel CPUs. As long as the values are in FPU registers, they're more accurate than they look like from C side, so any intermediate calculations are done in higher precision.

It's quite obvious how this will affect the AMD vs intel bit - let's say one uses 80 bit floats and the other 64, for example - but why the same binary requirement?

As I said, the higher precision is in use *as long as the values are in FPU registers*. This means that whenever you recompile, your compiler optimization may swap values in and out of FPU registers, resulting in subtly different results.

You may be able to help this by setting \_control87()/\_controlfp() flags to use the lowest possible precision. However, some libraries may also touch this (at least some version of d3d did).

# Answer
> 8 votes
Save the initial state of your random number generators. Then save, timestamped, each input (mouse, keyboard, network, whatever). If you have a networked game you probably already have this all in place.

Re-set the RNGs and play back the input. That's it.

This doesn't solve re-winding, for which there is no general solution, other than playing back from the start as fast as you can. You can improve performance for this by checkpointing the entire game state every X seconds, then you'll only ever need to replay that many, but the entire game state might also be prohibitively expensive to grab.

The particulars of the file format don't matter, but most engines have a way to serialize commands and state already - for networking, saving, or whatever. Just use that.

# Answer
> 4 votes
I'd vote against deterministic replaying. It's FAR simpler and FAR less error-prone to save the state of every entity every 1/Nth of a second.

Save just what you want to show on playback - if it's just position and heading, fine, if you also want to show stats save that, too, but in general save as little as possible.

Tweak the encoding. Use as few bits as possible for everything. The replay doesn't have to be perfect as long as it looks good enough. Even if you use a float for, say, heading, you can save it in a byte and get 256 possible values (1.4º precision). That may be enough or even too much for your particular problem.

Use delta encoding. Unless your entities teleport (and if they do, treat the case separately), encode positions as the difference between the new position and the old position - for short movements, you can get away with far less bits than you'd need for full positions.

If you want easy rewind, add keyframes (full data, no deltas) every N frames. This way you can get away with lower precision for deltas and other values, rounding errors won't be so problematic if you reset to "true" values periodically.

Finally, gzip the whole thing :)

# Answer
> 2 votes
I'm somewhat surprised that nobody's mentioned this option, but if your game has a multiplayer component, you may have already done a lot of the hard work necessary for this feature. After all, what's multiplayer but an attempt to re-play the movements of someone else at a (slightly) different time on your own computer?

This also gets you the benefits of a smaller file size as a side effect, again assuming you've been working on bandwidth-friendly network code.

In many ways, it combines both the "be extremely deterministic" and "keep a record of everything" options. You'll still need determinism - if your re-play is essentially bots playing the game again in exactly the way you originally played it, whatever actions they take that can have random outcomes need to have the same outcome.

The data format could be as simple as a dump of the network traffic, though I imagine it wouldn't hurt to clean it up a bit (you don't have to worry about lag on a re-play, after all). You could re-play only a portion of the game by using the checkpoint mechanism other people have mentioned - typically a multiplayer game will send out a full state of the game update every so often anyway, so again you may have already done this work.

# Answer
> 1 votes
Its hard. First and most of all read Jari Komppa answers.

A replay made on my computer may not work on your computer because the float result is SLIGHTLY different. Its a big deal.

But after that, if you have random numbers is to store the seed value in the replay. Then load all default states and set the random number to that seed. From there you could simply record the current key/mouse state and the length of time its been that way. Then run all events using that as input.

To jump around files (which is much harder) you'll need to dump THE MEMORY. Like, where every unit is, money, length of time passes, all of the game state. Then fast forwarding but replaying everything but skipping rendering, sound etc until you get to the time destination you want. This could happen every minute or 5mins depending how fast it is to forward.

Main points are \- Dealing with random numbers \- Copying input (player(s), and remote player(s)) \- Dumping state for jumping around files and... \- HAVING FLOAT NOT BREAK THINGS (yes, i had to yell)

# Answer
> 0 votes
To get the smallest possible replay file you'll need make sure your game is deterministic. Usually this involves looking at your random number generator and seeing where it is used in the game logic.

You'll most likely need to have a game logic RNG and an everything else RNG for things like GUI, particle effects, sounds. Once you have this done, you need record the initial state of the game logic RNG, then the game commands of all the players every frame.

For many games there is a level of abstraction between the input and the game logic where the input is turned into commands. For example pressing the A button on the controller results in a "jump" digital command being set to true and the game logic reacts to commands without checking the controller directly. By doing this, you'll only need to record the commands which impact the game logic (no need to record the "Pause" command) and most likely this data will be smaller than recording the controller data. You also don't have to worry about recording the state of the control scheme in case the player decided to remap buttons.

Rewinding is a difficult problem using the deterministic method and other than using snapshot of the game state and fast-forwarding to the point in time you want to look at there is not much you can do other than recording the entire game state each frame.

On the otherhand, fast-forwarding is certainly doable. As long as your game logic isn't reliant on your rendering, you can run the game logic as many times as you want prior to rendering a new frame of the game. The speed of fast-forwarding will just be bound by your machine. If you want to skip ahead in large increments, you'll need to use the same snapshot method as you would need for rewinding.

Possibly the single most important part of writing a replay system that relies on determinism is to record a debug stream of data. This debug stream contains a snapshot of as much information as possible each frame (RNG seeds, entity transforms, animations, etc) and be able to test that recorded debug stream against the state of the game during the replays. This will allow you to quickly let you know mismatches at the end of any given frame. This will save countless hours of wanting to pull your hair out from unknown non-deterministic bugs. Something as simple as an uninitialized variable will mess everything up at the 11th hour.

NOTE: If your game involves dynamic streaming of content or you have game-logic on multiple threads or on different cores... good luck.

# Answer
> 0 votes
To enable both recording and rewinding, record all events (user generated, timer generated, communication generated, ...).
For each event record time of event, what was changed, previous values, new values.

Calculated values do not need to be recorded unless calculating is random
(In these cases you can either record calculated values too, or record changes to seed after each random calculation).

Data saved is a list of changes.
Changes can be saved in various formats (binary, xml, ...).
Change consists of entity id, property name, old value, new value.

Make sure your system can play back these changes (access desired entity, changed desired property forward to new state or backward to old state).

Example:

- time from start = t1, entity = player 1, property = position, changed from a to b
- time from start = t1, entity = system, property = game mode, changed from c to d
- time from start = t2, entity = player 2, property = state, changed from e to f

To enable faster rewinding/fastforwarding or recording only certain time ranges,
key frames are necessary - if recording all the time, every now and then save entire game state.
If recording only a certain time ranges, at the beginning save the initial state.

# Answer
> -3 votes
If you need ideas on how to implement your replay system, search google for how to implement *undo/redo* in an application. It may be obvious to some, but maybe not to all, that undo/redo is conceptually the same as replaying for games. It is just a special case in which you can rewind, and depending on the application, seek to a specific point in time.

You'll see that nobody implementing undo/redo complains about deterministic/non-deterministic, float variables, or specific CPUs.

---
Tags: architecture, data-structure, file-format, game-recording
---


# Question
Title: Game Object Factory: Fixing Memory Leaks
Dear all, this is going to be tough: I have created a game object factory that generates objects of my wish. However, I get memory leaks which I can not fix.

Memory leaks are generated by **return new Object();** in the bottom part of the code sample.

```
static BaseObject * CreateObjectFunc()
{
    return new Object();
}

```

How and where to delete the pointers? I wrote **bool ReleaseClassType()**. Despite the factory works well, ReleaseClassType() does not fix memory leaks.

```
bool ReleaseClassTypes()
{
    unsigned int nRecordCount = vFactories.size();
    for (unsigned int nLoop = 0; nLoop < nRecordCount; nLoop++ )
    {
        // if the object exists in the container and is valid, then render it
        if( vFactories[nLoop] != NULL)
            delete vFactories[nLoop]();
    }
    return true;
}

```

Before taking a look at the code below, let me help you in that my CGameObjectFactory creates **pointers to functions** creating particular object type. The pointers are stored within vFactories vector container.

I have chosen this way because I parse an object map file. I have object type IDs (integer values) which I need to translate them into real objects. Because I have over 100 different object data types, I wished to avoid continuously traversing very long Switch() statement.

Therefore, to create an object, I call **vFactoriesnEnumObjectTypeID** via CGameObjectFactory::create() to call stored function that generates desired object.

The position of the appropriate function in the vFactories is identical to the nObjectTypeID, so I can use indexing to access the function.

So the question remains, **how to proceed with garbage collection and avoid reported memory leaks?**

```
#ifndef GAMEOBJECTFACTORY_H_UNIPIXELS
#define GAMEOBJECTFACTORY_H_UNIPIXELS

//#include "MemoryManager.h"
#include <vector>

template <typename BaseObject>
class CGameObjectFactory
{
public:
    // cleanup and release registered object data types
    bool ReleaseClassTypes()
    {
        unsigned int nRecordCount = vFactories.size();
        for (unsigned int nLoop = 0; nLoop < nRecordCount; nLoop++ )
        {
            // if the object exists in the container and is valid, then render it
            if( vFactories[nLoop] != NULL)
                delete vFactories[nLoop]();
        }
        return true;
    }

    // register new object data type
    template <typename Object>
    bool RegisterClassType(unsigned int nObjectIDParam )
    {
        if(vFactories.size() < nObjectIDParam) vFactories.resize(nObjectIDParam);

        vFactories[nObjectIDParam] = &CreateObjectFunc<Object>;
        return true;
    }

    // create new object by calling the pointer to the appropriate type function
    BaseObject* create(unsigned int nObjectIDParam) const
    {
        return vFactories[nObjectIDParam]();
    }

    // resize the vector array containing pointers to function calls
    bool resize(unsigned int nSizeParam)
    {
        vFactories.resize(nSizeParam);
        return true;
    }

private:
    //DECLARE_HEAP;

    template <typename Object>
    static BaseObject * CreateObjectFunc()
    {
        return new Object();
    }

    typedef BaseObject*(*factory)();
    std::vector<factory> vFactories;
};

//DEFINE_HEAP_T(CGameObjectFactory, "Game Object Factory");

#endif // GAMEOBJECTFACTORY_H_UNIPIXELS

```

# Answer
You can't clean up from inside the Factory class. It's the job of whatever code called `create()` to deallocate that memory later. The "cleanup" you've done just allocates and then destroys a new object of each type.
> 4 votes

---
Tags: c++
---


# Question
Title: When should a bullet texture be loaded in XNA?
I'm making a SpaceWar!-esque game using XNA. I want to limit my ships to 5 active bullets at any time. I have a **Bullet** `DrawableGameComponent` and a **Ship** `DrawableGameComponent`. My **Ship** has an array of 5 **Bullet**.

What is the best way to manage the **Bullet** textures? Specifically, when should I be calling `LoadTexture`? Right now, my solution is to populate the **Bullet** array in the **Ship**'s constructor, with `LoadTexture` being called in the **Bullet** constructor. The **Bullet** objects will be disabled/not visible except when they are active. Does the texture really need to be loaded once for each individual instance of the bullet object? This seems like a very processor-intensive operation.

Note: This is a small-scale project, so I'm OK with not implementing a huge texture-management framework since there won't be more than half a dozen or so in the entire game. I'd still like to hear about scalable solutions for future applications, though.

# Answer
First of all: how you do it doesn't really matter. Just do the very *simplest thing that could possibly work*. My current favourite way is with **static** methods in each class (ie: bullet, ship), like this:

```
static Texture2D myTexture, myOtherTexture;
// Call me from Game.LoadContent:
public static void LoadContent(ContentManager content) { content.Load /* ...etc */ }

```

(This is perfectly fine for simple games where you only have a single `ContentManager` instance and never call `Unload`.)

Being able to toss in simple systems like this is one reason why I don't think it's a good idea to use `DrawableGameComponent`.

As has been mentioned a couple of times: XNA's `ContentManager` will share instances of loaded content (like textures). So after the first time you load it, subsequent loads will give you back the same texture with no cost for loading.

---

Anyway - it doesn't really matter *how* you load your content. What matters (and what you are asking) is *when?*

The answer to that is simple: **Load your textures when your game starts!** (Or behind loading screens or other the-game-isn't-animating screens if necessary.) If you cannot do this, the correct solution is to load your textures in a worker thread.

When you load a texture (a synchronous operation - it blocks the calling thread), you take a hit pulling the data from disk, a hit to decode it, a hit to send it to the GPU, and a hit if you trigger the garbage collector (blocks all threads, and is especially bad on Xbox 360).

In terms of the game loading, loading a texture is a very fast operation. In terms of the 16ms you have to calculate and render each frame at 60FPS, loading a texture is *agonisingly* slow.

---

Bill, in comments, asked for some resources on `ContentManager`. I am obviously biased, but I think some of my answers (including this one) contain some pretty good information and hint at some best practices:

And one from XNA lead Shawn Hargreaves: If ContentManager doesn't suit your resource-management needs, you should derive from ContentManager and override Load. This way you can implement whatever asset tracking you like, without making ugly custom wrappers.
> 8 votes

# Answer
The simplest texture manager has one function: GetTexture. GetTexture checks its cache for a texture. If the texture isn't cached, it loads the texture. Then it returns the texture. Kapow! Done!

That is sufficient for most small-scale indie games I've seen. You just don't have enough content for this to ever be a problem.

One downside is that this can result in loading hiccups during gameplay. Quick fix: just call GetTexture with all the textures you expect to use during a "loading" section. Another possible fix: when you "load" a texture, hand a functional blank texture handle back, then start loading in the data asynchronously in the background (in another thread or with asynchronous file loading calls) and fill it in once it's done. This way you avoid the load hitches, but things can look a bit weird until textures are filled in. If you want to implement this, I'd recommend a GetTextureAsync function to call when asynchronous loading is acceptable (which in my experience will be only a few places, but those places may account for the majority of the textures in your game.)

Another downside is that you will, eventually, keep all the textures in your game in memory at once. This can also be easy to fix - if your game is divided into levels, just clear the entire cache between levels and reload everything. A somewhat more complex solution is to throw away textures after they've been unused for some number of seconds. This works great for large streaming worlds with unknown resources needed at each point (like MMOs - you never know what armor you're going to see next) but it does mean there's some lag between when a texture is unneeded and when the memory is actually freed.

If you want a more complex texture manager, you can start having formal concepts of blocks of textures that need to be preloaded. Each level can have a texture corpus, and when you change levels, you explicitly throw away the old corpus and load in the new one. Couple this with on-demand loading for unexpected textures, and a delay for deallocating those, and you're pretty much set for quiet some time.

As an example of this, in a game in a large contiguous world you might break the world into areas, then come up with a corpus for each area. Load textures for all adjacent areas to the player while throwing away textures from further away. (With refcounting, of course - if every area uses "grass", then there's no reason to store multiple copies of "grass".)

But meanwhile, back in reality, you'll probably be just fine with GetTexture. :)
> 5 votes

# Answer
If the texture is always the same then you should load the texture once in the game life, for example in the Ship class once it´s LoadContent is called.

\***I´m not sure, but I think XNA loads the texture once, and the other calls to the load method will just use the memory loaded texture. Even if that is true, I think calling that method once is beter.
> 2 votes

---
Tags: textures, xna-4.0, loading, preload, game-component
---


# Question
Title: What would be the level of effort required to implement a screencapture command on a PS3 game?
Looking to see what the level of effort is for implementing a screen capture command into PS3 game by a mid-level PS3 game developer.

Bonus for a description of what is involved in the process...

**EDIT**

Not sure how to get back my question since it was the first but let me clarify some things. @Nate Bross, nope I am not the actor although i've fielded calls for him on occasion

@coderanger my intent was to try and speak to other PS3 developers, however coming from a web development no one in my social circle close or extended develops on the PS3. Additionally i'm interested in hearing the effort required in terms of hours so that this information can be passed on to a client. A client who has a game on the PS3 using the unreal engine. Convo with devs sometimes go something like "can you implement feature a" which gets a response "this will take us 8 weeks and an army". Trying to be educated before the ask. I hope that helps

If anyone here is a PS3 game dev and would like to respond off site so as not to break NDA that would be awesome.

@Roger it would be from within the game, something that users can use. Something akin to the iphone screencap utility. No need to get fancier than that.

# Answer
> 3 votes
Do you want to capture the screenshot from within the game for some purpose, or from a development PC?

From the development PC there are simple facilities provided, you easily use the Target Manager SDK to achieve this (you'll need to read the full description to see what else you need to set up as specifics are NDA'd).

From within the game, the simplest way is to insert something after the frame has been rendered to first flush the GPU (to ensure that everything has finished being rendered before you continue). The game should have a pointer to the current frame buffer somewhere, you'll know the format of that buffer (the stride, etc), you can then do what you want, including writing it out in a format of your own choice with a little work.

# Answer
> 2 votes
As your client is using the Unreal Engine, I recommend looking at the UDN. Here you will find all the information you need relating to implementing features within the Unreal Engine itself. I couldn't tell you exactly what you would need to call though as a good portion of it (any link that is red) is blocked off only to licensed developers.

You will need to make some sort of arrangement with your client for them to let you access their development materials.

# Answer
> 1 votes
The PS3 runs a variant of OpenGL ES (which is the same thing most mobile devices are using), though I don't know of anyone that actually uses OpenGL directly. http://www.bit-101.com/blog/?p=1861 shows how to create a screenshot an an iPhone, I wouldn't expect it to be very different.

---
Tags: playstation3
---


# Question
Title: Using Google App Engine to Perform World Updates vs an Authoritative Server
I am considering different game server architectures that use GAE. The types of games I am considering are turn-based where the world status would need to be updated about once per minute.

I am looking for an answer that persuades me to either perform the world update on the google servers OR an authoritative server that syncs with the datastore. The main goal here would be to minimize GAE daily quotas.

For some rough numbers, I am assuming 10,000 entities requiring updates. Each entity update would require:

* Reading 5 private entity variables (fetched from datastore)
* Fetching as many as 20 static variables (from datastore or persisted in server memory)
* Writing 5 entity variables

Clients of the game would authenticate and set state directly against GAE as well as pull the latest world state from GAE.

Running the update on GAE would consist of a cron job launched every minute. This would update all of the entities and save the results to the datastore. This would be more CPU intensive for GAE.

Running the update on an authoritative server would consist of fetching entity data from the GAE datastore, calculating the new entity states and pushing the new state variables back to the datastore. This would be more bandwidth intensive for the datastore.

# Answer
> 2 votes
From my (limited) experience with GAE, while database reads are trivial, database writes are *expensive*. We've got a database of around 20,000 GAE entities; when measured, writes are taking around 0.3 - 0.5 *billable* seconds. Updating our entire datastore takes ~2.5 billable CPU hours.

It's perfectly possible to use GAE to run an authoritative server, but given the cost, I wouldn't want to -- a cloud-hosted VM server would be more flexible and would likely cost less.

# Answer
> 0 votes
I am new to developing Games and this may sound naive, but somehow having 10,000 entities or more to describe a world sounds like a lot. I would rethink the database and the patterns that place those entities in your world. The Text and Blob datatypes are saved as binary by default although they are retrieved as a string.

---
Tags: mmo, networking, server, databases, google-app-engine
---


title: Android game development in c++

text:
# Question
Title: Android game development in c++
So being a primarily c/c++ developer, I've always thought that the only option for mobile game development for me was using iOS, which allows for c/c++ (and minimising objective C).

I heard from a friend though, that android has a native development toolkit which allows for c++ code to work on android.

Has anyone used this, and if so, how do you find it? I mean, will it "just work" like iOS, or are there more considerations that need to be taken care of due to the wide variety of android devices available?

# Answer
> 25 votes
Android APIs are Java. Since 2010, Google provides the NDK (a SDK) for C/C++ developers.

The NDK offers two ways:

* for android 1.5 devices, you can load an elf library and uses it from the java application via a JNI bridge
* for android 2.3 devices, you can use a NativeActivity to bypass the Java Activity code for Fullscreen Application.

The NDK offers few C/C++ API:

* a pseudo libc called bionics: many functions aren't availabled
* a pthread library
* OpenGL ES 1.x (\>Android 1.5) and OpenGL ES 2.x (Android 2.0)
* OpenSL (limited support on Android 2.3)

But many API are Java only (also available via JNI).

NDK 5 version is the first usable for C++ developers because it offers:

* RTTI
* Exceptions supports
* STLport
* gdb support for multi-threaded programs

The most painful operation is debugging on android devices. So i develop my own multi-platform framework (OS X, Windows, Linux, iOS and Android) to debug first on desktop platform, next iOS platform (on Simulator) and Last (Android).

The android Emulator (not a simulator) have a poor performance and can't emulate OpenGL ES 2.x. I recommend real devices to develop.

You can find many useful informations :

# Answer
> 9 votes
I have successfully used the Android NDK to port two SDL + OpenGL games to Android and found it surprisingly easy. I have a 200-line Java wrapper that creates the GL context and provides utility classes such as input, sound and image loading for the C++ code to call back. The "San-Angeles" sample program in the NDK is an excellent starting point.

By the way, it is possible to build C/C++ programs without a line of Java, but I find it convenient to access some OS-level methods by calling back the JVM from time to time.

I think if your game already compiles on Linux, you will feel at home. Out of 100+ files in my current project, only 4 have an `#ifdef ANDROID_NDK` directive (the image and sound related classes).

In fact most of the time spent porting the game was because of a known emulator bug that I wasn't aware of.

# Answer
> 4 votes
Android has supported native applications since version 1.5 through Android NDK, which should cover your target audience very well. You still need a simple Android Java application that loads the native side of your application through JNI and passes forward e.g. input and render calls.

There has been several versions of the NDK, but you can use the latest NDK and select the target API you want to support. Since Android version 2.3 you can do a lot more on the native side and need less Java code, but the device support for 2.3 is currently very limited.

Native Android C/C++ development is a working solution at least for fullscreen games and the effort needed to port existing C/C++ OpenGL ES applications is quite small.

---
Tags: c++, android
---


# Question
Title: Are there alternatives to ChatBlade similar in features?
ChatBlade is an MMO middleware for handling client side chat in (massively) multiplayer environments. I am looking for a royalty-free, cheaper (\<1k) alternative (C++ or dll preferred) that would do the same before deciding on having to spend time developing an own solution.

Any help is greatly appreciated.

# Answer
Can't you just use XMPP? It's weak for transmiting binary data in-band but you may not need this on an in-game chat.

You can run ejabberd on your server and just embed a jabber client on your game.

There's a list of libraries implementing XMPP here. gloox is a C++ implementation.
> 3 votes

---
Tags: c++, mmo
---


title: How do I import my first sprites?

text:
# Question
Title: How do I import my first sprites?
Continuing from this question (new question - now unrelated)

So I have a thorough background in programming already (algorithms, math, logic, graphing problems, etc.) however I've never attempted to code a game before. In fact, I've never had anything more than minimal input from a user during the execution of a program. Generally input was given from a file or passed through console, all necessary functions were performed, then the program terminated with an output. I decided to try and get in on the world of game development. From several posts I've seen around gamedev.stackexchange.com XNA seems to be a favorite, and it was recommended to me when I asked where to start.

I've downloaded and installed Visual Studio 2010 along with the XNA Framework and now I can't seem to get moving in the right direction.

I started out looking on Google for "xna game studio tutorial", "xna game development beginners", "my first xna game", etc. I found lots of crap. The official "Introduction to Game Studio 4.0" gave me this (plus my own train of thought happily pasted on top thanks to MSPaint):

http://tinypic.com/r/2w1sgvq/7 (broken image)

The "Get Additional Help" link (my best guess, since there was no "Continue" or "Next" link) lead me to this page:

http://tinypic.com/r/2qa0dgx/7 (broken image)

I tried every page. The forum was the only thing that seemed helpful, however searching for "beginner", "newbie", "getting started", "first project", and similar on the forums turned up many threads with specific questions that are a bit above my level ("beginner to collision detection", for instance)

Disappointed I returned to the XNA Game Studio home page. Surely their own website would have some introduction, tutorial, or at least a useful link to a community. EVERYTHING on their website was about coding Windows Phone 7.... Everything.

Giving up on any official documentation after a while, I went back to Google. I managed to locate www.xnadevelopment.com. The website is built around XNA Game Studio 3.0, but how different can 3.0 be from 4.0?.... Apparently different enough.

http://tinypic.com/r/5d8mk9/7 (broken image)

Figuring that this was the correct folder, I right-clicked....

Hmm... maybe by "Add Content Reference" they mean "Add a reference to an existing file (content)"? Let's try it (after all- it's my only option)

At this point I gave up. I'm back. My original goal in my last question was to create a keyboard-navigable 3D world (no physics necessary, no logic or real game necessary). After my recent failures my goal has been revised. I want to display an image on the screen.

Hopefully in time I'll be able to move it with the keyboard.

# Answer
Having created your first XNA game project, you will get two projects created.

> * **`MyFirstGame`**

This project contains:

1. Game.ico;
2. Game1.cs;
3. GameThumbnail.png;
4. Program.cs.

A reference to your content is also available. That is refered to as the content pipeline.

> * **`MyFirstGameContent`**

This project's content is primarily empty. You will have to add content to it, such as your sprites (images).

> * The **`Game1.cs`** class structure

This class inherits from the Microsoft.Xna.Framework.Game class.

The most important methods of this class are:

1. private members;
2. Its constructor;
3. protected override void `Initialize()` { } ;
4. protected override void `LoadContent()` { } ;
5. protected override void `Update(GameTime gameTime)` { } ;
6. protected override void `Draw(GameTime gameTime)` { } .

> * **Private Members**

The default private members that are useful:

```
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch; // This instance of the SpriteBatch is used to display your sprites in your game.
private Texture2D _sprite; // The sprite that will be displayed on the game screen.

```

> * **The constructor**

You may here change the screen size, its resolution. When you wish to address specifically to Windows, you may even use the compiler directives:

```
#if WINDOWS
    _graphics.PreferredBackBufferHeight = 400;
    _graphics.PreferredBackBufferWidth = 640;
#endif

```

These lines will change your game resolution to the specified values.

> * The **`Initialize()`** method

You may or may not have anything to write here. Aside, if you wish to reserve some area for specific needs in your game, you may as well define your boundaries variables here.

> * The **`LoadContent()`** method

This is the most important method along with the `Update()` and `Draw()` methods. This is here you will need to load your sprite.

```
protected override void LoadContent() {
    // Remember those private members? They'll be used here!

    _spriteBatch = new SpriteBatch(GraphicsDevice);
    _sprite = Content.Load<Texture2D>(@"mySpriteKey");
}

```

The System.String "mySpriteKey" refers to the `Asset Name` property accessed through the Properties Window of an image file.

> * The **`Update(GameTime gameTime)`** method

This is used to update the state of your game and get the keys pressed by the user such as keyboard keys. That is subject for another question though. Besides, you need to master this method to make your sprite move on screen.

> * The **`Draw(GameTime gameTime)`** method

This is where the sprite, loaded within the `LoadContent()` method, gets drawn on your game screen. To draw your loaded in `_sprite` private member sprite image, you need to use the `_spriteBatch` private member.

```
protected override void Draw(GameTime gameTime) {
    GraphicsDevice.Clear(Color.CornFlowerBlue);

    _spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
    _spriteBatch.Draw(_sprite, new Rectangle(0, 0, 100, 100), Color.White);
    _spriteBatch.End();
}

```

> * **Okay, I've all coded the necessary, but the**

```
_sprite = Content.Load<Texture2D>(@"mySpriteKey");`

```

> **line complains about an invalid asset name or something, what to do?**

You need to add your sprite image file to your `MyFirstGameContent` project. In order to do so,

1. right-click on the project name, and **Add|Existing Item**; then
2. browse to your whatever image you want to display on screen; and
3. click **\[Add\]** button.

You should now see you image file being part of your content project. Now,

1. right-click the image file, and click `Properties`; you now have to make sure that
2. your `Asset Name` property value is the same as the string key you passed to the `Content.Load<T>()` method.

> * **Some interesting links I've used to learn**

1. Arkanoid Nintendo NES Sprites;
2. How to make a 2D XNA Game;
3. Going Beyond: XNA Game Studio in 3D.

Please feel free to ask any further details as I will be pleased to tell all I know and beyond. I love to share knowledge.
> 7 votes

# Answer
Here is a small sample from msdn on how to load and draw a simple sprite.

I would wrap the `Content.Load` part into a Method, so you could just call a custom method like, `loadTexture("textureName")` that loads the texture or sets other things up as well.

But that is not that helpful for a lot of sprites, or sprites with animations.

To use sprites with animations, use Sprite Sheet Packer. It generates a Sprite Sheet, and a txt file with a map of rectangles for each image.

In my games, **I create a `AssetManager`, that has a Method to load a SpriteSheet texture, and uses the exported text file to group animations.** I just edited the txt file map to have the animations all grouped with no spaces under each line, and then a line break to end it and start the new one.

The reasons sprite sheets are really good to use in XNA, is that for each texture that is used for drawing, **it requires an extra `SpriteBatch` call to the video card**, and if you have too many calls, you will have reduced performance. So if you are going to have a lot of objects being drawn at once, if they can all fit on one sprite sheet, you will have less drawing overhead.

But if you have a large animation with little to no extra instances, you are going to want to import the texture as individual frames, so only each frame needs to be sent to video card, and not the entire animation when it is not being used. Here is an answer I posted explaining how to do the large animation
> 1 votes

---
Tags: xna, windows, xna-4.0
---


# Question
Title: Where can I advertise my engine, library or framework to attract users?
I have just finished my hypothetical game engine, library or framework.
Now, I want to share it with people who may find it useful in their projects. Where can I advertise it to gain users?

By advertise, I mean to spread the word of its existence - not advertise it for money.

# Answer
> 8 votes
Marking technology is going to be quite similar to marketing a game -- in fact, if you have games made with that technology, that would be a great boon to adoption. Show them off.

With SlimDX, we started by hosting the project on Google Code, advertising very narrowly -- within a single community of developers (GDNet). That got us a few high level bits of feedback that we iterated on. Most importantly, though, we used the framework ourselves to build our own projects so we knew what the user experience was like and tweaked that until it was a good user experience. This includes things like making the end-user runtime installers as painless as possible, coming up with a decent documentation build, and providing at least basic "getting started" samples.

Then we kept plugging it whenever it was relevant in forums, we started a Twitter account to watch for people mentioning it and interacting with them, and slowly built up a community around the library, at which point the community was able to take on some of the burden of mentioning it all over the place.

You have to be careful when plugging your project, of course; we tended to be able to say, "well, you could use XNA if X, Y and Z or you could use SlimDX if A, B and C." It helps, I think, to be honest about the advantages and disadvantages of your product.

The most important thing is probably going to be establishing yourself as quick, responsive, and client-focused early on. We were able to turn around bug reports and feature requests extremely quickly in our first few months and invested a lot of time in making the framework easy to get and start using. Establishing that solid initial relationship with your early-adopters will really help propel you forward.

# Answer
> 4 votes
1. Make it good.
2. When people ask (on forums, StackExchange, etc) which library to use for X, answer with your library.

That's sufficient, I think. Word spreads quickly between developers about these things.

# Answer
> 3 votes
Social networks. It may sound a little stupid, but lots of people use them, and you are generally connected to people with the same interests as you, so it can be a good place to get a little exposure.

Having a website for the engine/lib/framework may also be a good idea, it will make the project look a little more professional. Then depending on the type of project, some screenshots will allow people to see the level of quality. Some getting started tutorials will also allow users to quickly start using the projects.

Message boards too can be a good place to advertise your project, and to allow for feedback too.

# Answer
> 3 votes
If it's an open source project, you might consider putting it on SourceForge and/or link it to Ohloh. People might like what you created and will (hopefully) give positive feedback/ratings on these platforms which can increase the popularity of your project. That way you might even find some developers who will help you improve the software you wrote.

Having a dedicated Website for the product and maybe a Twitter feed/account won't hurt either.

# Answer
> 2 votes
Posting it on a developer forum like the TIGSource forums would be useful, but you should make sure not to just drive by and spam them. People will be much more receptive if you're trying to be a member of their community and also happen to have this cool tool to help them work.

# Answer
> 2 votes
Not sure why it hasn't been mentioned yet, but I believe the best way to attract users to your engine is to write (or have someone write) a good game using it. When evaluating libraries and engines, the list and number of titles using them is always a good indicator of ease of use, versatility, support availability...

---
Tags: marketing
---


# Question
Title: How can Highscores be more meaningful and engaging?
I'm developing a casual Android game in which the player's success can very easily be represented by a number (I'm not more specific because I'm interested in the topic in general).

Although I myself am not a highscore person at all, I was thinking of implementing a highscore for that game, but I see at least 2 problems in the classical leaderboard approach:

* very soon the highscore will be dominated by hardcore players, leaving no chance for beginners, who are then frustrated. This is very severe especially in casual games.
* there is no direct reward for being a loyal player who plays the game over and over again

My current idea is to "reset" the highscore every 24 hours (for example) and each day nominate the "player of the day" who then gets a "star". Then there would be some kind of meta-highscore of players with the most stars.

That way even beginners might have a chance to be "player of the day" once and continued or repeated play is rewarded much more.

The idea is still very rough and there are many problems in the details and the technical implementation but I have a feeling it is a step in the right direction.

**Do you have creative and new ideas on how to implement highscores?**

Which games are doing this well / what types of highscores do you find most engaging?

# Answer
> 8 votes
I like all time high score and daily high score board as well. But my favourite highscores is when they match it up with my friends scores, I don't care about some guy I don't know highscore, I want to see how well I do against people I know/in my area

# Answer
> 2 votes
Perhaps the best solution is to compile this in a community wiki:

**Make your Highscore more meaningful:**

* integrate it with **social networks** your players are using (their friends are much more important to them than strangers)
* make it **local** (because players care more about their city/country)

**Make your Highscore more engaging and less frustrating**

* **divide** your highscore table in **time ranges** (e.g. last 24 hours) so everyone gets a fresh chance every once in a while (*Risk:* If there's no all-time highscore, the player's scores "expire" or are reset it feels like taking them away)
* **divide** your highscore table in **skill ranges** to only show players opponents whom they can realistically beat
* **reward** other things than raw points, like **continued or repeated play**
* provide **short term goals** like achievements on the way to a highscore

*Feel free to add your own guidelines/tips!*

# Answer
> 1 votes
As a player I would be very upset if my high score was reset. Hardcore players work hard to get that score. Taking it away would not be a nice thing.

You could have a hybrid approach. Have a high score board and a daily high score board.

As far as loyal players, you could add a third board for a type of overall or averaged score system. This could be a some factor of amount of time played, number of games and average/total score.

Just some thoughts.

# Answer
> 0 votes
If you keep all scores in the database, you can filter your leaderboards by scores that were received in the last 24 hours to get the best players of the day. Analogously, you can show the best players of the week or the month, or the best players in a specific location.

There is no need to reset the high-scores.

---
Tags: competition, leaderboards
---


# Question
Title: Game engine used for iPhone Zombie Cafe?
There is a game called Zombie Cafe, for iPhone. It is 2d and has a cool concept. Developed by capcommobile.

Anyway, all I want to know is what engine did they use for making it? I know that this kind of game could be done using pretty much any engine, but I am particularly interested in capcommobile's approach. Do you have any idea?

# Answer
Seeing as it's Capcom, it's most likely that they used a bespoke engine that they created themselves. I'm not familiar with the game itself, but with fairly few stable engines for mobile development currently out there and not many big developers using something like Unity at the minute, I would say they just made it themselves.

It's Capcom, they have A LOT of code and experience, so I don't think it would be a massive challenge for them (unless the game has some crazy stuff in it, which is a challenge for anybody).
> 2 votes

---
Tags: iphone
---


# Question
Title: How to get local point inside a body where mouse click occurred in box2d?
I need to find out the point inside a body, lets say a rectangular object, where the mouse was clicked on. I'm makin a game where the force will be applied depending on where the mouse was clicked on the body. Any ideas?

Will `body.GetLocalPoint(b2vec2)` work? I tried by passing the mouse coordinates when the click occurred when inside the body but if the body's position is `(400,300)` in world coordinates then for `trace(body.GetLocalPoint(new b2vec2(mouseX,mouseY)).x);` I get some value between 380 to 406 or something (eg. 401.6666666). I thought getLocalPoint will give something like `x=-10` when clicked to the left of the centre of body or `x=15` etc when clicked to the right.

Language is As3 btw.

# Answer
> 1 votes
I got the point inside the body by passing the proper values of arguments. GetLocalPoint() needs its arguments in the correct pixel to metre ratio. Also I'm supposed to pass a world point.

```
m_targetX = ball.GetWorldPoint(ball.GetLocalPoint(new b2Vec2(mouseXPhys, mouseYPhys)) ).x * m_physScale;
m_targetY = ball.GetWorldPoint(ball.GetLocalPoint(new b2Vec2(mouseXPhys, mouseYPhys)) ).y * m_physScale;

```

This gives the required point inside the body in world coordinates. Donno if there's an efficient way but it is good for now.

```
mouseXPhys = mouseX / m_physcale;
mouseYPhys = mouseY / m_physcale;

m_physcale = 30; //my pixel to metre ratio.

```

---
Tags: actionscript-3, box2d
---


# Question
Title: What are the pros and cons of non-unique display names?
I know of at least big title game (Starcraft II) that doesn't require unique display names, so it would seem like it can work in at least some circumstance.

Under what situations does allowing non-unique display names work well? When does it not work well?

Does it come down to whether or not impersonation of someone else is a problem?

The reasons I believe it works for Starcraft II is that there isn't any kind of in-game trading of virtual goods and other than "for kicks" there isn't much incentive to impersonate someone else in the game. There's also ladder rankings so even trying to impersonate a pro is easily detectable unless you're on a similar skill level.

What are some other cases where it makes sense to specifically allow or disallow duplicate display names?

# Answer
> 9 votes
In Champions Online and Star Trek Online we solved this by using a two part name. The second part must be unique, but the first doesn't need to be - we show this in-game as `Display Name@account`. This also means we can put significant restrictions on the account name - for example, ASCII only, no spaces, no punctuation - and give more freedom for the display name. In-game, players see a combination of both with the account name visually muted (smaller font, darker font), and the account name display can be turned off for strict RPers.

The need for this was driven mostly by Champions. Experience with City of Heroes told us that the namespace of desirable superhero names is pretty small. They all follow a similar pattern. Since naming was also the last step of creating the character, it was also very frustrating to build a character like "Giant Flame" only to find the name was taken, and have to go back to and make yourself either smaller or less on fire. It also encourages RPing - one supergroup (guild) in CoH had characters "Duplicate Girl", "DupIicate Girl", "Duplicate Gir1", all with the same costume. In Champions, people can use the exact same name.

Honestly, I don't know when it doesn't work well. It probably works well everywhere. Some answers have brought up issues with FPSs that need quick communication, but it seems to me that it would only become a problem if you need *quick* and *long-term* communication. For someone to abuse it, you need to give them enough time with you to spoof a name, and yet not enough time to explain which one you're talking about. When you say "Crap, Joe's around the corner", which one you mean is usually obvious.

# Answer
> 2 votes
If you're going to be trading, interacting, or something that involves potentially meeting that person again, then unique names would be a good idea. For example, if you were playing `generic FPS` with two people called `generic name`, and you wanted to tell one to fall back, how would you say which person? If they were on different teams, you would again wonder what's going on.

Impersonation isn't going to be an issue unless the game depends on some kind of ladder or ranking system. Even then, there's not going to be much point.

~~Then again, what reason is there to have non-unique names?~~

# Answer
> 2 votes
I guess it's because the display-name doesn't matter that much in Starcraft 2. Even if you were about to meet a player with the same name in an online-match it wouldn't be an issue, since there are several other "layers" that help you distinguish players in game. One is the color of the units on screen, another one is the team the player belongs to (in 2v2 or other team matches).

Impersonation is probably also a non-issue. This is most likely going to happen where there's a bad player that wants to use the name of a very good player. Nobody is going to believe that `FruitDealer` located in the bronze-league is actually the real `FruitDealer`. As soon as you're playing in the top levels, you're most likely opting for a unique name.

Since the ladder is segmented into leagues and the leagues are segmented into divisions, name-clashes are also very unlikely. Maybe Blizzard even makes sure that there aren't players with the same display-name in the same division.

I think the non-unique display-name can work in every game where the name isn't an important part of the virtual identity. In the case of Starcraft 2 you have an character-code (ID) or your battle.net account e-mail that can be used to find friends. The display-name is just what is shown on screen and can even be changed (a limited amount of times).

You might have noticed, that the same is also true for the gamedev.SE site. You can have several users with the same name here.

As soon as you have several properties that can help distinguish players and the display-name isn't used as ID, non-unique display-names can work fine. It also has the big advantage that players don't have to search hours for a display-name, because all the "good" ones are already taken.

# Answer
> 0 votes
One problem with non-unique names is the personating as you described it. If there's a really popular player it is likely that someone will try to impersonate him. You could prevent this or make it obvious by always displaying some kind score next to the players name, so others know if it is the "real" popular player.

If someone is bad and tries to impersonate someone better, others will see it, if he is similarly good he won't try to impersonate because he rather wants his score with his own name.

Another scenario where it would cause problems is in MMORPGs, because you would confuse the two, in the chat for example. Then again that might not be a problem if there is another property of the player that distinguishes them (like class, which is shown next to the players name or as a color of it)

# Answer
> 0 votes
Most other answers have covered the impersonation concerns, but what I haven't seen mentioned and I think is most important is the capacity to specify a player if names can be duplicates. Which one receives `/tell DuplicateName Private information.`? All of them? What if you want to initiate some kind of remote trade? What about a friend's list? What about a mute list? What about impersonating someone just to grief/troll in chat, regardless of league/score/rank/team/whatever?

Having a unique secondary name works if you want to allow duplicates, but ultimately I think that's still rather user-unfriendly. Specifying a player with a long name is annoying to most. By adding a secondary name, the total length of each player's full name increases. If you use the unique secondary name *only* for player specification, it is still user-unfriendly in that you have to refer to players by names that you usually don't associate them with because it's not on display.

---
Tags: multiplayer, gui, security
---


# Question
Title: Restricting joystick within a radius of center
I'm using Unity3d iOs and am using the example joysticks that came with one of the packages. It works fine but the area the joystick moves in is a rectangle which is unintuitive for my type of game. I can figure out how to see if the distance between the center and the current point is too far but I can't figure out how to constrain it to a certain distance without interrupting the finger tracking.

Here's the relevant code:

```
using UnityEngine;
using System.Collections;
public class Boundary
{
public Vector2 min = Vector2.zero;
public Vector2 max = Vector2.zero;
}

public class Joystick : MonoBehaviour{
static private Joystick[] joysticks;                    // A static collection of all joysticks
static private bool enumeratedJoysticks=false;
static private float tapTimeDelta = 0.3f;               // Time allowed between taps

public bool touchPad;                                   // Is this a TouchPad?
public Rect touchZone;
public Vector2 deadZone = Vector2.zero;                     // Control when position is output
public bool normalize = false;                          // Normalize output after the dead-zone?
public Vector2 position;                                    // [-1, 1] in x,y
public int tapCount;                                            // Current tap count

private int lastFingerId = -1;                              // Finger last used for this joystick
private float tapTimeWindow;                            // How much time there is left for a tap to occur
private Vector2 fingerDownPos;
private float fingerDownTime;
private float firstDeltaTime = 0.5f;

private GUITexture gui;                             // Joystick graphic
private Rect defaultRect;                               // Default position / extents of the joystick graphic
private Boundary guiBoundary = new Boundary();          // Boundary for joystick graphic
public Vector2 guiTouchOffset;                      // Offset to apply to touch input
private Vector2 guiCenter;                          // Center of joystick

private Vector3 tmpv3;
private Rect tmprect;
private Color tmpclr;

public float allowedDistance;

public enum JoystickType
{
    movement, rotation
}

public JoystickType joystickType;

public void Start()
{
    // Cache this component at startup instead of looking up every frame
    gui = (GUITexture) GetComponent( typeof(GUITexture) );

    // Store the default rect for the gui, so we can snap back to it
    defaultRect = gui.pixelInset;

    if ( touchPad )
    {
        // If a texture has been assigned, then use the rect ferom the gui as our touchZone
        if ( gui.texture )
            touchZone = gui.pixelInset;
    }
    else
    {
        // This is an offset for touch input to match with the top left
        // corner of the GUI
        guiTouchOffset.x = defaultRect.width * 0.5f;
        guiTouchOffset.y = defaultRect.height * 0.5f;

        // Cache the center of the GUI, since it doesn't change
        guiCenter.x = defaultRect.x + guiTouchOffset.x;
        guiCenter.y = defaultRect.y + guiTouchOffset.y;

        // Let's build the GUI boundary, so we can clamp joystick movement
        guiBoundary.min.x = defaultRect.x - guiTouchOffset.x;
        guiBoundary.max.x = defaultRect.x + guiTouchOffset.x;
        guiBoundary.min.y = defaultRect.y - guiTouchOffset.y;
        guiBoundary.max.y = defaultRect.y + guiTouchOffset.y;
    }
}

public void Disable()
{
    gameObject.active = false;
    enumeratedJoysticks = false;
}

public void ResetJoystick()
{
    if (joystickType != JoystickType.rotation)
    {
        //Don't do anything if turret mode
        // Release the finger control and set the joystick back to the default position
        gui.pixelInset = defaultRect;
        lastFingerId = -1;
        position = Vector2.zero;
        fingerDownPos = Vector2.zero;

        if ( touchPad ){
            tmpclr  = gui.color;
            tmpclr.a = 0.025f;
            gui.color = tmpclr;
        }
    }
    else {
                    //gui.pixelInset = defaultRect;
        lastFingerId = -1;
        position = position;
        fingerDownPos = fingerDownPos;

        if ( touchPad ){
            tmpclr  = gui.color;
            tmpclr.a = 0.025f;
            gui.color = tmpclr;
        }
    }
}

public bool IsFingerDown()
{
    return (lastFingerId != -1);
}

public void LatchedFinger( int fingerId )
{
    // If another joystick has latched this finger, then we must release it
    if ( lastFingerId == fingerId )
        ResetJoystick();
}

public void Update()
{
    if ( !enumeratedJoysticks )
    {
        // Collect all joysticks in the game, so we can relay finger latching messages
        joysticks = (Joystick[])  FindObjectsOfType( typeof(Joystick) );
        enumeratedJoysticks = true;
    }

    //CHeck if distance is over the allowed amount
    //Get centerPosition

    //Get current position

    //Get distance

    //If over, don't allow

    int count = iPhoneInput.touchCount;

    // Adjust the tap time window while it still available
    if ( tapTimeWindow > 0 )
        tapTimeWindow -= Time.deltaTime;
    else
        tapCount = 0;

    if ( count == 0 )
        ResetJoystick();
    else
    {
        for(int i = 0;i < count; i++)
        {
            iPhoneTouch touch = iPhoneInput.GetTouch(i);
            Vector2 guiTouchPos = touch.position - guiTouchOffset;

            bool shouldLatchFinger = false;
            if ( touchPad )
            {
                if ( touchZone.Contains( touch.position ) )
                    shouldLatchFinger = true;
            }
            else if ( gui.HitTest( touch.position ) )
            {
                shouldLatchFinger = true;
            }

            // Latch the finger if this is a new touch
            if ( shouldLatchFinger && ( lastFingerId == -1 || lastFingerId != touch.fingerId ) )
            {

                if ( touchPad )
                {
                    tmpclr = gui.color;
                    tmpclr.a = 0.15f;
                    gui.color = tmpclr;

                    lastFingerId = touch.fingerId;
                    fingerDownPos = touch.position;
                    fingerDownTime = Time.time;
                }

                lastFingerId = touch.fingerId;

                // Accumulate taps if it is within the time window
                if ( tapTimeWindow > 0 )
                {
                    tapCount++;
                    print("tap" + tapCount.ToString());
                }
                else
                {
                    tapCount = 1;
                    print("tap" + tapCount.ToString());
                    //Tell gameobject that player has tapped turret joystick
                    if (joystickType == JoystickType.rotation) {
                        //TODO: Call!
                    }
                    tapTimeWindow = tapTimeDelta;
                }

                // Tell other joysticks we've latched this finger
                foreach ( Joystick j in joysticks )
                {
                    if ( j != this )
                        j.LatchedFinger( touch.fingerId );
                }
            }

            if ( lastFingerId == touch.fingerId )
            {
                // Override the tap count with what the iPhone SDK reports if it is greater
                // This is a workaround, since the iPhone SDK does not currently track taps
                // for multiple touches
                if ( touch.tapCount > tapCount )
                    tapCount = touch.tapCount;

                if ( touchPad )
                {
                    // For a touchpad, let's just set the position directly based on distance from initial touchdown
                    position.x = Mathf.Clamp( ( touch.position.x - fingerDownPos.x ) / ( touchZone.width / 2 ), -1, 1 );
                    position.y = Mathf.Clamp( ( touch.position.y - fingerDownPos.y ) / ( touchZone.height / 2 ), -1, 1 );
                }
                else
                {
                    // Change the location of the joystick graphic to match where the touch is
                    tmprect = gui.pixelInset;
                    tmprect.x = Mathf.Clamp( guiTouchPos.x, guiBoundary.min.x, guiBoundary.max.x );
                    tmprect.y = Mathf.Clamp( guiTouchPos.y, guiBoundary.min.y, guiBoundary.max.y );

                    //Check distance
                    float distance = Vector2.Distance(new Vector2(defaultRect.x, defaultRect.y), new Vector2(tmprect.x, tmprect.y));
                    float angle = Vector2.Angle(new Vector2(defaultRect.x, defaultRect.y), new Vector2(tmprect.x, tmprect.y));
                    if (distance < allowedDistance) {
                        //Ok
                        gui.pixelInset = tmprect;
                    }
                    else {
                                                 //This is where I don't know what to do...
                    }

                }

                if ( touch.phase == iPhoneTouchPhase.Ended || touch.phase == iPhoneTouchPhase.Canceled )
                    ResetJoystick();
            }
        }
    }

    if ( !touchPad )
    {
        // Get a value between -1 and 1 based on the joystick graphic location
        position.x = ( gui.pixelInset.x + guiTouchOffset.x - guiCenter.x ) / guiTouchOffset.x;
        position.y = ( gui.pixelInset.y + guiTouchOffset.y - guiCenter.y ) / guiTouchOffset.y;
    }

    // Adjust for dead zone
    float absoluteX = Mathf.Abs( position.x );
    float absoluteY = Mathf.Abs( position.y );

    if ( absoluteX < deadZone.x )
    {
        // Report the joystick as being at the center if it is within the dead zone
        position.x = 0;
    }
    else if ( normalize )
    {
        // Rescale the output after taking the dead zone into account
        position.x = Mathf.Sign( position.x ) * ( absoluteX - deadZone.x ) / ( 1 - deadZone.x );
    }

    if ( absoluteY < deadZone.y )
    {
        // Report the joystick as being at the center if it is within the dead zone
        position.y = 0;
    }
    else if ( normalize )
    {
        // Rescale the output after taking the dead zone into account
        position.y = Mathf.Sign( position.y ) * ( absoluteY - deadZone.y ) / ( 1 - deadZone.y );
    }

}

```

}

So the later portion of the code handles the updated position of the joystick thumb. This is where I'd like it to track the finger position in a direction it still is allowed to move (like if the finger is too far up and slightly to the +X I'd like to make sure the joystick is as close in X and Y as allowed within the radius)

Thanks for reading!

# Answer
I'm not at all familiar with unity or iOS, however this sounds like a maths problem.

As your positions go from -1 to +1 all you need to do is see if the distance to the point is greater than 1.0 (i.e. outside a circle) and if it is normalize it so it's on the circle. Something like:

```
float distance = Mathf.Sqrt(position.x * position.x + position.y * position.y);
if (distance > 1.0f)
{
    position.x /= distance;
    position.y /= distance;
}

```
> 4 votes

---
Tags: c#, unity, ios, joystick
---


# Question
Title: What is the best practice to move sprites using mouse order in Tile games?
I am trying to make my first Tile-game using XNA. I have no problem drawing the map layers using TiledLib from codeplex, but, now I want to give sprite an (order) to move to a specific position on map, by selecting the sprite (left mouse click) and then right mouse click somewhere on the map to specify the target position. I don’t know what is the best practice to move sprite this way, considering that there may be collision objects in the direct path.

What is the best practice to do this? Is there any demo covering this issue?

BTW: I couldn’t upload snapshot because of my low score :(

# Answer
> 2 votes
You may want to look up the A\* pathfinding algorithm and some material explaining it.

---
Tags: xna, game-design, tiles
---


# Question
Title: 2D shader to draw representation of rotating sphere
I want to display a 3D textured sphere, and then rotate it in one direction. The direction will never change, and the camera will never move. One way is to actually create a spherical mesh, map a texture to it, rotate the sphere, and render in 3D.

My question is, is there a way to display a 2D circle, that looks like a rotating sphere, with just a 2D shader.

In other words, can someone think of a trick, like mapping a texture to the circle in a particular way, to give the appearance of an in-place rotating sphere, that is always viewed from the side?

I don't need exact shader code, I'm just looking for the right idea.

# Answer
> 10 votes
You can perform a spherical projection in a pixel shader applied to a quad.

Assume the sphere is centered in the quad and the projection is orthogonal (it becomes slightly more difficult with perspective projection but if you pass your inverse view and projection matrices within the shader you should manage to do it, too).

Instead of querying the texture coordinates the usual way:

```
gl_FragColor = texture2D(texture, texCoord);

```

You use `texCoord` as the final coordinates of a spherical texture mapping and retrieve the original texture coordinates by reversing the process:

```
float x = 2.0 * (texCoord.x - 0.5);
float y = 2.0 * (texCoord.y - 0.5);
float r = sqrt(x * x + y * y);

float d = r ? asin(r) / r : 0.0;
float x2 = d * x;
float y2 = d * y;

```

Now `x2` and `y2` are values between  and `π`. You need to “scroll” the texture according to your `time` variable, and normalize your texture coordinates. For a simple rotation around the Y axis:

```
float x3 = mod(x2 / (4.0 * pi) + 0.5 + time, 1.0f);
float y3 = y2 / (2.0 * pi) + 0.5;

```

Then finally query the texture, but only if we fall inside the sphere:

```
if (r <= 1.0)
    gl_FragColor = texture2D(texture, vec2(x3, y3));
else
    ; /* Choose something to do here */

```

# Answer
> 2 votes
If it doesn't have to be highly accurate, you could write a simple 2D displacement-map filter (something like this pixelbender shader). Then use a 2D normal-map to achieve a spherical effect. Here's an image showing the result (above) and the normal-map (below) \[source\]:

To give the effect of a rotating sphere, you would simply move the image (checkerboard) and mask it with a circle (or `discard` all the pixels outside the circle radius).

# Answer
> 1 votes
You might find http://www.voofoostudios.com/?p=33 useful.

Note that a sphere towards the edge of the screen won't be represented in 2D by a circle - perspective will distort it a bit.

---
Tags: mathematics, shaders, hlsl
---


# Question
Title: Converting to and from local and world 3D coordinate spaces?
I've been following a guide I found here (http://knol.google.com/k/matrices-for-3d-applications-view-transformation) on constructing a matrix that will allow me to 3D coordinates to an object's local coordinate space, and back again. I've tried to implement these two matrices using my object's look, side, up and location vectors and it seems to be working for the first three coordinates. I'm a little confused as to what I should expect for the *w* coordinate.

Here are couple of examples from the print outs I've made of the matricies that are constructed. I'm passing a test vector of \[9, 8, 14, 1\] each time to see if I can convert both ways:

Basic example:

```
localize matrix:
Matrix: 0.000000    -0.000000   1.000000    0.000000
        0.000000    1.000000    0.000000    0.000000
        1.000000    0.000000    0.000000    0.000000
        5.237297    -45.530716  11.021271   1.000000
globalize matrix:
Matrix: 0.000000    0.000000    1.000000    0.000000
        -0.000000   1.000000    0.000000    0.000000
        1.000000    0.000000    0.000000    0.000000
        -11.021271  -45.530716  -5.237297   1.000000

test:
Vector4f(9.000000, 8.000000, 14.000000, 1.000000)
localTest:
Vector4f(14.000000, 8.000000, 9.000000, -161.812256)
worldTest:
Vector4f(9.000000, 8.000000, 14.000000, -727.491455)

```

More complicated example:

```
localize matrix:
Matrix: 0.052504    -0.000689   -0.998258   0.000000
        0.052431    0.998260    0.002068    0.000000
        0.997241    -0.052486   0.052486    0.000000
        58.806095   2.979346    -39.396252  1.000000
globalize matrix:
Matrix: 0.052504    0.052431    0.997241    0.000000
        -0.000689   0.998260    -0.052486   0.000000
        -0.998258   0.002068    0.052486    0.000000
        -42.413120  5.975957    -56.419727  1.000000

test:
Vector4f(9.000000, 8.000000, 14.000000, 1.000000)
localTest:
Vector4f(-13.508600, 8.486917, 9.290090, 2.542114)
worldTest:
Vector4f(9.000190, 7.993863, 13.990230, 102.057129)

```

As you can see in the more complicated example, the coordinates after converting both ways loose some precision, but this isn't a problem. I'm just wondering how I should deal with the last (w) coordinate? Should I just set it to 1 after performing the matrix multiplication, or does it look like I've done something wrong?

Thanks in advance for your help!

# Answer
It looks like you are confusing rows and columns in your matrices, either in the way your load or store them, or when you perform the matrix×vector multiplication. The `w` coordinate should always yield `1` with the matrices you are using.
> 2 votes

---
Tags: 3d, coordinates, matrix, localization
---


title: Weird rotation problem

text:
# Question
Title: Weird rotation problem
I'm creating a simple tank game. No matter what I do, the turret keeps facing the target with it's side. I just can't figure out how to turn it 90 degrees in Y once so it faces it correctly. I've checked the pivot in Maya and it doesn't matter how I change it.

This is the code I use to calculate how to face the target:

```
void LookAt()
{

    var forwardA = transform.forward;
    var forwardB = (toLookAt.transform.position - transform.position);

    var angleA = Mathf.Atan2(forwardA.x, forwardA.z) * Mathf.Rad2Deg;
    var angleB = Mathf.Atan2(forwardB.x, forwardB.z) * Mathf.Rad2Deg;

    var angleDiff = Mathf.DeltaAngle(angleA, angleB);
    //print(angleDiff.ToString());
    if (angleDiff > 20) {
        //Rotate to
        transform.Rotate(new Vector3(0, (-turretSpeed * Time.deltaTime),0));
        //transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + adjustment, transform.rotation.z, transform.rotation.w);

    }
    else if (angleDiff < 20) {
        transform.Rotate(new Vector3(0, (turretSpeed * Time.deltaTime),0));
        //transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + adjustment, transform.rotation.z, transform.rotation.w);

    }
    else {

    }
}

```

I'm using Unity3d and would appreciate any help I can get! Thanks!

# Answer
To solve this I kept my code and added a parent object which got the code component instead. Then I turned the child object so that the rotation weirdness disappeared.
> 1 votes

# Answer
Why are you doing the math at all instead of a helper function or two?

For example, `Quaternion.LookRotation( Vector3 forward )`
> 2 votes

---
Tags: unity, vector, rotation
---


title: Texture mapping on gluDisk

text:
# Question
Title: Texture mapping on gluDisk
I'm trying to map a brick texture on the edge of a fountain and I'm using gluDisk for that. How can I make the right coordinates for the disk? My code looks like this and I have only found a function that takes the texture along with the camera.

I want the cubic texture to be alongside of the fountain, but gluDisk does a linear mapping. How do I get a circular mapping?

```
void Fountain::Draw()
{
    glPushMatrix(); // push 1
    this->ApplyWorldMatrixGL();
    glEnable(GL_TEXTURE_2D); // enable texturing
    glPushMatrix(); // push 2
    glRotatef(90,-1,0,0); // rotate 90 for the quadric

    // also drawing more here...

    // stone texture
    glBindTexture(GL_TEXTURE_2D, texIDs[0]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    glPushMatrix(); // push 3
    glTranslatef(0,0,height);

    // spherical texture generation
    // this piece of code doesn't work as I intended
    glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
    glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
    glEnable(GL_TEXTURE_GEN_S);
    glEnable(GL_TEXTURE_GEN_T);

    GLUquadric *tub = gluNewQuadric();
    gluQuadricTexture(tub, GL_TRUE);
    gluDisk(tub, radius, outerR, nrVertices, nrVertices);
    gluDeleteQuadric(tub);
    glDisable(GL_TEXTURE_GEN_S);
    glDisable(GL_TEXTURE_GEN_T);

    glPopMatrix(); // pop 3
    // more drawing here...
    glPopMatrix(); // pop 2
    // more drawing here...
    glPopMatrix(); // pop 1
}

```

To refine my question a bit. This is an image of what it is at default (left) and of what I want (right). The texture should fit in the border of the disk, a lot of times. If this is possible with the texture matrix, than that's fine with me as well.

# Answer
> 1 votes
I'm not sure I understand your diagram. Are you saying you want the image to repeat along the edge of the disk (i.e. the lines represent the borders of the image?) If so, that may produce visual artifacts that you might want to consider first.

The way you've drawn it here, the image will compress near the inner part of the disk, and stretch near the outer part. The different radii of the inner/outer circle causes the arc lengths to be different. You're essentially mapping a square to a trapezoid. I would post an image, but my account is too new. Argh.

I don't think GLU offers any other form of texture mapping for disks. If you want that kind of custom texture coordinates, you probably need to roll your own form of disk generation, which isn't that bad anyways. Still, you might want to reconsider using GLU for actual geometry anyways.

---
Tags: c++, opengl, uv-mapping
---


# Question
Title: Calculate the initial velocity of a 3D trajectory
I've got a 2D projectile code sample working, but would like to extend it to 3D. How would I calculate the initial velocity of the Z-axis? At the moment, I've got:

```
initVel.X = (float)Math.Cos(45.0);
initVel.Y = (float)Math.Sin(45.0);

```

How would I convert this to work in 3D, and add the initial velocity for the Z-axis?

In my example, X is across, Y is up down and Z is going into the screen. I also normalize the vector and multiply it by the speed.

# Answer
> 3 votes
```
double ZAdjust = Math.Cos(XZAngle);
initVel.X = (float)(Math.Cos(XYAngle) * ZAdjust);
initVel.Y = (float)(Math.Sin(XYAngle) * ZAdjust);
initVel.Z = (float)Math.Sin(XZAngle);

```

---
Tags: 3d, physics, mathematics, vector
---


# Question
Title: How to detect and collide two elastic line segments?
There are 4 moving physical nodes in 3D space. They are paired with two elastic line segments / strings (1 \<-\> 2; 3 \<-\> 4).

Part I: How to detect the collision of two segments?

Part II: On the moment of collision, fifth node is created at the intersection point and here you have the force-based graph. 5-th node (bend point) **can slide** among the strings as in a real world. Given the new coordinates of 4 nodes, how to calculate the position of the 5-th node on the next frame? I assume string force on the nodes to be `F = -k * x` where x is the string length.

All I came up to is that the force between 5 and 1 equals 5 and 2 (the same with 3 and 4). What are the other properties?.

# Answer
I realized one can detect two segment collision by observing 180° change in shortest distance vector comparing with previous frame.

*Update:*

Yep, collision seems to be detected correctly and guess what? The length of the elastic strings is actually zero. It only has this super ability to stretch infinitely. If the length is zero, **no sliding** is possible. From visual observation, everything seems real, sliding is not needed here.

*Update:*

Something is still wrong. Sliding *is* needed. It's very visible, when you turn on global gravity and observe one horizontal pair hit vertical pair with velocity. Horizontal one should slide down, but instead, it remains stuck in the middle of the string. Looking in further.

*Update:*

I managed to fix up a formula:

k - general pair's tension.
k1 and k2 - two new tensions for 1 \<-\> 5 and 2 \<-\> 5
d - distance 1 \<-\> 2
d1 and d2 - distance 1 \<-\> 5 and 2 \<-\> 5

k2 = k * d / (2 * d2)
k1 = d2 * k2 / d1

Update k1 and k2 for a pair each frame before physics forces integration kicks in and it behaves OK. Basic frictionless sliding has been enabled, finally.
> 1 votes

# Answer
for very fast moving line segments or large time intervals, I believe you can still get realistic behavior in a system with constant "energy" without very much calculation, but I have not yet found the solution, I'm curious as to what thoughts you dismissed when you went to the "change in occlusion order" method.
> 0 votes

---
Tags: physics, mathematics, collision-detection
---


title: Collision Detection in Java for a game

text:
# Question
Title: Collision Detection in Java for a game
Im making a game in Java with a few other people but we are stuck on one part of it, making the collision detection. The game is an RPG and I know how to do the collision detection with the characters using Rectangles, but what I dont know how to do is the collision detection for the maps. What I mean by that is like so the character cant walk over trees or water and that stuff but using rectangles doesnt seem like the best option here.

Well to explain what the game maps are gonna look like, here is an example:

Now I could use rectangles to get bounds and stop the player from walking over the trees and water but that would take a lot of them.

But is there another easier way to prevent the player from walking over the trees and obstacles besides using Rectangles?

# Answer
> 5 votes
Your map looks like a 2D grid so why not have a boolean\[\]\[\] lookup table for the map? Or even int\[\]\[\] if you want different grid cell types. For smoothing movement around corners you can look up the target position and make a smoother animation, e.g.

`if (movingUpRight && myGrid[playerPosX + 1][playerPosY + 1] == TILE_EMPTY) {
 /* smooth animation */}`

Judging by your question you don't need anything more complicated than that.

If you do need something more fancy take a look at Recast/Detour project \[1\]\[2\] but it doesn't seem to have a Java binding or port (apart from CritterAI but it's not a straight port) so far but someone's got to do the work sooner or later :) If you choose to go that route please get in touch as I plan to support it in my game at some point so we can coordinate the efforts.

\[1\] http://code.google.com/p/recastnavigation/

\[2\] http://digestingduck.blogspot.com/

# Answer
> 3 votes
You use something called a nav mesh. This is basically (in this simple case) a texture with just one bit for each square- collidable or not. When the player tries to move, you check the texture.

# Answer
> 0 votes
Ok, I think I understand your problem and you have a few options that I can think of, the best I don't want to write the code for, but I will give a metaphor for the algorithm I am suggesting. imagine your map as colored entirely black and white, where black pixels are not allowed to be collided with and white pixels are. then imagine your hero (or any character) to be a shape cut out of that map. if any of the pixels in the shape are black, then you have collision. this is similar to what the folks above were suggesting but it does not assume that your character moves on a grid (well it does, but not the same way). some things that might help you speed this up. if your character moves one pixel at a time, then you only need to check the boundary of the shape for black pixels, if he moves two pixels at a time, you need to check two pixels in etc. and if you imagine this as boolean trues and falses instead of black and white, then collision is just everything in your test space ORed together. what's nice about this method, is that since you're only testing the boundary, you can make your collision resolution really fine and the amount of checks you have to do goes up as the square root of the number of pixels, which increases pretty slowly. Some ideas for optimization are to only check a small subset of the pixels in the border of your character since this check is going to occur very often, and this is a good approximation of the whole border.

another idea, you can actually do this by drawing, and then converting the color data into boolean data.

hope this helps.

---
Tags: java, collision-detection
---