# Question
Title: Is networked gameplay inherently hard to debug and create?
I have worked with XNA before and made a simple networked game. I have also worked with Unity3D as well. One thing I notice on many game engine web pages is that they talk about how the engine is great for networking and makes it easier. I then see on these pages links to articles by Valve and such about network predictions and lag which I have seen a bit of with my XNA networked game.

My question is, is networking a game inherently hard to debug and similar to design no matter what engine/framework you use? For example is making a 4 player game with XNA or unity or UDK the same thing in terms of networking code or do some engines relieve this burden.

# Answer
> 10 votes
This is largely an opinion post, as "difficulty" is subjective, some people find things difficult that others find easy, and vice-versa. And honestly networking of games is such a huge topic I'd probably have to write a book about it to fully answer your question.

The difficulty of networking a game depends largely upon the game type. The most difficult would probably be real-time MMOs (massively multiplayer online game), and then FPSs (first-person shooter game), then RTSs (real-time strategy game). Turn-based games like Chess, or other strategy games are usually state-based and much easier to network.

Debugging difficulty depends on a lot of factors:

* **Sending and receiving information during live gameplay:** If a game is always updating the game world based on the new information, that means that when you want to debug you usually need either conditional breakpoints with some very specific conditions that you're expecting, or you'll need some kind of real-time output that you can read through to see when something occurs. You can also create large log files, outputting all the relevant information, and sift through those log files looking for the data you need. For a turn-based game, information is usually only sent when an action occurs. This means the game is usually sitting in a waiting state, waiting for input from a player. I've found this makes it very easy to watch the chain of actions that occur, and the data going back and forth during each action, to see where something goes wrong.
* **Number of players:** The more players that are interacting, the more information is being generated, and the more places are sending and receiving that data, and changing that data, etc. More players in a game at one time will almost always add to the difficulty of networking and debugging that networking.
* **Precision:** Depending on the type of game and the quality level you're shooting for, the precision of your network prediction may have to be high, or not. For a turn-based game this is usually not important, there is a relatively large amount of time between events (hundreds to thousands of milliseconds), and the number of possibilities in a single turn in a turn-based game is relatively small, so prediction can usually be 100% accurate. With something like an FPS game there will almost always be too much going on, in such small amounts of time, in an unpredictable manor, that you will need to make educated guesses on what position something will be in given a handful of variables, most important of which is usually time. Making a basic guesses during prediction will give you some illusion of precision, but can often be far from precise, and if you want something that is more precise most of the time then you'll need to put a lot more work into your prediction methods. Debugging this often means seeing what the server actually did, and what the client did, and looking for differences. Did the client have current information, if not when did it last receiving information, what did it do with the information, etc. Generally I would log a new event that came down from the server, and then log changes to that data, over a period of time, to watch what happened to the data, and see if it's what is expected, and if not I can usually see where the changes start to go wrong.
* **Bandwidth:** This goes hand-in-hand with the last point, which was 'Precision'. If you want very precise movement you often need to send more information per packet and/or more packets over time. Better prediction methods can often result in more accuracy without the need for as much information, but sometimes at the expense of more CPU usage on the client or server.
* **Latency:** If you're making an MMO, FPS, or some other game with networking occurring during gameplay then you may want to have quick reactions and adjustments made based on actions in the game. For example, if a player fires a weapon you're going to want all of the clients to see that as soon as possible. Unfortunately you usually won't get to pick the latency that clients have so your prediction algorithms will need to compensate for different latency between different clients. This becomes more difficult when there are wide ranges of latency between clients on the server. For example if player #1 has 100ms of latency, and they think they just shot player #2 at 30.1 seconds into game, and player #2 has 300ms of latency, and they think they just shot player #1 at 30.3 seconds into the game, which does the server choose? You received player 1's packet 0.2 seconds before player 2, but based on their latency times they probably both sent their packets at the same real time. On top of that problem, you may now realize that after receiving the packet from player 1 at 30.1 seconds into the game, if you had immediately responded to that packet by giving player 1 the reward for the kill, then what do you do when you get the packet from player 2? Just deny them the kill even though they shot player 1 at the same time? Luckily if you're making a turn-based game latency will be of almost no consequence other than to slow the game down ever so slightly by adding latency to the time between events. Debugging latency issues, luckily, is not as difficult of a problem as implementing the handling for latency in the first place. Usually you will have a queue of events that the client has said they have done, and timestamps for each event. As you're going through the queues you should be able to easily visualize the timeline of what has occurred from each client.
* **Combination of the above points:** When you combine the most difficult choices in each of the above points things often become exponentially more difficult. This is why, for example, real-time MMO games tend to be the worst, you have many players who all need to receiving information about changes in each others actions, in real-time. FPS games require high amounts of precision in the prediction and latency issues are extremely noticeable as well. Take all the debugging hassles in each category, and then debug a problem that may span events that occur using one or all of those categories and things can become messy. Real-time monitoring of events, and good tools will go a long way in making debugging easier for games.
* **And more:** There are probably a handful of other points as well that I just haven't thought of at the moment, such as cross-platform networking (can the client run on multiple platforms but connect to the same server?), or localization (can clients running different languages connect to the same server? If so, how would a chatbox work, how would you display Mandarin to someone on an American English client? etc.). Again, implementing these things is difficult enough, but now to properly debug those clients you need to be running in multiple languages, and multiple platforms. Can you debug a Mac client from a PC running Visual Studio, for example? Yes, but it's a pain if you've never done it.

My best advice is to use any game/networking engine that already exists and has some good documentation, reviews, and tools. Writing your own networking for anything but a simple game could take quite a bit of time, so you'll have to weigh that against what kind of time/money you have, and what kind of game you're making.

# Answer
> 0 votes
There are a lot of specifics that make networked gameplay much harder to debug, but in very very general terms it comes down to 2 basic points:

1. Error can arise from a much greater set of potential sources than client-only gameplay.
2. It's hard to insert debug tools into live instances, especially when huge volumes of data are being manipulated.

Usually a multiplayer game has a lot of specialized servers working together (lobby server, game logic, etc.), and many times multiple databases. An error can come from any part of this system such as a bug in your game server software, too much load on the server, incorrect server configuration, bugs or unexpected behavior in the client that send incorrect commands or data, etc. Since you can't easily use a debugger on this live code, usually most companies make use of Logging (either with their own logging tools, open-source tools, or commercial logging packages like Loggly) to debug and then also use specific tools to monitor key system performance metrics.

Keeping an eye on issues in a live environment is a MUCH more in-depth instrumentation, and requires administrators to keep an eye on constantly.

As far as design, even if you use a commercial networking package (like a commercially available networking library, game server or a PaaS/SaaS game networking tool) there's still a lot of fundamental architecture decisions you have to make for your own specific style of game (for instance, are you turn-based, real-time, %100 asynch?), no package will do that for you. So networking while engines provide tools, they don't free you from needing to know networking and network programming principles.

---
Tags: networking
---


# Question
Title: Debugging/Logging Techniques for End Users
I searched a bit, but didn't find anything particularly pertinent to my problem - so please do excuse me if I missed something!

A few months back I inherited the source to a fairly-popular indie game project and have been working, along with another developer, on the code-base. We recently made our first release since taking over the development but we're a little stuck.

A few users are experiencing slowdowns/lagging in the current version, as compared to the previous version, and we are not able to reproduce these issues in any of our various development environments (debug, release, different OSes, different machines, etc.). What I'd like to know is **how can we go about implementing some form of logging/debugging mechanism into the game, that users can enable and send the reports to us for examination?** We're not able to distribute debug binaries using the MSVS 2010 runtimes, due to the licensing - and wouldn't want to, for a variety of reasons.

We'd really like to get to the bottom of this issue, even if just to find out it's nothing to do with our code base but everything to do with their system configuration. At the moment, we just have no leads - and the community isn't a very technically-savvy one, so we're unable to rely on 'expert' bug reports or investigations.

I've seen the debug logging mechanism used in other applications and games for everything from logging simple errors to crash dumps. We're really at a loss at this stage as to how to address these issues, having been over every commit to the repository from the previous to the current version and not finding any real issues.

# Answer
It sounds like you really want to implement some kind of deployed profiling option, not logging in general (while you could use logging to surface the results of your profile data, logging in general isn't really required here because there are better ways to surface the data).

The basic premise will be to have some fairly lightweight methods/objects you can call or create in your code to track timestamps and shove them into data structure, which you then serialize to disk in some form so that users can email it to you. Something like a `BeginTask` and `EndTask` function that takes some kind of task identifier -- a string, or number, or whatever. When `BeginTask` is called, you can record the current time via a high-resolution counter and store it. Then you do the same in `EndTask`, except you look for the matching `BeginTask` timestamp and compute the difference, giving you a task duration.

You can store these in a tree-like structure to give yourself hierarchical profiling (which will help alleviate the issue of coming up with unique task names to match up begin/end pairs). You can also take advantages of C++ idioms such as RAII by putting the calls into the constructor/destructor of some `Profile` class, then you can simply construct one of these `Profile` instances in every function that might be time-critical and you'll get the begin/end calls automatically.

You can go even further than that an enable penter and pexit hooks to call your profiler functions for *every function in your code* automatically, which is a lot less painful than retrofitting construction of `Profiler` objects everywhere. It will also catch things you might have decided "couldn't be slow" and thus avoided adding `Profiler` objects to. Unfortunately it's a bit more work to write proper penter/pexit hooks.

Then you can save this information to disk. You could just dump it to a plain-text log file, for simplicity. I find that it's much better to dump the data into a binary format that you can parse back later with a tool on your end -- but if you're not up for writing such a tool, plain text will serve in a pinch. You'll still probably want some code to scan through the data and find the tasks that took the longest and print them outside of the regular call hierarchy, because that's what you're most likely interested in.

Once you have this functionality enabled, you can have users send you their profiling logs and you can hopefully use that to see what is taking up too much time on their machines, and that might help guide your optimization efforts.

We do this kind of instrumentation on our content production tools at work, and dump the statistics into a database which we use to develop daily metrics reports about task performance. Tasks that become outliers in terms of runtime, or take too long on average (especially if they're running on the UI thread) are hilighted in these reports so we know when we accidentally hurt the performance of something.
> 9 votes

# Answer
In my experience relying on users to send you error reports to you even if it's only a push of the button isn't always reliable. Most users won't send these reports, they'll just stop playing and remove the game or app. In most games I've worked on the fraction of users who send bug reports even with a 1-click option is less than 5%, so the subset of users sending you error reports might not be big enough to solve bugs decisively.

It sounds like what would optimally help you here is some kind of tool that would help you take data from all game sessions automatically, aggregate it, and then allow you to look through the aggregated logs for deviations in optimal behavior without relying on the user at all.

Assuming most of your players have an internet connection, what I'd recommend is sending logs to a 3rd party log aggregation tool like Loggly . This way you can send logs from all clients and will have the full set of data from almost all of your users (minus those few who lack internet connection).

As far as what to log, there's a few different ways to go about it

* The approach cited in using penter/pexit hooks is a good one, but I'd recommend instead of saving it to disk that you send it to your logging tool.
* I'd say that you'd want to use a timer or counter to measure the execution time of key functions in any controller classes that are widely consumed by various objects in your game. Things like animation, rendering, AI, UI, or player-character controllers should be measured and then sent as a log if it deviates from what would be considered a normal execution time.
* Along with anything you log, you would want to send all relevant information about the system the user is playing on (like processor, RAM, OS, etc.) as extra data fields with the JSON logs you send.

To actually send the logs, it would be good to implement a separate controller which handles organizing the logs into a JSON that you can easily read and then sending it to the 3rd party provider's logging servers so that it's a simple Logger.log(functionname, executiontime, … \[overloaded options you might need\] … ) call each time you need to log something.

Over time, this logging will give you constant telemetry for the game which will be immensely useful for logging these bugs and any future ones that may arise.
> 0 votes

---
Tags: c++, debugging
---


# Question
Title: In Monogame, why is multiple tile drawing slow when rendering in "windowed fullscreen"?
I have this drawing function (recommended as a solution here). It draws tiles on the whole window with no problem but my game slows down to ~30fps after maximizing it to "windowed fullscreen", which is 1600x1200 on my PC. (So 1600/16 * 1200/16 = 7500 tiles in the window)

While I want to add more advanced stuff to this simple rendering I wonder if it is possible to draw this tiles in instantiated way in monogames? (Like in OpenGL 3.3) Or is there any other way to speed it up?

BTW. Lowering the number of tiles is not a way and i need to update whole screen per frame because of incoming transparent GUI.

```
protected override void Draw(GameTime gameTime)
{
    frameCounter++;

    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin();

    for (int x = 0; x < Window.ClientBounds.Width / 16; x++)
    {
        for (int y = 0; y < Window.ClientBounds.Height / 16; y++)
        {
            int offX = x + mainCamera.Position.X;
            int offY = y + mainCamera.Position.Y;

            Tile t = gameMap.GroundTiles[offX, offY, mainCamera.Position.Z];
            spriteBatch.Draw(t.Texture, new Vector2(x * 16, y * 16));

        }
    }

    spriteBatch.End();

    base.Draw(gameTime);
}

```

# Answer
I suspect your issue lies in the way a sprite batch works in MonoGame. The performance cost is coming from using different textures for each tile.

Let's take a peek into the MonoGame source code and see what's going on. If you follow the code down through SpriteBatch.End you eventually end up in the SpriteBatcher.cs class around about here:

https://github.com/mono/MonoGame/blob/develop/MonoGame.Framework/Graphics/SpriteBatcher.cs#L243

```
        foreach ( SpriteBatchItem item in _batchItemList )
        {
            // if the texture changed, we need to flush and bind the new texture
            if ( item.TextureID != texID )
            {
                FlushVertexArray( startIndex, index );
                startIndex = index;
                texID = item.TextureID;
                GL.BindTexture ( All.Texture2D, texID );
            }
            // store the SpriteBatchItem data in our vertexArray
            _vertexArray[index++] = item.vertexTL;
            _vertexArray[index++] = item.vertexTR;
            _vertexArray[index++] = item.vertexBL;
            _vertexArray[index++] = item.vertexBR;

            _freeBatchItemQueue.Enqueue ( item );
        }
        // flush the remaining vertexArray data
        FlushVertexArray(startIndex, index);

```

As you can see from this code, the way it batches things up internally is by checking the TextureID of each item in the \_batchItemList and if it has changed, flushes the vertex array and binds a new texture.

This approach is pretty typical of how sprite batching works in most 2D engines (from my understanding) and usually turns out okay. However, if you have too many texture switches it can be pretty costly on performance.

The usual way to deal with this in a tile based engine is to use a texture atlas. That is, a single texture that stores all your tiles and during rendering you pick the tile's "rectangle" from the source texture.

So it's okay to have a few different textures in your game, but try to keep the texture switching to a minimum. For example, 1 texture per layer in tile based game should be fine (assuming you draw each layer one at a time) but for tiles within a single layer, try store them all on a single texture.
> 4 votes

---
Tags: xna, rendering, tiles, performance, monogame
---


# Question
Title: How to describe the performance requirements for a PC game?
System requirements describe the minimum specifications of the hardware and software required to play a game, in terms of performance and compatibility. Some requirements are clear-cut, like the operating system(s), 32 or 64 bit, minimum RAM and disk space, minimum DirectX versions, but for CPU and GPU performance, it's complicated:

* The megahertz/gigahertz myth applies, so it's inaccurate to say "1.6GHz or faster"
* CPU and GPU vary by generation ("Is my Core 2 Duo too old for this?") and segment ("Do I need a high-end rig or a budget rig is enough?"), so "1.2 GHz Pentium" won't cut it
    + Many minimum system requirements mention Athlon, Core 2 Duo, Pentium, ATI and GeForce 8800 GT which sound irrelevant in the age of i3/i5/i7 and A6/A8/A10/FX, AMD-branded (not ATI) GPU and three-digit GeForce GPU numbers (like 760).
* Benchmark scores like 3DMark are accurate, but not everyone are aware of benchmarks or bother to run them.
* Screen resolution and graphic settings are variables not mentioned in most system requirements.
* "Playable frame rate" is subjective: It can be 12, 24, 30, 40, 60

My question is, is there a way to communicate the performance requirements of a game to a buyer that address the issues above. Or, should we ditch performance requirement descriptions and let the buyers do their own research on forums, benchmark sites and review sites? Are there any unusual ways of communicate system performance requirements?

# Answer
Take a look at these requirements published for a recent FPS game:

> • OS: Windows 7 64-Bit / Windows 8 64-Bit
>
> • Intel® Core 2 Duo E8200 2.66 GHZ / AMD Phenom X3 8750 2.4 GHZ or better Recommended: Intel® Core i5 – 680 @ 3.6GHz
>
> • RAM: 6 GB RAM Recommended: 8 GB RAM
>
> • HDD: 40GB HD space
>
> • NVIDIA GeForce GTX GTS 450 / ATI® Radeon HD 5870 or better Recommended: NVIDIA® GeForce GTX 760 @ 4GB
>
> • Sound: DirectX Compatible Sound Card

So to address your concerns:

* Yes megahertz alone is not enough, but usually the hardware model is included anyway
* Hardware brand name (*Core 2 Duo*) alone is not enough, which is why the model name (*E8200*) is also included.
* Yes, hardware numbers are confusing. No, there's no good solution around this; it's a marketing problem.
* If consumers knew about benchmarks, they'd be savvy enough to understand the confusing hardware model numbers too, so this is not a better solution.
* Performance settings are indeed subjective but it's up to you, the game developer, to decide what is a minimally acceptable experience for the game, as well as what's recommended.

None of this has substantially changed in a long time. The PC platform is the ultimate in fragmentation, and for good reason: system requirements is a very complex, multivariable thing. Hardware develops at different rates and sometimes stop entirely (*clock speed vs. cores*) or become obsolete (*fixed pipeline*). Games requirements also grow at different rates or change entirely. The fragmentation also causes huge problems for the uptake of any standard; hardware vendors want inflated scores to sell their product, or for the scores to favor their products; software vendors want diminished scores for much the same reason; consumers want simple scores across hugely disparate hardware and game genres. You mentioned benchmarks being a possible solution, but that has had problems with uptake and corruption. Windows Experience Index is also another one that failed recently, due to uptake problems.

In my experience the most useful approach was to look at the performance of a popular game I already own, and try to guestimate the performance of a new game. This is also the approach taken by a few game reviewers, for example by looking at the fps of the new game vs a well known older game running on the same machine.

The great thing about PC games is the configurability, which really increases the number of people able to play the games; those with beefier hardware can crank up the settings, those with weaker hardware can cripple some settings and still enjoy the game. It is then up to the gamer to decide whether to upgrade or replace their PC to get a better enjoyment on the same games they own.
> 4 votes

---
Tags: performance
---


# Question
Title: The object of type GameObject has been destroyed but you are still trying to access it
I am instantiating the prefabs time to time and I want them to be destroyed with in 2 to seconds as well. But I am getting the error that says:

```
The object of type GameObject has been destroyed but you are still trying to access it

```

So, somewhere script to trying to access the prefab even after it has been destroyed so probably I need to relocate the the statement where I am destroying the prefab using `destroy` .

Here is my code:

```
void Update()
    {
        if (!spawning)
        {
            timer += Time.deltaTime;
        }
        time = Random.Range (20, 40);
        if (timer >= time)
        {
            StartCoroutine(Spawn());

        }
        }
    public IEnumerator Spawn()
    {
        spawning = true;
        timer = 0;
        initial = new Vector3 (Random.Range(rmin, rmax), -0.23f, Random.Range(r.renderer.bounds.min.z, (r.renderer.bounds.max.z + 20)));
        fuelprefab = (GameObject)Instantiate (fuelprefab, initial, Quaternion.identity);
        yield return new WaitForSeconds (Random.Range (1, 3));
        spawning = false;
        Destroy (fuelprefab, Random.Range(1,3));
    }
}

```

What change do I need to make so that it's not accessed after it hs been destroyed and the newly instantiated prefab is accessed?

# Answer
> 3 votes
The problem is that `fuelprefab` is the object passed to the Instantiate() command:

```
fuelprefab = (GameObject)Instantiate(fuelprefab etc.

```

Thus the code attempts to instantiate that object after destroying it. So what you want to do is have separate variables for `fuelprefab` and `fuelInstance`. Then you can freely Destroy() the latter while never destroying the former:

```
fuelInstance = (GameObject)Instantiate(fuelprefab, initial, Quaternion.identity);
yield return new WaitForSeconds(Random.Range (1, 3));
spawning = false;
Destroy(fuelInstance, Random.Range(1,3));

```

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


# Question
Title: Destroying the instance that instantiated the prefab
What I have so far:

A `fuel` that has Fuel script attached to it. The `fuel` prefab is first instantiated from another script in its Start() method.

**problem:** The `Fuel` script is such that it results in instantiation of prefab `fuel` repeatedly at some intervals of time and keeps destroying the earlier ones. But

the prefab that was instantiated from the other script stays there always. I want this prefab to be destroyed as well(or atleast made invisible) while the process of instantiation and destruction of of `fuel` prefabs continues to go on.

How do I achieve this?

# Answer
> 3 votes
Don't instantiate from the Fuel script. I mean, obviously if you don't want a second copy of the object then don't *make* a second copy of the object.

You say "the fuel prefab is first instantiated from another script"; so handle *all* the instantiating and destroying in that script, not just the first time.

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


# Question
Title: How to calculate FPS and what factors affect FPS?
In this case, FPS means Frames Per Second and that means the number of frames that graphic hardware render in one second. I'm wondering what kind of stuffs could affect FPS?

So, for some tests I created a simple scene in Unity with some cubes and capsules and then create a empty game object and then add this c# code to it:

```
public class FPSReport : MonoBehaviour {

    public double Fps;

    void Update ()
    {
        Fps = 1.0 / Time.deltaTime;
    }
}

```

I think it can tell me the FPS. When I played it it worked but it wasn't more than 30.

I was saw a lot of games that their fps was normally on 150. Is this fps rate ok?

If I add more objects, textures, animations , etc ... to my scene.

* What happen to my fps?
* Could it attain zero? and
* If it attain zero, what is the meaning of a zero FPS (the hardware stopped working?!)?

# Answer
In general to calculate the FPS, you need the following:

* cn: counter of how many frames you've rendered
* time\_start: the time since you've started counting
* time\_now: the current time

To calculate the FPS, you simply evaluate this formula (all taken from this answer):

`FPS = cn / (time_now - time_start)`

One thing that often greatly influences the run-time and therefore the FPS is whether you are running a *debug* or *release* build. The debug builds are often slower by multiple order of magnitudes, since they contain a lot of additional information and checks that help with the debugging process while slowing the application down considerably.

---

*Regarding your concrete FPS quantity*: There is no way for us to tell whether that value is "ok" since it depends on so many factors that we don't know about, such as your system in general, the current resource usage by other processes / applications, etc.

Unity has a FPS limiter built in that ensures that the FPS do not cross a certain limit (and thus preserves computation power for other processes).

To disable it, put this somewhere in your script:

`Application.targetFrameRate = -1`

Additionally "vertical synchronization" (VSync) might be enabled which forces the GPU to only emit new frames as fast as the monitor can actually display them to the user (this basically locks the rendering frame rate to the monitor framerate). This sometimes can prevent "coil whines".

To check whether VSync is enabled in Unity go to:

> Edit → Project Settings → Quality

The default quality profile is "Good", so expand "Good" and set "VSYNC Count" to "Don't Sync" (source).

---

*In general*: For the human eye you need at the bare minimum 20 FPS to fool the brain into thinking that it sees a fluid motion. Usually 30 frames is considered enough for a smooth game. Everything above is basically luxury (= unused computation power) that could be put to use to render the scene in higher fidelity (= select higher quality settings in the game's configuration = better textures, better shaders, higher long-range visibility/more objects rendered).

The more elements you add to the scene (be it objects, more or higher-resolution textures, additional animations, shader effects, etc.), the longer your scene will take to render and the lower the FPS will get.

Theoretically you could reach 0 FPS, if your application stops rendering all together either because the software decides to (some games check if the game window has lost its focus and then stop rendering to preserve the computer power for other processes) or if there is really no computation power given to your application at all because all other processes have a higher priority and use up all resources.
> 4 votes

---
Tags: unity, optimization, frame-rate
---


title: Collision between player and heightmap

text:
# Question
Title: Collision between player and heightmap
Im programming a small project, an opengl height map. It is build of triangles, which points are fit to the right y position (read out of an image).

The player is represanted by a cuboid. (p1, p2, ... p8). now, i want to implement collision detection between the player and the heightmap.

I thought about split the whole world in cubes, and this cubes again in cubes, and then distribute the triangles of the heightmap in this cubes (then check for the big cube, the smaller cube, which contains the player, and then check all triangles for collision).

But which collision detection method would be the best here, and how could i implement it? (By the way, im using lwjgl \[java\])

# Answer
It may not be necessary to go the Quadtree route as you're suggesting. How about breaking the problem down into two parts:

1. Store the heightmap data in a 2D array so that nodes can be accessed with O(1) time complexity.
2. Decide how far apart each node is in world-space coordinates. E.g. The coordinate (64, 64) might correspond to the "terrain-space" coordinate (4, 4) if nodes are 16 units apart. So when you want to know the height at a particular coordinate, all you need to do is `heightMap[x>>4][z>>4]` for example.
3. For the spaces in between just use bilinear interpolation of the surrounding node heights (also just by getting them from your array; no need to reference them anywhere else).

Now you have a method that can quickly give you the interpolated height of your terrain under any given coordinate.

1. So now you take your player's position and cuboid, and for each point (x, y, z):
    * Sample your terrain height at (x, z).
    * If any of the player's vertices' y-coords are less than the terrain height, you know that your player is colliding and you also know how far in they're colliding. No need to test with individual triangles.

Of course you can still do bilinear interpolation with any other data structure you store your terrain heightmap in like a QuadTree if you're doing any LOD or frustum culling stuff but it would be slower. You might even deem is sufficient to simply test terrain height against the centre of your player and a fixed (or averaged) distance threshold for "player height".
> 1 votes

---
Tags: opengl, java, collision-detection, lwjgl, heightmap
---


# Question
Title: MonoGame - Get the 2D area of a 3D object
I'm writing a 2d game, but decided to make some 3d objects that my 2d character can pick up.

I've got them displaying on the screen - but can't work out how to get the 2d area that the 3d object is displayed at (so I can do 2d collision detection).

Here's the code that draws my 3D objects - I can see that there's a projection object and have been poking around in there. But no luck so far ...

```
    foreach (var mesh in Model.Meshes)
    {
        foreach (BasicEffect currentEffect in mesh.Effects)
        {
            currentEffect.EnableDefaultLighting();
            currentEffect.World = (transforms[mesh.ParentBone.Index] * GetMatrix());
            currentEffect.View = viewMatrix;
            currentEffect.Projection = projectionMatrix;

        }
        mesh.Draw();
    }

```

# Answer
> 1 votes
you could use a `BoundingSphere`, initialized with the mesh of your 3d object (see here how), and then use your it to collide in 2d environment.

# Answer
> 1 votes
There are roads to solving this you can go down, project the 3D geometry in 2 dimensions or project the 2D geometry into 3 dimensions. The later is far simpler as the former requires you to define a plane on which your sprites lie and then detect where each triangle defining the mesh intersects with that plane.

## 2D to 3D

Projecting the 2D geometry into 3 dimensions is fairly trivial. 2D geometry is, after all, just two triangles stuck together with one axis constrained to a constant value. So turn your sprites into a 3D quad of two triangles and use 3D collision detection techniques instead.

## 3D to 2D

Making 3D geometry into 2D requires you to project the geometry onto a plane. In this case the plane you need is the plane on which the 2D geometry lies.

It's probably and XY plane which intersects the origin so can be defined by the vectors (1, 0, 0) and (0, 1, 0) making the normal (0, 0, 1).

If you can define the plane you need, all you really have to do is to move each vertex along the plane's normal until it's at a point on the plane. If the plane above is correct, just set the z coordinate of every vertex to 0.

For a general plane you do this by finding the distance from the plane to the point then moving the point by that result. The distance should conform to the plane's normal. This question might help you do this.

Alternately use a projection matrix to do this operation. This is exactly what your rendering pipeline will do to project the 3D geometry into screen space (which is the camera's near clipping plane). Specifically, it multiplies each vertex by the world (to get it relative to the origin), view (to get that relative to the camera) and projection (to get it in screen space).

Once projected onto the plane you have to construct triangles from the points. This will depend on how the mesh is defined; i.e. does it use a triangle list/strip/fan or is there an index array?. Each of those triangles can then be used in your 2D collision detection.

You could also apply a convex hull algorithm 2d give you an acceptable shape to use (you might need to triangulate it first though)

*Note:* You might want to consider the plane in use as being the near clipping plane of the camera so the player collides exactly with the shape drawn to the screen. This could be achieved by multiplying the vertices by the world, view and then projection matrix as that's how you project them into screen space and you should already have that information defined somewhere.

**One more problem**

Projecting the 3D geometry in this way will probably suit, even if it is expensive. But, you might need to consider the case where the geometry drawn to the camera isn't what you'd want to collide with. For example, if it was some wheels on an axel you might want to collide only with the axel and not the wheel. Collapsing the geometry to the plane will meen you collide with the wheel.

To avoid this you would actually have to define a plane and find the geometry defined by the mesh intersecting the plane. However, I doubt this is what you want since generally in 2D games you collide with the edges of what you see or not at all (foreground/background items).

## Conclusion / Long story short

Create 2 3D triangles for the 2D resources or some better fitting collision mesh and just use 3D collision detection for these problems. It's the easiest way. If you really need it to be more 2D collision then project the 3D geometry onto the draw plane (probably done by just zeroing the z component or multiplying verts by world, view and projection matrices) and do 2D collision detection with the cloud of triangles that defines.

---
Tags: monogame
---


# Question
Title: Creating charging particles using Shuriken
I've been trying to create a charging effect using the Shuriken Particle system for the longest time, and I've had little to no luck with it. I've tried setting different curves for the Force over Time and Color over Time, but I always come up empty. However, I've seen examples all over the place for charging particles. The most recent example of charging particles I've seen is from the Space Cowboy game jam entry LOS CUERVOS.

The game has a ship with a laser that requires the player to hold a button down before it fires. It looks like this when charging and firing. I'm specifically talking about the particles surrounding the ball of light that's slowly growing in size over time.

I was wondering if anyone here knew what I may be doing wrong when going about setting up the particle system. Any suggestions relative to the question would be much appreciative.

# Answer
Just a few properties for that:

* **Shape**

+ Shape = Sphere
    + Emit from Shell = true
    + Radius = Whatever works for you
* **Particle System**

+ Start speed = -40
* **Size over Lifetime**
    + Curve = Something small to large

Note that the speed is negative. This will cause the particles emitted from the shell of the sphere to move inwards toward the center.

One thing you'll have to tweak here is making sure that the lifetime and speed of the particles and the size of sphere balances to make the particles end their life just at the center of the sphere.

A few minutes of tweaking resulted in this for me:
> 1 votes

---
Tags: unity, shuriken
---


# Question
Title: How is the environment moved in endless runner games like Tiny Wings
I've always wondered how the background scene is scrolled endlessly as the main player is moving (usually to the right). With Tiny Wings I suspect that it's somehow drawn dynamically because when investigated a little deeper, one can see that the hills can easily be drawn. All in all it's just some parabola shaped curves, some texture and mini sprites on them. In Cocos2D the hills themselves could be drawn by a very convenient class called CCRenderTexture. Of course this will involve some maths too, but that shouldn't be a problem. But how about a scene that I want to be composed of images but not easily drawable shapes?

1. Is this even done in practice?
2. Is it possible to dynamically customize the same images so that they look a bit different the next time they appear on the screen again?
3. How is smooth transition achieved between different images?
4. And finally how are the images swapped one after another?

For this game I'm going to be using Cocos2D V3.

# Answer
> 3 votes
Number 3 is easiest if you have an image that is tileable, meaning that if you put them next to each other you wouldn't be able to pick out the seam.

Then you can draw the same image twice once on `x,y` and once on `x+image.width,y`. each frame you decrement `x` until `x < -image.width` where you add `image.width` to it.

Adding details is easy by drawing some sprites after you draw the background and moving them at the same pace as the background.

# Answer
> 1 votes
> But how about a scene that I want to be composed of images but not easily drawable shapes?
>
> Is this even done in practice?

Yes and this is the more common by far too.

> Is it possible to dynamically customize the same images so that they look a bit different the next time they appear on the screen again?

In runtime? Possible but maybe not very commonplace unless the textures are simple. At the most you might find a tile type made up of a single "base" tile that is colorized to give it some variation. Games with scenes made up of tiles tend to store these variations in the map metadata. E.g. you might have a normal "grass" tile then a few pre-made variations of that that are placed from the start.

For games that use geometric shapes instead of textures or tiles, you're always at liberty to tweak color, scale and rotation of course. In fact, often times these parameters are randomly generated. In the same way, a cloudscape can also just be randomly generated noise.

> How is smooth transition achieved between different images?

They're made in such a way that they can tile.

> And finally how are the images swapped one after another?

On a small scale, they're simply translated. More practically, your scene's camera is the one that's moving and these images are simply rendered at their set positions.

On a medium scale, you do something called "Frustum Culling" where you only draw images/tiles that are completely or partially within your viewport. The rest of the scene may be loaded in RAM but you only draw the parts that the user sees so it doesn't lag by drawing a million things. When the camera pans far enough, you draw a different set of tiles.

On a large scale, you can save parts of the scene in files and only have "chunks" loaded that are close enough to where the player/camera is for them to actually be useful. When you move enough, you can load more chunks and free the ones you've moved away from from memory.

---
Tags: cocos2d, scene
---


# Question
Title: Why are my sprite outlines partially rendering in the wrong place?
I've been trying to draw an outline around a sprite using the code from this answer.

# Details

My sprite is called `Ship2Sprite`.

This is how I create the rectangle:

```
 rectangle = New Rectangle(backgroundPos.X + NPCAI.enemyPosistion.X,
                           backgroundPos.Y + NPCAI.enemyPosistion.Y,
                           Ship2Sprite.Width, Ship2Sprite.Height)

```

This is how it looks without any rectangle drawn:

If I use this line of code

```
hudSpriteBatch.Draw(t, rectangle, New Rectangle(0, 0, 0, 0), Color.Red,
                    NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)

```

the following is the result in game

```
hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, 2, rectangle.Height), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)
hudSpriteBatch.Draw(t, New Rectangle(rectangle.Right, rectangle.Top, 2, rectangle.Width), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)
hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Top, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)
hudSpriteBatch.Draw(t, New Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, 2), New Rectangle(0, 0, 0, 0), Color.White, NPCAI.enemyAngle, New Vector2(0, 0), SpriteEffects.None, 0)

```

However, when trying to use the code from the linked answer, this is the result:

The first and third lines produce the correct lines, however the other 2 are in the correct orientation but not the correct position

Am I missing something somewhere?

**EDIT**

Based on Blau's answer, I have updated my code to this:

```
 Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice)

    Dim spriteBatch1 As New SpriteBatch(graphics)
    Dim rectangle As New Rectangle(Game.backgroundPos.X + pos.X, Game.backgroundPos.Y + pos.Y, sprite.Width, sprite.Height)
    Dim w = rectangle.Width
    Dim h = rectangle.Height
    Dim x = rectangle.X + w / 2
    Dim y = rectangle.Y + h / 2
    Dim transform As Matrix = Matrix.CreateRotationZ(NPCAI.enemyAngle) * Matrix.CreateTranslation(x, y, 0)

    spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform)
    x = -w / 2
    y = -h / 2

    spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y + h - 2, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x + w - 2, y, 2, h), Nothing, Color.White)
    spriteBatch1.End()

End Sub

```

However the rectangle is rendering in the wrong position, which is slightly ahead of the sprite. Like this

**EDIT 2, with the following code**

```
 Public Shared Sub DrawOutline(ByVal t As Texture2D, ByVal sprite As Texture2D, ByVal pos As Vector2, ByVal graphics As GraphicsDevice, ByVal angle As Single)

    Dim spriteBatch1 = New SpriteBatch(graphics)
    Dim rectangle As New Rectangle(Game.backgroundPos.X + pos.X, Game.backgroundPos.Y + pos.Y, sprite.Width, sprite.Height)
    Dim w = rectangle.Width
    Dim h = rectangle.Height
    Dim x = rectangle.X + w / 128
    Dim y = rectangle.Y + h / 128

    Dim transform As Matrix = Matrix.CreateRotationZ(angle) * Matrix.CreateTranslation(x, y, 0)

    spriteBatch1.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Nothing, Nothing, Nothing, Nothing, transform)
    x = -w / 128
    y = -h / 128
    ' spriteBatch1.Draw(t, rectangle, Color.Red)
    spriteBatch1.Draw(t, New Rectangle(x, y, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y + h - 2, w, 2), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x, y, 2, h), Nothing, Color.White)
    spriteBatch1.Draw(t, New Rectangle(x + w - 2, y, 2, h), Nothing, Color.White)
    spriteBatch1.End()

End Sub

```

# Answer
Pixel color addresing is bad, it will work on a square but not on a rectangle.

Change this:

```
 colors[ x * texture.Width + y ] = borderColor;
 colors[ x * texture.Height + y ] = Color.Transparent;

```

To this:

```
 colors[ x + texture.Width * y ] = borderColor;
 colors[ x + texture.Width * y ] = Color.Transparent;

```

EDIT: If you are using the other method, your problem is the rotation

You have to use a transform matrix and generate the rectangle based in (0,0) as origin.

```
var w = rectangle.Width;
var h = rectangle.Height;
var x = rectangle.X + w/2;
var y = rectangle.Y + h/2;
Matrix transform = Matrix.CreateRotationZ(NPCAI.enemyAngle) * Matrix.CreateTranslation(x,y,0);

husSpriteBatch.Begin(,.,..., transform);
x = -w/2;
y = -h/2;
hudSpriteBatch.Draw(t, new Rectangle(x, y, w, 2), null, Color.White);
hudSpriteBatch.Draw(t, new Rectangle(x, y+h-2, w, 2), null, Color.White);
hudSpriteBatch.Draw(t, new Rectangle(x, y, 2, h), null, Color.White);
hudSpriteBatch.Draw(t, new Rectangle(x+w-2, y, 2, h), null, Color.White);

husSpriteBatch.end();

```
> 2 votes

---
Tags: xna, rendering, sprites
---


title: LibGDX ImageButton resizeing

text:
# Question
Title: LibGDX ImageButton resizeing
How can I resize ImageButton ? It show very big on screen . How I know it is an Actor and it is not resizing automatically . I can\`t find the method for resizing it. Any ideas?

# Answer
> 3 votes
Put your ImageButton in a table. Set the size of it. Add the table as an actor in your stage.

Here is an example:

```
ImageButton. ImageButton Style btnStyle new ImageButton.ImageButtonStyle ();
btnStyle.up = skin.getDrawable ("your image");

btnB = new ImageButton (btnStyle);

stage.addActor ( table );

table.add (btnB).size (150, 200);

```

---
Tags: libgdx
---


# Question
Title: Inventory management syncronized network
I'm implementing an inventory system with items in 1x1 slots in a open-world multiplayer game. But I can't decide how I want to synchronize the item management with the server. I see two options here.

1. ***Server and client are fully synced after every move.*** Synchronize every action the player takes in their inventory, even the action of "lifting" items.
2. ***Server only syncs "when neccessary"*** An unordered list on the server keeeping track of WHAT items the player has and not WHERE (in what slot) they are. Then every time the player drops/uses/acquires or stacks/unstacks an item the client syncs their inventory including slot positions with the server.

Is there perhaps another option that's even better?

# Answer
> 3 votes
It really depends on your game, but three considerations you need to keep in mind are:

1. Does the positioning in the inventory have any game-mechanical effect? When it does, you need to handle the inventory positions server-sided.
2. When the player organizes their inventory how they see fit, logs out and back in again, their inventory will be a mess again. You could prevent this by storing the order on the client. But what if the player regularly accesses their account from different machines?
3. Is there a limitation of inventory slots? When there is, item stack splitting and merging becomes a game mechanic, so you won't get around handling it server-sided.

However, when the player does a drag&drop, I would not recommend you to remove the item when they start dragging and put it back when they stop. There is a high risk that when a bug occurs while the user is dragging that the dragged item could get lost. There are also mechanical problems which might get hard to solve. What would happen, for example, when the player starts dragging an item, receives a new item while dragging which occupies the slot the item came from and then drops the first item at an invalid location? You can't revert it, because that would overwrite the new item.

Instead, wait for the player to drop the item, check where they dropped it, check if it's valid and then perform the swap-operation. While the user is dragging, the item still occupies the same place.

---
Tags: xna, networking, monogame, .net, synchronization
---


# Question
Title: How do I make a 2D game resolution independent?
I'm working on a simple 2D game. I've finished the mobile phone version.

However, my boss wants the game to works on his RT. I'm doing the "conversion" but my buttons are in the wrong places, because I hard-coded the screen size, like this:

```
 texture = game.Content.Load<Texture2D>("StartScreen");
 mainFrame = new Rectangle(0, 0, game.GraphicsDevice.Viewport.Width, game.GraphicsDevice.Viewport.Height);

 // button definitions
 startbrect = new Rectangle(300, 258, 88, 88);
 startbtext = game.Content.Load<Texture2D>("bplay");

```

In this example, `mainframe` is fine, but `startbrect` isn't, because I defined the size to match a Windows phone's screen. How can I handle responsive design when all Windows 8 phones' screens are different? Is there a formula or macro to calculate each time the good size?

# Answer
I use a reference screen size, and scale everything according to it, while keeping the ratio of everything the same.

```
private static float CalcRatio(Vector2 Sizes)
{
    return Sizes.y/Sizes.x;
}

public static Vector2 CalculateNewPos(Vector2 RefPos, Vector2 RefScreenSize,
                                      Vector2 CurrentScreenSize)
{
    return new Vector2((RefPos.x/RefScreenSize.x) * CurrentScreenSize.x,
                       (RefPos.y/RefScreenSize.y) * CurrentScreenSize.y);
}

public static Vector2 CalculateNewSize(Vector2 RefSize, Vector2 RefScreenSize,
                                       Vector2 CurrentScreenSize)
{
    float origRatio = CalcRatio(RefSize);
    float perW = RefSize.x * 100f / RefScreenSize.x;
    float newW = perW / 100f * CurrentScreenSize.x;
    float newH = newW * origRatio;
    return new Vector2(newW, newH);
}

```

To make sure the game looks good on resolutions with ratios substantially different from your reference resolution's, define a "playable area", that fits into any kind of screen, and put all of the gameplay critical visuals there. Fill everything outside of it with background. Usually, my reference playable area is as big as the reference screen size itself.

On portrait orientations, I calculate the (new) playable area so that the screen is filled vertically, and the space it takes horizontally is just as big as it is required to keep the ratio. On landscape orientations, I fill the screen horizontally, and keep the ratio when setting the vertical size.

For more, see http://en.wikipedia.org/wiki/Safe\_area\_(television) as it's a similar, if not identical, concept.
> 18 votes

# Answer
I think the easiest and most natural approach to resolution independent layouts is a relative (percentage) scheme. So from the start do not work with the real resolution but only in a uniform \[0,1\]x\[0,1\] square wherever possible.

That means that for a given `screen_size` and a given `object_size` and a given relative position `(px, py)` (for example (0.5, 0.5) for the center of the screen), the upper, left corner of the object is calculated by:

```
x = px * screen_size.width - 0.5 * object_size.width
y = py * screen_size.height - 0.5 * object_size.height

```

The idea should be clear. A ready abstraction would be

```
x = cx1 * screen_size.width + cx2 * object_size.width + cx3
y = cy1 * screen_size.height + cy2 * object_size.height + cy3

```

and every position is defined then by `(cxi, cyi)`. By this one could place objects in corners with or without borders, etc.

Please make sure that the single elements size (buttons, labels, ...) are scaled too.
> 0 votes

# Answer
Specialy for MonoGame i have platform independent solution for this problem called IRR (Independent Resolution Renderer). It has very simple usage:

1. Create IRR in **Initialize()** method

\_irr = new ResolutionRenderer(this, VirtualResolutionWidth, VirtualResolutionHeight, \_gfx.PreferredBackBufferWidth, \_gfx.PreferredBackBufferHeight);
2. Call **\_irr.Draw()** each cycle in **Draw()** call
3. Supply **\_irr.GetTransformationMatrix()** in any **SpriteBatch.Begin()** call you want to use IRR.

Description is here: http://panthernet.ru/forum/index.php?/topic/17-monogamexna-examples-v14/?p=44

Code is here: https://github.com/panthernet/Monogame-Examples
> -2 votes

---
Tags: c#, 2d, resolution
---


title: How to lock and unlock game levels?

text:
# Question
Title: How to lock and unlock game levels?
In my level menu (I'm using libGDX), I would like to lock and unlock game levels.

The idea is that after finishing the previous level, the player is allowed to tackle the next one.

Can someone point me to an example?

# Answer
From my point of view, this question is unrelated to libGDX in its core. Implementing this is a matter of your own application logic. Somewhere you need to store the progress of the player and based on those values, determine which levels are available. Based on your target platform different best practices on how best store data are available.

If you definitely want libGDX to take care of that, one option would be to use the Preference interface of libGDX.

Some links that might help:

Whether a level is available or not, should then be made visually clear to the player, e. g. via different colours:

* Level icons/images/etc. that are available could be coloured.
* Unavailable ones only be displayed in gray scale.

This can even be combined with an green "ok" sign and a red crossed sign to make it even easier for the user to distinguish the two states.
> 1 votes

---
Tags: menu, gui
---


# Question
Title: Computing Field-of-View from window dimensions
I'm looking into computing the vertical Field-of-View (FOVy) based on the projection parameters of my camera. From this source, I've found an equation that seems to work.

```
float FOVyForProjection(const float height, const float nearClip, const float farClip)
{
    // From http://paulbourke.net/miscellaneous/lens/
    //
    // vertical_field_of_view = 2 atan(0.5 height / focal_length)
    //
    const float focalLength = (farClip - nearClip);
    const float fovy = 2.0f * std::atan((height * 0.5f) / focalLength);
    return (fovy);
}

```

However, the author of the last link is talking about actual cameras and lenses, measured in millimeters, so I'm not sure if my interpretation is valid. Is the above function correctly computing the y-FOV based on the window height and near/far planes?

For a `768 height` and `far plane = 1000` it is giving a `~42 degrees` FOV, which seems a bit low.

```
std::cout << "FOV = " << RadToDeg( FOVyForProjection( 768, 0.1f, 1000.f ) ) << std::endl;
// prints: FOV = 42.0174

```

# Answer
I don't believe your second link's analysis works for a projection matrix FoV.

In that link, the angle of the field of view is centered on the middle of the lens. The 'camera' with a perspective matrix is actually located behind the near plane. So the distance between the near plane and the far plane being used as one component of the atan calculation will be incorrect (only off by 0.1 in this case, but still). The correct distance would be the distance between the far plane and the camera, which is just your value *farClip*.

Also, you don't *need* to calculate Field of View based on dimensions if you don't want to. You can also just use a desired field of view in your perspective matrix calculations. As long as your aspect ratio value is correct, the image will still look okay (for reasonable FoVs).

http://ogldev.atspace.co.uk/www/tutorial12/tutorial12.html

This guide shows how to create a perspective matrix that utilizes a custom FoV and also takes into account aspect ratio.
> 2 votes

---
Tags: c++, mathematics, camera, projection
---


title: OpenGL Compute Shader Uniforms

text:
# Question
Title: OpenGL Compute Shader Uniforms
I am trying to use a compute shader to generate some data in a texture. My compute shader looks something like this:

```
#version 430
//uniform int u_CurrentMipSize;
const int u_CurrentMipSize = 1024;
layout( r16f ) uniform writeonly image2D u_densityTexture;

bool ContributesSignificantDensity( ivec2 uv )
{
    return uv.x >= ( u_CurrentMipSize / 8 ) && uv.y >= ( u_CurrentMipSize / 8 );
}

//.... in main()
if( ContributesSignificantDensity( targetPosition ) )
{
    imageStore( u_densityTexture, targetPosition, vec4( 1.0 ) );
}
else
{
    imageStore( u_densityTexture, targetPosition, vec4( 0.0 ) );
}

```

And the calling code looks like this:

```
glUseProgram( m_DensityGenShader );

glMemoryBarrier( GL_SHADER_IMAGE_ACCESS_BARRIER_BIT );

uniform_loc = glGetUniformLocation( m_DensityGenShader, "u_densityTexture" );
if( uniform_loc != unsigned int( -1 ) )
{
    glBindImageTexture( uniform_loc, m_DensityTexture, 0, false, 0, GL_WRITE_ONLY, GL_R16F );
}
checkOpenGLErrors( "Density Texture Compute Shader" );

uniform_loc = glGetUniformLocation( m_DensityGenShader, "u_CurrentMipSize" );
if( uniform_loc != unsigned int( -1 ) )
{
    glUniform1i( uniform_loc, 1024 );
}
checkOpenGLErrors( "Density Texture Compute Shader" );

int num_to_compute = mip_sizes[ i ] / 16;
glDispatchCompute( num_to_compute, num_to_compute, 1);
checkOpenGLErrors( "Density Texture Compute Shader" );

glMemoryBarrier( GL_SHADER_ACCESS_BARRIER_BIT );

```

If I use this code, the program executes correctly on my texture of size 1024. I am just storing this result in an image2D. If I use a const float the program executes correctly, and I get a red square in the upper right 7/8ths of the image. (Just rendering this texture onto a quad in another shader). Texture rendered on quad- yay red!

However, if I change the top of my shader to the following by using a uniform instead of a const float:

```
uniform int u_CurrentMipSize;
//const float u_CurrentMipSize = 1024;

```

Then the output texture is just garbage, random data: Texture rendered on quad- boo noise!

I'm always sending the uniform from the compiled code (if I get a valid uniform location back from opengl) so the only thing that changed is reading the value from a uniform vs a const float.

Should I be doing something differently with this because it's a compute shader? I've never had issues passing uniform data with vert/frag/geometry shaders?

I had a similar issue trying to do imageLoad operations, so I think I'm not setting up stuff with my compute shader correctly, but it works in the constant hard-coded case, so I'm not sure.

This is my first forray into compute shaders- I've worked with CUDA a bit so I'm familiar with the paradigms, but not sure how to debug if the kernel is crashing or abandoning early or corrupting the texture somehow or what?

# Answer
> 4 votes
I'm not sure why this fixed it, but apparently setting the uniform layout location works:

Compute

```
    layout( location=1 ) uniform unsigned int u_CurrentMipSize;

```

C++:

```
    glUniform1ui( 1, mip_sizes[ i ] );

```

I had these other uniforms in my compute shader:

```
    layout( r16f ) uniform writeonly image2D u_densityTexture;
    layout( r16f ) uniform readonly image2D u_densityTexturePrevLevel;

```

So maybe mixing uniforms with a *layout* qualifier and those without caused the issue? I'm not sure.

---
Tags: opengl
---


title: Disable lighting in DirectX10

text:
# Question
Title: Disable lighting in DirectX10
I'm implementing a D3D10 version of my renderer (not porting to avoid losing Windows XP support). I didn't go straight to D3D11 because MSDN and other sources recommend upgrading to 10 and then to 11.

From what I've read so far, what used to be done with `IDirect3D9::SetRenderState` is done in D3D10 with `ID3D10RasterizerState`, `ID3D10BlendState` and `ID3D10DepthStencilState`. You declare and fill a descriptor structure, tell the device to create a state object, and then bind it to the device. For example:

```
//D3D9
m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );

//D3D10
//This defines the ID3D10RasterizerStatePtr type used below
_COM_SMARTPTR_TYPEDEF(ID3D10RasterizerState, __uuidof(ID3D10RasterizerState) );
//...
ID3D10RasterizerStatePtr pRasterState;
D3D10_RASTERIZER_DESC rasterDesc;
rasterDesc.CullMode = D3D10_CULL_NONE;
if( !CheckErrorCode( m_pImpl->pDevice->CreateRasterizerState( &rasterDesc, &pRasterState ), "InitDevice", "CreateRasterizerState" ) )
    return false;
m_pImpl->pDevice->RSSetState( pRasterState );

```

However, now that I have to "port" the line...

```
 m_pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );

```

... I cannot find a related property in any of the descriptors. From what I've seen, most examples implement lighting in HLSL, so perhaps I don't need to explicitly disable lighting, because my shaders don't do it?

This is a desktop app, no fancy Metro stuff. Using unmanaged C++.

# Answer
Direct3D 10.x and Direct3D 11.x do not support the 'legacy fixed-function' pipeline that your Direct3D 9 code is using. Preparing to move to Direct3D 10 or 11 means eliminating all fixed-function usage and moving to programmable shaders.

It is also apparent from your code snippet that you are not using the state objects correctly. In Direct3D 9, you set hundreds of individual settings. In Direct3D 10 and Direct3D 11, you manage all state through a few objects and a few simple individual switches such as primitive topology.

You have really need to take a step back and understand the major shifts in technology here. All fixed-function rendering needs to be replaced with programmable shaders, state management needs to be changed from a 'lazy-evaluation 'model to a 'known groups' model. In other words, you cannot meanigfully translate the single line: `m_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );` by itself to Direct3D 10.x or 11.x. You need to know the state it is grouped with and how you are using them *all* together to render your scene.

```
ID3D10RasterizerStatePtr pRasterState;
D3D10_RASTERIZER_DESC rasterDesc;
rasterDesc.CullMode = D3D10_CULL_NONE;
if( !CheckErrorCode( m_pImpl->pDevice->CreateRasterizerState( &rasterDesc, &pRasterState ), "InitDevice", "CreateRasterizerState" ) )
    return false;

```

This code will always fail because you did not fully initialize the rasterizer state object which also sets fill mode, winding mode, depth bias/clamp, depth clipping, scissors, and MSAA line AA modes all together. And once you create that state object, it is immutable. To change any setting in that object, you create a new one with all the states specified.

The DirectX Tool Kit for Direct3D 11 provides a lot of basic functionality that you may find useful for replacing old D3DX9 and concepts like "Draw\*UP", common used state object combinations, and a bunch of stock programmable shaders you can start learning from. Take some time to really learn the Direct3D 11 API basics before jumping into a porting job for an old codebase that is not even really up to the programmable shader model for Direct3D 9.0 (circa 2004).

Start with the resources at Getting Started with Direct3D 11 and the samples on MSDN Code Gallery. When you've got a good understanding of how to program for Direct3D 11, then take a look at the seminal 'porting from Direct3D 9' presentation Windows to Reality: Getting the Most out of Direct3D 10 Graphics in Your Games. All those recommendations would apply to moving from Direct3D 9 to Direct3D 11.x as well.
> 3 votes

# Answer
You're right, there is no lighting in D3D10 unless you implement it yourself in shaders.
> 1 votes

---
Tags: c++, lighting, directx10, porting
---


# Question
Title: How to encode game files or pack to one file like game_data.dat
I am a beginner C++ programmer. I am creating a custom Open Tibia Server and I use the alternative Tibia client (OTClient).

I want encode game files (image, sound, lua, etc.) or pack all files into one. Can anyone help me with this?

# Answer
> 1 votes
There are already multiple similar questions, that should give you some pointers to get stared:

One option is to use an archiving tool to pack all game assets into an archive and encrypt it with a key. Then in your application use a library such as "zlib" to load and decrypt the contents from that archive.

From a security standpoint, those contents could of course still get extracted, if someone manages to get the key from your application. But there are some tricks around to make that harder, e. g. by not storing to complete key string in one place in your application.

You of course also need to be aware, that those packing approaches also have some drawbacks, e. g. when you later want to replace a single asset file in an patch, you either need to ship again the complete game data archive again or create some sort of intelligent updater tool, that can add/remove/edit assets within your game data archive file.

---
Tags: c++, server, assets, file
---


title: Not able to destroy the prefab

text:
# Question
Title: Not able to destroy the prefab
In the code, everything is working smoothly, only problem I am facing is that the `Destroy(fuelprefabInstance)` is not getting Destroyed in `OnTriggerEnter` Method though the print statements are clearly executed and Destroy in `Spawn` method works fine as well. What am I missing?

Edit: It infact gives `NullReferenceException` if I try to set `fuelprefabInstance` to `false` instead of destroying the prefab using `fuelprefabintsnace.setActive(false);`

```
  public IEnumerator Spawn()
    {
        time1 = Random.Range (1, 5);
        spawning = true;
        timer = 0;
        initial = new Vector3 (Random.Range(rmin, rmax), 0.037f, Random.Range((-7.608864f + 10f),(r.renderer.bounds.max.z + 20)));
        fuelprefabInstance = (GameObject)Instantiate (fuelprefab, initial, transform.rotation);
        yield return new WaitForSeconds (time1);
        spawning = false;
        Destroy (fuelprefabInstance, time1);  //this destroy works
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            print("called");
           Destroy (fuelprefabInstance);     //this Doesnot
            print ("destroyed");
                }
    }

```

# Answer
Comment out the destroy function while you spawn and give it a try. Most likely the object gets destroyed before it even collides with the player. The prefab becomes null and throws the exception.
> 0 votes

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


# Question
Title: Can an individual apple developer account have your own name/studio's name?
I just purchased the iOS developer program for $99. It said on the website that the sellers name would be your name. I think Ketchapp (the creator of 2048) also uses individual. So are you allowed to use a name you created yourself to be your individual account's name? Thanks in advance!

# Answer
This is my *personal experience* from having set up and used two different developer programs over the last few years. As such, there may be a way to work around the things I state below, but I have not found them.

**Look at the bottom for a tl;dr.**

When I enrolled in a Personal Developer Program in June 2011, for my personal App Business Street Samurai Studios, I was allowed to set a Developer Name that would appear in the App store and I put in "Street Samurai Studios". I was also given notice that I would not be able to (ever) change the name once I had put it in.

Now, when it was time to start up my second business venture, in August 2013, me and my Co-Founders decided to start out with a personal developer account until we had registered our business properly. Once enrolled I assumed I would be given the same option to put in a Developer Name, but I was not. As such, we had to go with the First and Last name of the person who registered the account (me), until we migrated it into a Business Developer Account.

I was in contact with Apple via phone to ask them for assistance and was told that the aforementioned option HAD been available before, but was withdrawn some time ago. However, account that had already been set up with this option (e.g. my first one and, we assume, KetchApps) were allowed to keep the Developer Names.

One thing that might work, though I'm not sure it's possible, or allowed, is to set up a new Apple Account with your studio name as the First and Last name of the Account. Like I said, I'm not sure this is possible or allowed, but it might be worth a shot.

**TL;DR;** 1. No, you cannot provide a developer name other than the First and Last name registered with the Apple Account. 2. You could before, hence KetchApps name, but not anymore. 3. You could try registering a new Apple Account with your developer name as First and Last name, but I do not know if this works, or if it's allowed by Apple.
> 1 votes

---
Tags: appstore
---


# Question
Title: Desaturate texture using mask in OpenGL 2
I have a very large texture i am using as background and i want to apply a filter to a small part of it, the "small part" is defined by the alpha layer of another texture i have (which is still RGB8888), i am not sure what's the best approach to do this. I'd like to keep the same (very simple) shader i am already using for other sprites, which is similar to the basic one, i.e.:

```
precision mediump float;
uniform sampler2D uTexture;
varying vec2 vTexPos;
void main() {
  gl_FragColor = texture2D(uTexture, vTexPos);
}

```

So, i have some questions

* How can i apply my filter only to "masked" region and avoid drawing others?
* Do i have any performance loss if i draw the big texture again once loaded to just apply it to a small portion of the screen?
* Can i map a second texture to the shader and use something like "if uTexture2 != null" -\> apply as mask? Will this give me any performance gain compared to using a second shader?
* Both textures are premultiplied, how should i handle alpha masking?

What id like to do is something like this (original, mask, result):

My environment is Android 4.0, im using GLES20.

# Answer
> 3 votes
I'd go for a second shader that accepts two textures and does the desaturation. Performance loss will be minimal.

```
uniform sampler2D tex;
uniform sampler2D texA;

void main()
{
    vec4 texelColor = texture2D(tex, gl_TexCoord[0].xy);
    vec4 maskColor = texture2D(texA, gl_TexCoord[1].xy);

    vec4 desatColor = texelColor * vec4(0.3, 0.59, 0.11, 1.0); // Weightened greyscaling
    float luminance = desatColor.r + desatColor.g + desatColor.b;
    desatColor = vec4(luminance, luminance, luminance, texelColor.a);
    gl_FragColor = mix(texelColor, desatColor, maskColor.a);
}

```

---
Tags: android, textures, shaders, opengl-es2, masking
---


# Question
Title: Manage game objects depending on visibility
I'm trying to create an adventure game in 2D and I'm thinking about map management/objects.

Here is what I've got in mind in terms of modelling:

Now, I would like to create entities based on player's position, to avoid high memory and CPU load.

The goal is to have objects removed from memory when they are out of screen and far from the character (for the moment, I'm thinking about something like twice the viewport):

Here is a picture showing that:

*Note*: red spots in the image are entities.

What do you thing about that? Is there is a better technique?

# Answer
> 1 votes
Your idea is correct, only render and update entities near the player for better performance.

To do this in a efficient manner, you will need some sort of spatial partition to know what is near the camera. You definitely don't want to loop through all the entities on your map.

One of the most efficient ways to use is a hash table, also known as a grid. But if your map is too large, a quadtree would be more efficient.

Both uses the same basic idea, divide the map in cells. Each cells contains all the entities in that specific area. So instead of looping all entities you just loop through the entities contained in the cells that are around you camera.

As a bonus you can use this spatial partition to help with you collision tests, testing only what can possible collide (in the same cell).

# Answer
> 0 votes
If I understood the problem correctly it's not that hard to solve. You track the position of every entities and update/render them only if they are inside or near the view field. The other way round you can of course destroy them if they are outside the view frustum (if you want that).

Just loop through the container and check x and y coordinates and compare it with the view frustum.

---
Tags: architecture, level-design, memory-efficiency, gameobject
---


# Question
Title: Procedurally Generated Top View 2D RPG Map Generation
Procedural generation is a fascinating concept and is gaining popularity in the gaming industry. The thought of playing a game that has new content every-time the game is played is very exciting to me.

My question is how would I go about generating top view 2D maps with the appropriate transition tiles?

I know how to create top view maps with stand alone tiles. For example I can generate a procedural map with grass and trees. However I can not generate forests of different sizes and shapes. How do I know which forest sprite to put where? I'm trying to loop over the map tiles and accessing the surrounding tiles to pick which tile is the appropriate one. However wouldn't this approach lead to error in which forest tile is placed where? The computer would have to know the size of the forest and how the forest is shaped.

The problem seems too complex for me. Any ideas on how to break this problem down would be much appreciated or if you just want to talk about procedural generation I'm game for that too.

So far I've generated a forest but I'm having trouble making it look right. Here is what I have so far. https://76295db93db3812642fa5ba984c042fa81ffc37c.googledrive.com/host/0B6H3TRExU5M9eEkyd2FreHhiNlU/

# Answer
The question appears to be about how to go about selecting the correct tiles *after* generating a map, so that is what I'll answer.

**What you are talking about is called "autotiling" or "auto tiling" (depending on who you ask).**

Here's a simple-ish method for handling that:

Given a single tile, we can find it's neighbors. Each tile then has a 4 bit state for the edges and a 4 bit state for the corners, giving us a total of 256 states per tile. Given the images provided, we can assume that we only need to care about the edge neighbors of each tile:

```
.#.
#X#
.#.

```

For the sake of sanity, we'll also assume that tiles either transition with only 1 other tile type (e.g. `trees -> grass`), or that tiles contain transparency and are layered on top of other tile types.

There will then need to be 16 different images for each tile, one for each neighbor state:

```
e.g.
0: ... 1: .#. 2: ... 3: .#. etc.
   .X.    .X.    .X#    .X#
   ...    ...    ...    ...

```

To determine which image is needed, you only need to iterate over the map once after generating to determine which tile to render. This shouldn't be to expensive to do at run-time, or you can pre-process the map if needed.

If you pre-process the map, you should probably make a separate map in which to store your actual renderable tiles instead of editing the existing map in-place. This will make it simpler to process and not introduce any errors that can come of changing the tile types while processing.

**Update:** Simple live example below:

```
var canvas = document.getElementById('canv');
var ctx = canvas.getContext('2d');

var map = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 1, 1, 1, 1, 1, 1, 1, 0, 0,
  0, 1, 1, 0, 1, 1, 0, 0, 0, 0,
  0, 1, 1, 0, 1, 0, 0, 1, 1, 0,
  0, 1, 1, 1, 1, 1, 0, 0, 0, 0,
  0, 0, 1, 0, 1, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
  0, 1, 0, 0, 1, 1, 1, 1, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0
]
var tiles = new Image();
tiles.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKoAAAAKCAYAAAAkasVsAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAAADxSURBVFhH7ZfBCcJQEESNZQhe9CJiJSrYjUXYjaBWIuJFL4JtKF/54ikzg5/sByfXTGZn398kbLO/Dx894loMboTqLZlf1q3aw3hDezF+SaN41pwPZSvdaz4Ill9UvkYZVBQyN1tKlw8F+bG6yHzMm5nyleqVqadqIvP11bDWm0AEAQ9qBHXXlAl4UGVkfiCCgAc1grprygSkZUp27/gBtIhELlPsVt0xsk85xI5dWBWd0qs0qKPtstX7utq97pfSJa/kifyyDsGOHNTz8QTPRemVYQILfgkmsymUe+uHiCz4dwLSF7V2WDV/Uf3r/216nslTmhyOBL3DAAAAAElFTkSuQmCC';

var mTemp = [];
for (var i = 0; i < map.length; i++)
  mTemp.push(0);

for (var y = 0; y < 10; y++) {
  for (var x = 0; x < 10; x++) {
    if (map[y * 10 + x] == 1) {
      var val = 0;
      if (y > 0 && map[(y - 1) * 10 + x] == 1)
        val |= 1;
      if (x < 9 && map[y * 10 + x + 1] == 1)
        val |= 2;
      if (y < 9 && map[(y + 1) * 10 + x] == 1)
        val |= 4;
      if (x > 0 && map[y * 10 + x - 1] == 1)
        val |= 8;

      mTemp[y * 10 + x] = val + 1;
    } else
      mTemp[y * 10 + x] = map[y * 10 + x];
  }
}

for (var y = 0; y < 10; y++) {
  for (var x = 0; x < 10; x++) {
    var tile = mTemp[y * 10 + x];
    ctx.drawImage(tiles, tile * 10, 0, 10, 10,
      x * 10, y * 10, 10, 10);
  }
}
```

```
<canvas id="canv" width="100" height="100"></canvas>
```
> 2 votes

# Answer
For random tile generation, using a cellular automata algorithm is a good approach.

http://www.roguebasin.com/index.php?title=Cellular\_Automata\_Method\_for\_Generating\_Random\_Cave-Like\_Levels

This is a good tutorial on the basic idea. Essentially you have some some random (or noise) function that generates initial tiles. Then the process gradually groups similar areas together, which can give you nice looking "random" shapes.

You could do this with more than just binary values to achieve more complex tiled worlds.
> 0 votes

# Answer
A common technique is to construct your maps from premade sections of n\*n tiles which can fit together in different ways ("super-tiles" if you would like to call them that way). My favorite example for this is the good old X-COM: UFO Defense. They become very visible on the overview map, especially in the "farmland" biomes:

When you want your map to be easily navigable (player can move from any supertile to any adjacent supertile), you need to make sure that there is a section at both the north/south and the east/west border of every supertile which must not be blocked on any supertile so players can always move between them. X-com solved this on Farmland biomes by having every tile being completely open to the south and east, which allowed to place the exit to the north and west whereever they want.

When you want your maps to be more labyrinth-like (the player can only move between some adjacent supertiles), you need to create different supertiles for dead ends, straights, curves, t-junctions and crossing sections. At a bare minimum you need:

* 4 dead-ends (entered from south, west, north and east)
* 2 straights (horizontal and vertical)
* 4 curves
* 4 t-junctions
* 1 crossing

With just one of each of these 15 basic supertiles you can already create quite intereting maps using a standard maze generation algorithm. But when you want even more variety, you can create multiple alternative versions of each of these 15 basic tiles. As long as they all fulfill the contract of having the opening at the same place, they will be interchangeable. Here are some examples of north-east curves which all fulfill the same function and should be interchangeable without affecting the playability of the map:

```
### ###   ### ###   ### ###   ### ###
### ###   #     #   ###  ##   ##  ###
###       #         ####      #   #
#######   ##    #   #######   ###   #
#######   #######   #######   #######

```

To make these more interesting, super-tiles can also have randomized internal variations in form of features which only have a small chance to appear on each supertile as long as these do not interfere with how the supertile can be navigated. A room supertile in a dungeon, for example, could have a 50% chance each of having a chest in the upper-right corner, a bookshelf in the upper left, a weapon rack in the lower right and a table in the lower left. This already gives you 16 different supertiles for the price of one.
> 0 votes

---
Tags: 2d, javascript, procedural-generation, html-canvas, rpg
---


# Question
Title: Calculate an approximate distance between two rigid bodies or OOB
Is there any easy way to get an approximate distance between two OOB?

I searched around and people talk about GJK algorithm, however I don't see it returning the distance between two convex objects even they are not colliding.

I don't need to be exact but just sphere checking is not acceptable in my case. Any ideas?

# Answer
I take that you meant OBB. (Oriented bounding box)

For an approximate distance calculate it as an AABB.

For an exact distance you can use the Separation Axis Theorem or the Minkowski Difference.

The Minkowski Difference will give you the distance between them (the penetration vector if they are colliding). With SAT you get the distance in each dimension and you have to calculate the vector yourself.
> 1 votes

---
Tags: collision-detection, physics, bounding-boxes
---


title: Building stable ecosystems

text:
# Question
Title: Building stable ecosystems
I'm interested in creating a world in which the behaviors of some of the elements are generated randomly or evolved. Is there a field of study or some well known work that deals with what it takes to create a stable ecosystem?

For instance, let's say I randomly generate three creatures that each eat each other. It's easy to imagine that one of the creatures might be dramatically better than the other two, kill all of its prey and defend itself against all of its predators. This will result in everything in the world dying, which isn't very interesting.

I'm looking for techniques which help to find or guarantee ecosystems that don't implode or explode, but instead oscillate within some interesting (hopefully fun!) bounds.

# Answer
Population dynamics is a research field for over 200 years and describes changes in size and age of populations over time. Some famous models include Lotka-Volterra equations as a model for predator and prey.

Some assumptions in the Lotka-Volterra model are:

* The prey population finds ample food at all times.
* The food supply of the predator population depends entirely on the size of the prey population.
* The rate of change of population is proportional to its size.
* During the process, the environment does not change in favour of one species and the genetic adaptation is sufficiently slow.
* Predators have limitless appetite

They naturally lead to oscillations (with a fixed delay between them) of both involved species if the parameters are chosen right.

Otherwise you can also get one or both of them to extinction.

You can probably model this in a cellular automaton fashion (e.g. as agents) so that it directly fits into your game.

Some advice to get the system more stable:

* Have prey and predator species (so species that just reproduce and species that need to kill others in order to live and reproduce)
* Have a limited but renewable supply of food for the prey.
* Rate of change of population is proportional to its size, prey reproduces itself faster than predators (otherwise prey will die out)
* Keep that predators have limitless or virtually limitless apetite (otherwise overpopulation of prey may follow)
* Have some "refuge areas" for the prey where predators seldom go
* If prey dies out by chance (can happen in real life see Dodos) just put them back or cheat (make them reproduce faster if the population is very low)
* Have large enough numbers of prey to be statistically on the save side

To make it more interesting/diverse:

* Change the environment periodically and make the system (reproduction rate, agility, hunting success rate, ...) dependent on the environment

In general:

* The more stable you are the less the system will react on random influences/distortions
* Therefore keep the oscillations inbuilt in the system and the random fluctuations small enough, so you will always go back to equilibrium
* To have an additional security mechanism to ensure stability cheat (make species reproduce faster and more difficult to hunt if they are far below their equilibrium, make them reproduce slower, ... if they are far above)
> 4 votes

---
Tags: procedural-generation, procedural, evolution
---


# Question
Title: How do I translate accelerometer readings into object movement?
I am using the `DeviceMotionEvent` web API, which gives me a device's acceleration split up into x-, y- and z-dimensions and a time interval.

Here's my attempt at moving an object on screen based on these accelerations in `data` (just the x-dimension, for clarity):

```
velocity.x = data.acceleration.x * data.interval;

var newLeft = $('.object').position().left + (velocity.x);

$('.object').css({ 'left': newLeft });

```

This sort of works, but after moving, it goes back to where it started from instead of slowing to a stop.

What am I doing wrong? How do I do this right?

---

Here's an example of some data the API returns:

```
{ acceleration:
   { x: -0.048474962000711816,
     y: 0.025074772074713834,
     z: -0.0035549827887938587 },
  accelerationIncludingGravity:
   { x: -0.07826046448306878,
     y: 0.34760814211749236,
     z: -9.804854269410603 },
  rotationRate:
   { alpha: -0.15093386712448556,
     beta: 0.051146754356783085,
     gamma: -0.019824252207518427 },
  interval: 0.05000000074505806 }

```

# Answer
> 2 votes
Remember that acceleration is a change in velocity. You will want to use the acceleration samples to accumulate in the velocity variable. IE, instead of

```
velocity = acceleration * time

```

try

```
velocity = velocity + acceleration * time

```

# Answer
> 0 votes
The acceleration measures how fast you move the device, not the current position (rotation/tilt).

For moving something based in the tilt of the device you need to use the rotation with the device orientation event.

For the x axis you would use the gamma data if the device is standing up, and beta if it's in panoramic mode.

Then treat it like it was a analog joystick. For example using gamma:

```
var movementX = data.gamma / 90;
velocity.x = speed * movementX;

```

speed is the speed that the object can have (the maximum speed), you choose it.

movementX is a range between -1 and 1. 1 means that it wants to move at full speed to the right, and -1 it want to move at full speed to the left. It can be 0.2, so you move at 20% speed to the right.

So you use the tilt like a controller with smooth steps (instead of moving or not, you move a percentage of the speed).

You would probably want to limit it before 90 degrees, so the player doesn't need to put the device vertical. For example with 45 degrees as max speed:

```
var movementX = data.gamma / 45;
if(movementX > 1) movementX = 1;
if(movementX < -1) movementX = -1;

```

If you want the player to have a better control you can have a minimum angle that need to be tilt to start reacting:

```
var movementX = 0;
if(data.gamma <-10 || data.gamma > 10) {
    movementX = data.gamma / 45;
    if(movementX > 1) movementX = 1;
    if(movementX < -1) movementX = -1;
}

```

In this case I'm using 10.

---
Tags: javascript, motion-control, integration
---


# Question
Title: Vertical Collision Detection, Falling Through Ground
After much work trying to learn collision system theory and apply it, I've got my collision system working for the most part. The player can collide horizontally with no issue, sliding against walls, and can also jump and land with no problem 99.9% of the time. However, there are some cases where the player phases through a wall or floor, and it seems to be when combining horizontal and vertical movement that this occurs. However, most of the time it does not occur, so it has been difficult to narrow down the cause. I think it's a conditional/flow logic mistake, but I can't spot it.

Collision handling code:

```
        Vec3 old = camera.Position; //store player position
        if (!scene.BlockAt(camera.FootPosition)) camera.Velocity.Y -= .5f; //if there's no block below the camera, enact gravity
        camera.Velocity.Y = Math.Max(camera.Velocity.Y, -10); //terminal velocity
        camera.Move(camera.Velocity * (float)gameTime.ElapsedGameTime.TotalSeconds * camera.MoveSpeed); //move camera according to keyboard input
        if (scene[camera.Position] != null) //if player is in a chunk
        {
            foreach (Block b in scene[camera.Position].Blocks) //iterate through blocks in the chunk
            {
                if (b != null && b.IsVisible) //ignore non-blocks and invisible blocks
                {
                    Resolve(camera, b, old); //collision detection
                }
            }
        }
        else camera.Position = old; //don't let the player leave the playable area
        camera.DiscardVelocity(true, false, true); //discard X/Z and keep Y velocity

```

Here's the "Resolve" function, the collision resolver itself:

```
    void Resolve(ICollidable3 a, ICollidable3 b, Vec3 oldPos, int depth = 0)
    {
        Vec3 diff = b.Position - a.Position;
        float adx = (float)Math.Abs(diff.X);
        float ady = (float)Math.Abs(diff.Y);
        float adz = (float)Math.Abs(diff.Z);
        float adxz = adx + adz;
        BoundingBox sweptB = new BoundingBox(new Vec3(b.BoundingBox.Min.X, 0, b.BoundingBox.Min.Z), b.BoundingBox.Max);
        if (ady >= adxz) //if there's more vertical than horizontal (or they're equal), check collision and correct by resetting vertical (before running horizontal collision)
        {
            if (a.BoundingBox.Intersects(sweptB)) //check against "infinitely" tall bounding box to avoid falling through terrain.
                a.Position = new Vec3(a.Position.X, oldPos.Y, a.Position.Z);
        }
        if (a.BoundingBox.Intersects(b.BoundingBox)) //if there's (still) collision
        {
            if (adx > adz) //if there's more X than Z
            {
                if (a.BoundingBox.Intersects(b.BoundingBox))
                    a.Position = new Vec3(oldPos.X, a.Position.Y, a.Position.Z); //reset the X
                if (a.BoundingBox.Intersects(b.BoundingBox)) //if that didn't work
                    a.Position = new Vec3(a.Position.X, a.Position.Y, oldPos.Z); //reset the Z
            }
            else if (adx < adz) //if there's more Z than X
            {
                if (a.BoundingBox.Intersects(b.BoundingBox))
                    a.Position = new Vec3(a.Position.X, a.Position.Y, oldPos.Z); //reset the Z
                if (a.BoundingBox.Intersects(b.BoundingBox)) //if that didn't work
                    a.Position = new Vec3(oldPos.X, a.Position.Y, a.Position.Z); //reset the X
            }
            else a.Position = new Vec3(oldPos.X, a.Position.Y, oldPos.Z);
        }
        if (ady < adxz) //if there's more horizontal than vertical, check collision and correct by resetting vertical (after running horizontal collision)
        {
            if (a.BoundingBox.Intersects(sweptB)) //check against "infinitely" tall bounding box to avoid falling through terrain.
                a.Position = new Vec3(a.Position.X, oldPos.Y, a.Position.Z);
        }
        if (a.BoundingBox.Intersects(sweptB)) //if we fail to resolve the collision
        {
            if (++depth < 25) //if we have more passes left
                Resolve(a, b, oldPos, depth); //keep trying
            else
            {
                a.Position = oldPos; //otherwise, revert position
                return; //abort if too deep
            }
        }
        else return; //resolved

```

If it isn't obvious from reading the first code block, "a" is the camera and "b" is the block that the player is standing on (cube terrain). "sweptB" was implemented in an attempt to fix this behavior, basically extending the collision box for vertical collisions to stretch to the minimum Y (will cause issues later when doing collision from below, but I can handle that when I come to it with some conditions). This stopped the majority of the issues, but in certain cases it is possible to walk/land horizontally through blocks. I'm trying to use some variation on the separating axis theorem, separating things into X vs. Z and then XZ vs. Y. The issue seems to lay in XZ vs. Y..

Does anyone see any flaws in the conditional/flow logic for resolving vertical vs. horizontal collision and combinations thereof? I suspect that my problem may lay with this rather than the actual detection or response.

# Answer
> 0 votes
Apparently the ultimate solution here was to subtract .5 from the position of each block as it was created so that the coordinates of the visual/physics worlds would line up with the block arrays. Changing the adxz calculation probably helped remove some bugs, but it wasn't related to the actual problem.

# Answer
> 0 votes
adxz is not adx + adz

If adx and adz where vectors, it will work. But adx and adz are the distance of the vector in that dimension, when you add them you will have the vector (adx, 0, adz). You need to calculate the distance of that resulting vector.

You need to use pitagoras for calculating that.

```
adxz = Math.sqrt(adx*adx+adz*adz);

```

---
Tags: xna, collision-detection, 3d, separating-axis-theorem, jumping
---