# Question
Title: Why do games ask for screen resolution instead of automatically fitting the window size?
It seems to me that it would be more logical, reusable and user-friendly to implement flexible, responsive UI layout over a 3d or 2d screen, which can then be run on any screen resolution.

Some modern games auto-detect screen resolution and adjust the game to that, but the option to change the resolution still remains in the settings.

Why is this option there?

My guess is that this is one way to provide older machines with a way to improve performance by rendering less graphics and just stretching them across the screen, but surely there are better ways of improving performance (choosing different texture and model qualities, for example).

# Answer
> 52 votes
This lets the user choose the game's quality versus its performance. Some prefer higher-quality graphics settings on a lower resolution, others the opposite. Some computers can handle maximum settings on everything, some can't.

Devices with homogenous hardware (PlayStation, Xbox, iPhone...) usually don't offer graphics settings for this reason.

# Answer
> 30 votes
There is no way to completely reliably detect the correct screen resolution.

One approach is to simply leave at the user's desktop resolution. This is annoying, as I know a number of people (some with visual impairments) who prefer to run their desktop at a lower resolution to make things look larger, but still prefer games at the native resolution where small text and details are rarer and less critical.

Another approach is to consult the monitor's supported modes list. This is similarly unreliable: Some monitors provide no mode list or provide it incorrectly. Some provide resolutions higher than the native one, which they are able to hideously down-sample while taking a performance hit...

In a way, your question applies to any setting a game provides. "Why should I ask the user when I can guess what's best for them?" Why would I ask they about quality settings when I can detect their hardware? Why would I ask about FOV if I know what the game looks best with? Why should I let users turn of AA if their computers can handle it? This more general question highlights the real answer, which is twofold:

*Your guesses are sometimes wrong*, as you'll not always have the correct hardware information to make a good guess. What if a user's graphics card is bugged, causing the computer to crash at a certain resolution and you don't let them disable it? Your game is now useless to them. Also, *users like choices*. Perhaps someone prefers the fuzzy look of playing at a non native resolution even though it is "wrong". Perhaps they have a CRT monitor which supports many resolutions and the optimum one is not the highest, or they get better refresh rates at a lower one.

In effect you cannot judge accurately *what the user wants* based on information from the computer, neither can you accurately judge *what will work best*. It is best left to the user (who knows their own computer) to decide.

(Note I've only covered PC here. Consoles are a different story, but have already been covered by others.)

# Answer
> 7 votes
There are a VAST number of reasons to allow the user to control the settings for their game.

* MANY people have 2 (or more) monitors these days. The user should be able to determine which one to play the game on.
* There are thousands of different devices a user could be using, and no way to reliably tell what setting would be optimal for every one.
* Some users may prefer less than "optimal" settings for reasons ranging from better game performance, to poor eyesight (lower resolution = bigger text!).
* Some users may prefer to play the game windowed, so they can have their chat boxes, walkthroughs, music player, or other programs visible at the same time as the game.

That said, many games DO auto-detect, and then set the initial settings to whatever it thinks is the best your machine can handle.

# Answer
> 5 votes
That's because the cost and effect of texture quality, geometry detail and screen resolution are very hardware-dependent.

The texture quality usually does not have much impact on the speed of the rendering pipeline, but only when they are read from GPU memory. When not all textures fit into the GPU memory, they need to be read from normal RAM or even worse from the hard drive cache, which affects performance negatively. Reducing geometry\* and omitting expensive effects\** won't help much. But when the execution speed of the rendering pipeline is the bottleneck, reducing texture resolution won't help much either.

Vertex shaders are usually unaffected by the output resolution. The only way to reduce the load on them is to reduce quality and quantity of the 3d models in the scene.

But any pixel shaders still scale linearly with the number of pixels on the screen. Reducing the screen resolution is still an important tool to improve performance. Having half the horizontal- and vertical resolution means you have just a quarter of the calls to the pixel shaders.

In contrary to the older CRT displays, modern LCD or plasma screens have a native pixel-resolution. When they are fed with a video stream in a different resolution, they need to interpolate. Some interpolate much better than others which means that running them on a lower resolution doesn't reduce the picture quality a lot while other monitors really look bad when not run on their native solution (the first LCD screen I owned used nearest-neighbor interpolation, which looked **horrible**. With my current screens, it's hard to tell when they don't run on the correct resolution).

The game engine can not know how well the monitor of the user interpolates, so it's better to leave the choice to either reduce texture and geometry detail or reduce the screen resolution to the user.

<sub>\*) OK, reducing geometry might help *a bit* because vertices also consume GPU memory.</sub>

\**) unless, of course, omitting these effects means that some textures are no longer required

# Answer
> 2 votes
Not only the predefined resolutions settings make it possible to react with performance in some way, but creating a universal approach, which fits all kinds of resolutions, ratios and dpis is just way much harder to create.

If you create only few different resolutions, then it is user worry to choose best looking for him (especially when his resolution/ratio is unusual). If you make one universal design, you are responsible for making the game looking perfect on all the devices (could be especially hard on mobiles nowadays, espiecialy not on iOS, but on the other platforms with a huge variety of devices).

# Answer
> 2 votes
Additional reason: Changing environments.

1080 is now standard, but wasn't 5 years ago. 4k is entering the picture and how long until 6k/8k/1080k (or whatever) enters the picture? What about gaming on an 8 year old computer that tops out at 1280x720? 1024x768? 640x400?

My monitor supports 4k native, but It'd choke on the bandwidth required and max out at 30fps. Let me switch to 1080 (or lower) so that the game runs at 60fps and the text/hud/etc isn't microscopic.

(Additionally: Give me windowed / maximized windowed as well please so I can tab around easily lol)

# Answer
> 0 votes
> My guess is that this is one way to provide older machines with a way to improve performance by rendering less graphics and just stretching them across the screen, but surely there are better ways of improving performance (choosing different texture and model qualities, for example).

That's not so simple. A game can run slow on my machine because it's stuck on fragment processing (perhaps lots of particle effects like smoke). Reducing model quality wouldn't take much load from here, and neither would reducing texture quality. On the other hand, decreasing the resolution reduces the load dramatically here (a switch from 1920x1080 to 1366x768 cuts the number of pixels to process by half).

And if my screen happens to be big - like a TV (like my current setup - I pretend my PC is a bigger xbox) - then, in a given viewing distance, bigger resolution doesn't give me much. So I have a good reason to turn the resolution down and perhaps even use the extra processing power to have more detailed lighting or shadows.

---
Tags: graphics, rendering, resolution, interface, user-experience
---


# Question
Title: How do you create fnt (angelcode format) files from existing bitmaps?
I often gets the same problem: Someones creates a nice bitmap font for me in form of a sheet nicely formated into a png, like this:

...and i need to create the angelcode .fnt atlas for using it (into Unity, libGDX, or countless other engines).

Yet, every time I google it, I stumble upon dozen of tools that create .fnt files from rasterized TTF fonts. (BMFont, Fontbuilder, etc.) Correct me if i'm wrong but they don't support exsting images, they always start by generating one from a vector font.

I end up semi-manually creating the file with an ugly script (the format is quite simple), but it's incredibly tedious. Surely there is a much better way to do that? Especially for monospaced fonts which are very easy to partition...

edit: I've made a small javascript tool to solve that. if by any chance you're interested, it's here : http://fontcutter.fbksoft.com/

# Answer
> 1 votes
Another solution is if you can get the font with all the letters split (trivial to do if they can be maintained as individual layers in Photoshop or Gimp) and named with the letter's id. Hell you could spend some time renaming them yourself after you get the files individually.

Then you could take a lovely open source sprite sheet packer (such as SpriteSheetPacker, though there's several others as well), and modify it yourself to produce fnt file format instead. Since all of the information would be there already (position of each letter as it's packed in a page, letter size, id, etc...), then it would be completely automatic at that point.

# Answer
> 3 votes
AFAIK there is no possibility to do that. But when you take a look into a `.fnt` file, you'll see that it's possible to write it on your own. It's made of some lines of plain-text which are doable in a hour or so i guess.

So the only solution that comes to my mind is writing the `.fnt` yourself.

EDIT: the resource you have there (this one) contains actually everything that has to be written in your `.fnt` file.

---
Tags: unity, libgdx, fonts
---


title: Copying rotation between matrices

text:
# Question
Title: Copying rotation between matrices
I have a transformed Matrix A and an another transformed Matrix B. How can I COPY the rotation of Matrix B to Matrix A?

# Answer
> 2 votes
Generally the "top-left" 3x3 block of coefficients will be the rotation/scale/shear component of a 4x4 (or 3x4) transformation matrix.

If both matrices have no scale (including reflection) or shear, you can simply copy this block of coefficients, something like:

```
matrixA[0][0] = matrixB[0][0];
matrixA[0][1] = matrixB[0][1];
matrixA[0][2] = matrixB[0][2];

matrixA[1][0] = matrixB[1][0];
...
matrixA[2][2] = matrixB[2][2];
// Leave row [3] and column [3] alone.

```

If both matrices contain some scale aligned to the axes of the source space (eg. if these are ModelView matrices, and they contain scale solely along the model's local x, y, and z axes, as is a common convention in games), but still no shearing, then it's a little bit trickier but still feasible. The details will depend on your environment's conventions for matrix storage and multiplication.

In principle you can take the basis vectors from matrix B (these will be the rows of the top-left 3x3 block, or the columns, depending on your environment), normalize them, then multiply each by the corresponding scale coefficient for A, something like:

(abusing some hlsl notation to keep this compact...)

```
matrixA[0].xyz = scaleA.x * normalize(matrixB[0].xyz);
matrixA[1].xyz = scaleA.y * normalize(matrixB[1].xyz);
matrixA[2].xyz = scaleA.z * normalize(matrixB[2].xyz);

```

(You may need to transpose your matrices before & after this operation, if your environment uses the opposite row/column convention)

If either matrix contains shear, or scaling that isn't aligned to axes within the source coordinate space, then it becomes ambiguous what "copying the rotation" from one to the other would mean. Fortunately we don't encounter those types of matrices too often in gamedev, apart from perspective projection matrices.

# Answer
> 0 votes
I assume you work with a homogenous transformation matrix like those used with OpenGL.

Your question implies that you assume that one can extract a rotation part from that transformation matrix. Or more mathematically speaking, that it is possible to factor the transformation into a product of simpler transformations, where one of the simpler transformations is a rotation.

It turns out that this is not such easy for an arbitrary homogenous transformation matrices. In general there are many decompositions possible with different resulting rotation matrices which might or might not be useful for your purpose.

E.g. you can try a polar decomposition to factor a homogenous transformation matrix `M` into

```
M = P T R N S = Q S

```

where

* `P` is a simple perspective matrix
* `T`is a translation matrix
* `R`is a rotation matrix
* `N` is either `I` (identity matrix) or `-I`
* `S` is a stretch matrix
* `Q` is an orthogonal matrix (length and angle preserving, i.e. a combination of rotations and reflections)

The situation can be simpler if you can assume that the transformation matrix is the result of multiplying only a restricted set of intermediate transformation, see this blog post.

Also see this SO entry.

And this Math.SE entry on SVD, but beware, read the comments about the numerical and graphical properties of that decomposition in the above paper about polar decomposition.

---
Tags: matrix
---


# Question
Title: How can I deploy a Xbox 360 game onto a disc?
I'm making some games for Windows now since about 3 years using the Microsoft XNA Framework and C#. Now I finally came to buy myself a Xbox 360 and now I want to deploy some games I converted to Xbox 360 onto a CD to give it away to my friends. What tools would I need and how can I do this?

# Answer
> 5 votes
XNA only supports distribution of your final game via the Xbox Live service. You cannot print discs that will run on a retail console.

You will require an XNA Creator's Club membership, which is a subscription-based membership with an annual fee, in order to publish your game to the platform. Your friends will then be able to log on to Xbox Live and get it.

Your only other real option is to mod your console to support homebrew development. This will allow you to run unsigned executables (although usually not via discs, distribution via USB or similar is more common). It will likely require you to rewrite your games, since the XNA framework is supported by the homebrew development toolchain. Also, all of your friends will need to have modified consoles as well. Doing this will void your warranty and in the past has caused users to get banned from Xbox Live. Not all versions of the console are moddable, as well. I don't recommend this route, but there is plenty of information and guides out there on the internet on the process (which would not be appropriate to collect here).

---
Tags: xna-4.0, xbox360, deployment
---


title: Why is anti-aliasing so slow?

text:
# Question
Title: Why is anti-aliasing so slow?
I have always asked myself this, especially about x4 or x8 anti-aliasing. It seems that over the years, the algorithm has remained the same but needs more power than before due to improved game graphics.

Most disturbingly, some games look the same at x4 and x8, but perform worse at x8!

What makes anti-aliasing algorithms so computationally demanding?

# Answer
> 2 votes
It all comes down to memory bandwidth with proper anti-aliasing techniques (e.g. MSAA, SSAA, CSAA). While 8x SSAA and 8x MSAA have identical storage requirements (8x), the workload between the two algorithms is quite different. Multisample anti-aliasing adds some intelligence to the rasterization stage to reduce the number of fragments that have to be shaded, thus reducing the computational expense of anti-aliasing. However, the covered samples generated during rasterization still have to be written and averaged and this eats through a tremendous amount of memory bandwidth.

Newer image processing techniques (e.g. FXAA, MLAA) approach the problem from an entirely different perspective. They do not seek to solve the fundamental problem that leads to aliasing in the first place (inadequate sample frequency), instead they keep initial rendering as simple as possible and "fix it in post" using a complicated shader. Given the trend in hardware to increase compute power quicker than memory bandwidth and advances in display resolution, these compute-intensive approaches definitely have sticking power. Nevertheless, I have a hard time calling them anti-aliasing, as all they really do is mask aliasing ***after*** the fact.

If you are speaking of an anti-aliasing approach whose quality is measured in terms of sample rate, then the algorithm is of the memory hungry variety first discussed. The newer shader-based techniques have a myriad of implementation-specific properties that you can tune, and this is why a game that uses something like FXAA will sometimes offer vague "Low", "Medium", "High", etc. quality settings but nothing quantitative.

# Answer
> 0 votes
Well in XNA it samples the scene for pixel data a number of times and uses the data to interpolate the colour around the lines. So it is quite demanding on the GPU to do each frame, but there are newer types of AA(MSAA, TXAA etc) which are more efficient but i am unsure how they work.

Edit: Tordin pointed out my original answer was incorrect

# Answer
> 0 votes
I know that MSAA renders the scene at a higher resolution and then downsamples it to make nice pixels. Simply, the graphics card is trying to render double or quadruple the screen resolution, and calculating more pixels is just slower. You can find more info at http://en.wikipedia.org/wiki/Multisample\_anti-aliasing

TXAA though, combines MSAA with some past-frame blending, which means you don't get the flicker that MSAA sometimes gets on very thin architecture. It seems to be nvidia specific though.

# Answer
> -2 votes
http://en.wikipedia.org/wiki/Xiaolin\_Wu%27s\_line\_algorithm simply because anti-aliasing algorithm have high cost

---
Tags: graphics, performance, antialiasing
---


# Question
Title: 3D Background for a Verticle Shooter: Making it loop?
I know how to scroll a background using spritebatches + 2D background images, but how would I do it with a 3D model?

# Answer
> 3 votes
You will first need to ensure the model actual tiles seamlessly in the direction you want it to scroll. Then, a simple solution is to draw the model twice.

Consider the viewport of your game, represented by this ASCII box:

```
+------------+
|            |
|            |
|            |
+------------+

```

When you draw your 3D background model, represented by the ASCII `M`, it normally ends up looking something like this:

```
   MMMMMMMM
   MMMMMMMM
+------------+
|  MMMMMMMM  |
|  MMMMMMMM  |
|  MMMMMMMM  |
+------------+

```

That is, some portion of the model is visible and some portion is outside the viewing area. To "loop" this background model, you detect when the edge of the model is about to come into view (this is a simple rectangle-rectangle containment test, because you can project the bounding volume of your model onto your viewing plane), and the frame just before the edge would be visible, you draw a second copy of the model above the first (represented below by the ASCII 'm'):

```
   mmmmmmmm
   mmmmmmmm
   MMMMMMMM
+------------+
|  MMMMMMMM  |
|  MMMMMMMM  |
|  MMMMMMMM  |
+------------+
   MMMMMMMM
   MMMMMMMM

```

As the game continues to scroll, both models are onscreen, giving the illusion of a seamlessly tiling world:

```
   mmmmmmmm
   mmmmmmmm
   mmmmmmmm
+------------+
|  mmmmmmmm  |
|  mmmmmmmm  |
|  MMMMMMMM  |
+------------+
   MMMMMMMM
   MMMMMMMM
   MMMMMMMM

```

Once the first model has scrolled entirely off the screen you can stop drawing it, so at most you are only rendering the model twice.

If the model is particularly huge, you may want to break it into smaller chunks simply to avoid all the extra geometry processing to determine that large portions of the model are offscreen.

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


# Question
Title: Hotplugging Joysticks And Gamepads On OSX
I've tested the cross platform joystick support features on GLFW, SDL2 and SFML. SDL2 appears to be the most complete, but it can't detect when joysticks have been unplugged on OSX. To me, this is a fundamental feature.

Joystick detection support appears to be much weaker on the Mac than in Windows. What can I do to overcome this?

# Answer
> 4 votes
Using the latest SFML from github (2.1 should also work but I didn't test with it) you can listen for the `sf::Event::JoystickConnected` and `sf::Event::JoystickDisconnected` events as described in the SFML Events Tutorial. I've tested the events and they are both fired on Mac and Windows.

A sample program to test this would look like:

```
#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML Joystick Events!");

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event:: JoystickConnected)
            {
                std::cout << "joystick connected: " << event.joystickConnect.joystickId << std::endl;
            }
            else if (event.type == sf::Event::JoystickDisconnected)
            {
                std::cout << "joystick disconnected: " << event.joystickConnect.joystickId << std::endl;
            }
            else if (event.type == sf::Event::Closed)
            {
                window.close();
            }
        }
    }

    return 0;
}

```

---
Tags: c++, macos, joystick
---


title: How long does the collision take?

text:
# Question
Title: How long does the collision take?
I want to simulate a simple force-acceleration (rather than impulse-velocity) physical world made up entirely of disks and I'm having an irritating problem with my physics.

When two disks collide, I can calculate the changes in velocities quite easily using conservation of momentum and conservation of energy. Since this is going to be a force-based simulation, I need to calculate the forces to apply. I thought I'd use the momentum-impulse equality:

```
mΔv = FΔt

```

Sounds simple, except I don't know what to do with time(Δt). So I guess the question boils down to this: how long does the collision take? Or rather, do the two objects stick together for a period of time (Δt)?

# Answer
> 2 votes
In impulse physics everything is infinitely hard, that is the only way you can ever achieve an impulse.

In force physics, just like the real world, nothing is infinitely hard. How long a collision takes depends on how soft the involved objects are, relative to their mass.

The force between two objects is `hardness * deformation`, if the objects have different hardness then the harder object deform less than the softer object so that the result is the same for the two objects. This solves to:

```
force = [combined deformation] / (1/[hardness obj1] + 1/[hardness obj2])

```

That is the basic formula, it is very easy to implement. The big problem is energy conservation, you would have it with infinitely small time steps, but in a naïve implementation you won't have it. Using softer objects and a higher time resolution will bring you closer to this goal, that may be good enough in most game contexts. Using a hardness that makes the collision take an exact even number of time steps will solve the issue for simple one-on-one object collisions, so will using an advanced integration method, but I'm not sure that there is any nice way of ensuring energy preservation for collisions involving more than two objects.

---
Tags: physics
---


# Question
Title: What units does Sprite Kit use for physics?
I'm developing a simple ball game in Sprite Kit. I need to predict the ball's trajectory, so I went back to my physics book for the equations for acceleration, time, speed and space.

The problem is that Sprite Kit documentation does not declare the units of measurement of the properties of physics bodies, so it's hard to calculate the needed values.

Based on my experiments/research I suppose that:

* gravity is expressed in m/s/s (m/s^2)
* since gravity is a CGVector, all CGVectors are expressed in m/s/s (m/s^2)
* velocity (instant speed) is m/s

Then I realized a simple scene where a ball is falling:

* Gravity: CGVector(0,1.2);
* Height: 218.009499 pixels
* Time: 0.302499747
* Then acceleration should be: 2\*Height / Time^2 = 1441.3863 pixels/s/s
* And gravity of 1.2m/s/s corresponds to 1441.3863 in a world measured in pixels

Someone says the internal PTM (pixel to meter ratio) is 150.

Any hints?

# Answer
They actually do specify it:

> All values in Sprite Kit are specified using the International System of Units (SI units).

Gravity and velocity are both meters per second. (Though gravity ought to be meters per second *squared*; that might be a typo.)

When adding velocity to your sprite, ensure you use the the appropriate method, for instance `ApplyForce` versus `ApplyImpulse`: `ApplyImpulse` affects the body’s linear velocity without changing its angular velocity. `ApplyForce` accelerates the body without imparting any angular acceleration to it. The acceleration is applied for a single simulation step (one frame).

Also, do not rely on *pixels*; use *points* if you need precision, as Retina and non-Retina displays have different amounts of pixels per square inch.
> 3 votes

---
Tags: ios, projectile-physics, spritekit
---


title: Mobile: Physics and movement actions

text:
# Question
Title: Mobile: Physics and movement actions
I've been using spritekit for a while for a few small games. One thing I've noticed is that spritekit is the first game framework I've used that allows me to apply move actions to physics bodies. (without anything screwing up at least.)

Are there any cross platform game frameworks I can use that allow move actions on physics bodies? Not impulses. I've used cocos2d in the past and when I tried ccmoveby on physics bodies the simulation would get totally confused. I rather not use cocos2d anyway.

I'm asking because I want to make cross platform games and spritekit is iOS only.

# Answer
You can use SpriteKit or Kobold Kit and then use Apportable to convert it to Android.

http://www.apportable.com/

But if you want truly cross compatible you could use Unity3d free version and build out to the specific platform you want since iOS and Android are given. (They now have 2D Sprite abilities)

It costs a pretty penny if you want the Pro features though. http://unity3d.com
> 1 votes

---
Tags: physics, cocos2d, cross-platform, spritekit
---


# Question
Title: How to efficiently render a large terrain mesh?
Recently I've been stuck on a problem thinking about the best way to generate a terrain into my game. In another projects I normally used heightmaps, so all the core-work was based on the engine used, but now this cannot be done because the terrain has millions of specific polygons that must be drawn accurately. Also, many of them cannot be parsed from the Y vector (because of polygons hidden beneath), that is, a heightmap is not useful here. In this case I had to use a COLLADA object.

Someone told me to manually divide the model inside a software like Blender, but unfortunately this is also not possible because these terrains are created in chunks in another software and loaded after into the game (that's the idea). Therefore this would be a big work to be obliged to manually slice them everytime.

Thus, since a week I've been studying about how could I solve this problem and procedurally load this mesh, the terrain, accordingly to the camera frustrum, saving as much performance as possible. I came accross many documents about procedural mesh generation and I think that my problem could be solved by mapping the mesh into octrees. This is BIG work, at least for me, and that's why I'm here, because I don't want to risk taking the wrong path without before hearing from experienced people.

In short, I have millions of vertices and indices that together form the terrain, but for obvious reasons I cannot draw them at the same time. It's needed some kind of procedure. What's the best way to do that, to treat a big mesh as a terrain? Is there any specific book about that? Is there a best way to implement it?

Sorry for any kind of mistake, I'm very novice on this area.

# Answer
> 13 votes
Basic chunking is a good way to start. You can move to more sophisticated data structures like octrees later, if you need. For now, simply divide your terrain into chunks of given dimensions when loading the model from disk.

Depending on your data, you might either want to split your terrain into pillars on a plane spanning the full height, or in cubes in space. The code isn't complete (fmod, vector initialization, indices, ...) but should give you a start.

```
// Load vertices from disk
struct point { double x, y, z; };
vector<point> vertices;

// Create container for chunks
typedef pair<int, int> key;
unordered_map<key, vector<point>> chunks;
const int chunksize = 10;

// For each vertex
for (int i = 0; i < vertices.size(); ++i) {
    // Fetch global coordinates
    int x = vertices[i].x,
        y = vertices[i].y,
        z = vertices[i].z;

    // Find containing chunk
    key k;
    k.first  = x / chunksize;
    k.second = z / chunksize;

    // Calculate local coordinates
    point p;
    p.x = x % chunksize;
    p.y = y;
    p.z = z % chunksize;

    // Add to chunk
    chunks[k].push_back(p);
}

// Create separate buffers for each chunk
// ...

```

Since you have split up the mesh now, you can perform LOD and culling techniques on it to skip rendering of hidden chunks.

* **View distance** is where you start. You would only render chunks within a given distance, for example the view distance of your camera. The smaller the view distance, the more performance you get since fewer chunks of the terrain must be drawn.
* **Frustum culling** is a common technique to only render meshes that intersect with the camera's view frustum. This will most likely give you the largest performance gain.

Experiment with the chunk size and view distance to get the best results. Chunk size is a trade-off between accurate culling versus easy computation. To further optimize, you could take a look at these more advanced optimizations.

* **Occlusion culling** can be done by rendering the meshes on the CPU at very low resolution. This allows you to early detect meshes hidden behind other ones. They don't have to be sent to the GPU, so you save a lot of vertex shader executions which otherwise would have been performed before rejecting the triangles.
* **Level of detail** means that you calculate lower resolution meshes of your chunks. Based on the distance to the camera, you choose one of the meshes to draw. This allows you to reduce the number of vertices since chunks far away don't need so much detail. This approach plays well with octrees because you could merge multiple cubes into one low resolution mesh for areas far away from the camera. However, it is non-trivial to seamlessly merge the edges between two chunks of a different resolution.

---
Tags: opengl, 3d, performance, terrain, octree
---


title: Drawing symmetric equilateral triangles

text:
# Question
Title: Drawing symmetric equilateral triangles
I'm rendering equilateral triangles of different sizes and I'm having trouble making them symmetric along the vertical axis. Here I have rendered two triangles. The triangle on the left (rendered correctly) has the coordinates (0.0, 0.0), (-7.0, 14.0) and (7.0, 14.0). The triangle on the right, on the other hand, has the coordinates (0.0, 0.0), (-7.0, **15.0**) and (7.0, **15.0**) and is not symmetric along the vertical axis.

Here are the matrices I'm using:

```
glm::mat4 model_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(90.0f, 90.0f, 0.0f));
glm::mat4 view_matrix = glm::mat4(1.0f);
glm::mat4 projection_matrix = glm::ortho(0.0f, w * 1.0f, h * 1.0f, 0.0f);
glm::mat4 mvp_matrix = projection_matrix * view_matrix * model_matrix;

```

I'm aware of the diamond exit rule but I don't think that's the cause of the problem. Seems like the diamond exit rule only applies to line segments? This problem also exists when I try to make triangles symmetric in the horizontal axis. Cheers!

# Answer
> 3 votes
This is a notoriously hard problem - the short answer is that to have all the right properties when it comes to overlapping line segments, line drawing has to have some *inherent* asymmetries; for instance, a line that falls on a half-pixel boundary must be drawn on that pixel can only be drawn on that half-pixel if the line comes 'from the left' but not 'from the right', in a loose sense. If you need your triangles to be perfectly symmetric, you're best off explicitly mirroring the pixels yourself.

---
Tags: opengl
---


# Question
Title: 2D Rendering in DX11. Texture Storage and Reference
I'm trying to think of the best way to manage textures in my 2D game.

First, I am using DX11, so right now my "textures" are just pointers to a ID3D11ShaderResourceView created by D3DX11CreateShaderResourceViewFromFile. Is this how I should be loading content?

Right now my basic idea is to create a hashmap of textures with string references.

When an object is created that uses a texture it passes the reference of the texture to the hashmap and gets back a pointer to the texture. If the texture isn't loaded it will use the string to find the correct texture to load, add it to the map and pass back the pointer, so it automatically loads new textures as required (my game is turn based, and many small pauses would have no real effect).

But here are my issues:

1. Is the above method the best method I could be using (without it becoming overly complex)
2. ID3D11ShaderResourceView. Is this how I should be storing texture data in DX11?
3. Ideally I want to have all my texture data compressed in a file. Right now I am simply loading jpgs and so on. But I have no idea how to compress these images and selectively re-load them as required. Ideally I would want to compress them to be locatable in the file using the reference string used when searching the hashmap too.

# Answer
Yes, just keeping around the `ID3D11ShaderResourceView` is generally fine. Note that you can call its `GetResource()` method to retrieve the underlying `ID3D11Texture2D` object if you should ever need that for some reason.

What you're doing now sounds fine for a small game and hobby development. Eventually, there are a few enhancements you might want to consider:

* Make a list of all the textures used in a level or game section, and load them all up front rather than as you encounter them during gameplay; even if your game is turn-based, not having pauses to load textures is a better user experience.
* Similarly, you can load textures on a background thread so that your main rendering thread isn't stalled. The D3D11 device is automatically multithreaded, so you can create D3D objects on other threads without worries. This does require some inter-thread communication to ensure you don't try to use a texture before it's done loading.
* As far as compression goes, there are two different concepts here - compression of the actual texture data in a GPU-friendly format, and putting all the textures in one file to reduce disk seeks. For the compression part, consider converting your textures to .dds format and using DXT compression, which is natively supported by GPUs (JPEG is not). The .dds format also allows you to store mipmaps, so you're not re-generating the mips every time you load the texture.

For the aggregating-into-one-file part, you can use .zip files as a simple way to aggregate things. The simplest thing to do is probably to load the entire .zip into memory in one shot, which is the fastest way to do I/O. Then, with the file in memory, you can decompress individual textures out of it as you need (or just decompress them all at once). There are plenty of zip file libraries that can take care of the details, and you can find articles/tutorials about this on the web.
> 1 votes

# Answer
Yes, the approach that you have described is quite common due to the shareable nature of textures. Having a texture cache like this is very useful to avoid reloading the same texture more than once. Storing every loaded texture in a hash-table and looking up the table first is probably the easiest way to do it.

About using or not the raw API object `ID3D11ShaderResourceView`, this is a matter that is very specific of your project. If you never plan on porting your game to some other non-MS platform, then it would be OK to sprinkle a few D3D calls around. If you plan to port it at some point, the best would be to wrap this object in a custom `Texture` class. Another reason you might have to wrap it into a custom class would be to extend its functionality. Does `ID3D11ShaderResourceView` have all the methods you need? If not, it might be a good idea to define your own `Texture` type that has a `ID3D11ShaderResourceView` pointer.

For the third question, one easy way to pack all textures in a single file and avoid a lot of code change is to just store them all in a compressed (ZIP) folder and decompress the folder at startup. Take a look at a compression API, such as miniZ. Another option would be a Texture Atlas, but this might imply some changes to code and mesh assets.
> 0 votes

---
Tags: c++, textures, directx11
---


title: Issues with 2D Body/Limb system

text:
# Question
Title: Issues with 2D Body/Limb system
In my game I have programmed **Body** and **Limb** classes. The Body is guaranteed to have an origin in the center of its sprite. The Body class has a List of children Limbs, each with their own offset. Every Limb has a **Master** value which references the parent *Body*, but it also has a **Parent** value which *references the Limb it is a child of*. However, Limbs do not have to have a parent, they can directly connect to the Body.

The **Master**, **Parent**, and **Children** values of the **Limb** class:

```
    //Body containing all limbs this limb is connected to and others.
    public Body Master
    { get; set; }

    //Parent limb, if null then limb directly connected to the body.
    public Limb Parent
    { get; set; }

    //Children limbs
    public List<Limb> Children
    { get; set; }

```

The Limb methods have if statements to handle these situations. In relation to the offsets and rotations of the Limbs around the Body (using transformation matrices) things seem to work fine. Now, the problem I'm having is when a Limb is attached to another Limb. The child Limb draws and behaves as if it is rotating around the Body instead of its parent Limb, and the parent Limb itself vanishes. Limbs without Children that are directly connected to the Master Body have **no issues**. Because of this sort of recursive hierarchy I believe the problem has to do with reference types but I may be mistaken. Here is some additional code:

**Demonstration:**

Here is the **worldPosition()** method which is used to acquire the Limb's position in world space. I suspect it may be the culprit. The **Master.Position** is already in world space:

```
    public Vector2 worldPosition()
    {
        if (Parent != null) return (LocalPosition += Parent.worldPosition());
        else return (LocalPosition += Master.Position);
    }

```

Finally here is the **Update()** method of the Limb class: http://pastebin.com/5L5v5p6x

**EDIT:** Upon further analysis it appears that any changes I make to either Limb seem to affect the other Limb in one way or another even though they are both quite clearly different instances.

Here is the code to make the initial Body and first Limb:

```
        b = new Body()
        {
            Sprite = FileFactory.Textures["shoulders"],
            Position = new Vector2(this.Position.X, this.Position.Y),
        };

        Limb l = new Limb()
        {
            Sprite = FileFactory.Textures["left_arm"],
            Master = b,
            Offset = new Vector2(2, 13),
            Origin = new Vector2(0, Sprite.Height / 2),
            RotationalDifference = (float)(0.2 * Math.PI),
            RotateSpeed = 0.15f
        };

        b.Children.Add(l);
        b.Initialize();

```

And the code to add the child Limb to the first (Parent) Limb:

```
            Children.Add(
            new Limb()
            {
                Sprite = FileFactory.Textures["right_arm"],
                Master = this.Master,
                Parent = this,
                Offset = new Vector2(27, 0),
                Origin = new Vector2(0, Sprite.Height / 2),
                RotationalDifference = (float)(0.2 * Math.PI),
                RotateSpeed = 0.15f
            }
            );

```

# Answer
> 0 votes
As it turns out, the problem is in this code here:

```
public Vector2 worldPosition()
{
    if (Parent != null) return (LocalPosition += Parent.worldPosition());
    else return (LocalPosition += Master.Position);
}

```

I was using the wrong operator, += instead of just +. I was continually adding one position to the other and returning the accumulating result. It's hilarious that it took somebody else to notice it and only after 2 days of the problem arising. The working code looks like this:

```
public Vector2 worldPosition()
{
    if (Parent != null) return (LocalPosition + Parent.worldPosition());
    else return (LocalPosition + Master.Position);
}

```

---
Tags: xna, c#, 2d, matrix, skeletal-animation
---


title: java slick2d - key press being ignored

text:
# Question
Title: java slick2d - key press being ignored
I have the following in my update funtion. The first input for key\_enter when textPos!=2 works fine, but the one when textPos==2 doesn't work. The key up and down work fine though.

The System.out.println("Enter: " + choice); never gets printed

```
public void update() {
        Input input = gc.getInput();
        if (input.isKeyPressed(Input.KEY_ENTER)) {
            if (textShowing && textPos != 2) {
                textPos++;
                textShowing = false;
            }
        }
        if (textShowing && textPos == 2) {
            if (input.isKeyPressed(Input.KEY_ENTER)) {
                System.out.println("Enter: " + choice);
                if (choice == 0) {

                } else if (choice == 1) {

                } else {
                    textPos++;
                    textShowing = false;
                    System.out.println("Text Pos: " + textPos);
                }
            } else if (input.isKeyPressed(Input.KEY_UP)) {
                if (choice > 0) {
                    choice--;
                }
            } else if (input.isKeyPressed(Input.KEY_DOWN)) {
                if (choice < 2) {
                    choice++;
                }
            }
        }
    }

```

# Answer
> 0 votes
Figured it out. If i switch the "if (input.isKeyPressed(Input.KEY\_ENTER))" and "if (textShowing && textPos != 2) {" the other way around it works

---
Tags: java, slick
---


title: View-Update versus Model-update

text:
# Question
Title: View-Update versus Model-update
I am creating a game using a relatively new platform called "codenameOne", but I'm actually a software engineer, so this question might be rather basic or odd, but I'm unsure what to do.

The game is targeting mobile phones and tablets (codenameOne has the advantage of being close to WORA) and I'm unclear on how to correctly update the "logic" and the "view".

At the moment, both update 60 times per second, but this feels wrong. This means that if I decrease the update speed of the game, the elements will also slow down (such as applying the current acceleration to the velocity, to the position,...)

This comes down to two questions:

1) Should they have separate update frequencies?

2) If so, which ones are conventionel for mobile applications?

EDIT: It might actually be worth noting that the game works (some bugs but it renders fine and it's playable). If you want to take a look at the source it's here: https://github.com/DylanMeeus/CNOGame

# Answer
Usually we call "logic" "update" and "view" "draw".

Ideally the view would only want to redraw when the logic has changed. It's true that if you slow down the update speed, everything will be slower. This is why we used fixed time steps.

With a fixed time step, update should always be consistent. The only time it wouldn't be is:

* You change the time step at run time( don't do this. )
* Update is running extremely slow( 99% of the time, drawing should be the thing lagging behind. )

If draw is making the whole application slow, logic update will still be on time. If the user doesn't see a few frames, that's okay. If updates don't happen, that's not okay. That actually changes the game.

If you're using a well competent 3rd part library for this, then it should have this covered for you.

So, basically, everything is still based off time. View can be updated as much as possible, logic can only be updated if a certain amount of time has passed.
> 3 votes

# Answer
I think both approaches are valid if done correctly. In your case a delta value should be passed to the logic telling it how much time has passed since the last update. After that every logic part would update according to it so changing a coord for instance could be something along the lines of x += velocity\*delta.
> 0 votes

---
Tags: java, mobile
---


# Question
Title: How do I make a character follow behind another?
I'm creating a game in C++ using OpenGL. I want to add a character into my game who, after meeting the main player, follows the player around. The follower should position themselves directly behind the player, moving when the player does to stay in the correct position:

How can I accomplish this?

# Answer
There are several options for this.

* Keep a queue of a fixed number of past positions of the player character to which you append only whenever the player moves. Always place the NPC at the oldest position in that queue. That will look as if the NPC mimics past moves of the player-character. There will be no way for the PC to shake off the NPC, because it will always be behind even when physically impossible.
* Calculate the position behind the player based on the players coordinates and direction. Then navigate the NPC to that location using a stock route-finding algorithm like A\*. This will look much more natural because the NPC can fall behind, but they might get stuck when the route to the player-character gets blocked for some reason.
> 6 votes

# Answer
This will demonstrate how to create a dynamic list of positions the AI could move towards while following the player without mimicking the players movements or using a path-finding algorithm.

Assumptions:

* We need to know if the player could be reached in a straight line of movement (another question).
* We need to be able to tell the AI to perhaps look at the player when it's not moving towards her. Otherwise the AI needs to look towards where the AI itself is going.
* We should define some distance that we consider close enough (we don't want the follower to walk "inside" the player, that may be uncomfortable for both of them.
* We need to remember the last position of the player (where she was in the previous frame).

What we'll do:

We'll maintain a list of a minimal amount of points needed to follow the player (we'll use it to find the shortest path towards her).

Pseudo code:

```
// The player will leave a dynamic trail of cookie crumbs
// If the player is reachable in a straight line then the only coordinate we need is
// her current position
if (player.pos ().isReachableFrom (ai.getPos ()){
    checkPointList.clearList ();
    checkPointList.headPush (player.pos ());
// If the player is no longer reachable in a straight line then she left a cookie.
// But if the player is no longer reachable from the newest freshest cookie
// she needs to add a new cookie.
// We also remove stale cookies that may not longer be necessary.
// (for instance if the player moved in a loop we don't have to do the same loop)
} else if (!player. pos().isReachableFrom (checkPointList.head ()){
    for(curr = list. tail (); !player.lastPos ().isReachableFrom (curr); curr = curr.next ()){}
    checkPointList.deleteAfter (curr);
    checkPointList.headPush (player.lastPos ());
}

```

This is about it and you always need to move after that checkPointList's tail and remove the item in the tail once you get there. If you are too close, then have the AI look at the player and wait until it is far enough to require following.
> 0 votes

---
Tags: c++, ai, game-mechanics, character
---


title: Creating weapons/armor procedurally

text:
# Question
Title: Creating weapons/armor procedurally
In my current project I am creating a 2d game (rpg) which should be able to dynamically create new weapons and armor based on different components. So, i.e. a sample weapon would consist of barrel1, grip3, etc. It's much like Borderlands, but in 2d.

I thought about using a library like CImg in order to assemble the different parts (which are images) and then using the created sprite in my game.

Am I on the right way? Is there a better way to accomplish this task?

# Answer
> 1 votes
Have different spritesheets for every weapon-component you load as separate image resources. When you want to draw a character, you first draw the character-sprite, and then the sprites of each weapon-component, one after another.

Keep in mind that in some cases it might be necessary for some parts to change the drawing offsets of other parts. You might, for example, have a silencer-part which fits on the barrel of a pistol, carbine or sniper rifle. You can use the same sprite for each, but would have to draw it at different positions depending on how the barrel-part of the gun looks. That means each barrel-part would need an additional property which says where a muzzle-part would need to be drawn. Or maybe the weapon has multiple barrels. That would mean multiple silencers would have to be drawn with different offsets (Silenced gatling gun? Why not?).

Should performance be a concern, you could use sprite-batching as a performance enhancement. Sprite-batching means to draw each animation phase with all the sub-sprites to an off-screen image and then draw the actual game using that off-screen image as a source. That way, when you have a sprite consisting of 5 sub-sprites, you only need to do one draw-call per frame and not 5. However, converting that off-screen image into a graphic file and saving it somewhere is of little use. Just keep it in the native texture format of the graphic API you are using. The only use I could think of would be to save the complete spritesheet together with the savegame to speed up savegame loading. But considering that we are talking about a 2d game here, I doubt that this optimization would be worth the effort.

Whether or not that library fits your requirements is a technology-question, and what-technology-to-use questions are off-topic here because they are usually subjective.

# Answer
> 0 votes
It is a tree structure at heart. You have the "bare weapon" ("un-enhanced") which has `n` slots for extensions that will be positioned accordingly in with some translation, rotation or scaling possibly `(S1, S2, ... Sn)` and once you add an extension, it may open up new slots for extensions that will be positioned relatively to that extension's position.

So if you placed extension `A` in slot 3 and `A` has 2 slots then slot 3 is taken and the new slots (3, 1) and (3, 2) will be placed and could be occupied by new suitable enhancements.

So basically you have the root of the tree which is a basic un-enhanced weapon type. It has slots where new enhancements could be added randomly by the generator and possbly some enhancements could be further adorned with more complicated improvements if that enhancement has its own slots. You basically need to randomize recursively and decide in each step what to add. Some slots could be occupied with mundane stuff and on rare weapons they may contain some important improvements.

To position the pieces that you add to the weapon you could wither use a slot specific transformation matrix that will move, rotate and scale the sprite pieces accordingly or use the needed math to position the enhancements accordingly.

The bottom line is that as a data-structure the underlying idea is a tree that grows recursively as new pieces are added in, possibly with some constraints (perhaps you don't want a cannon with a silencer on top of it).

---
Tags: c++, graphics, procedural-generation
---


# Question
Title: Can game replays be used as cheat protection?
Say you're writing a complex turn based multiplayer strategy game in the browser (i.e. JavaScript). The game state is big and complicated (think line of sight calculations in a 3d world). There can be many simultaneous games on different maps. Thus keeping all of those maps in memory on the server and verifying every single client action as it happens would quickly become prohibitively expensive. So we're faced with the situation that we cannot trust anything from the client and we cannot verify every individual client action on the server due to cost.

Has anyone experimented with recording game sessions and running offline/asynchronous verification on them as a cheat deterrent? Ideally, the players themselves would get suspicious and spot check each others' replays. Obviously there would be a significant delay between the cheat happening and the player getting flagged, but in a long-running strategy game with persistent state, I think this would be a significant disincentive.

Do you know of such examples? Have they worked well?

# Answer
Depending on how the gameplay works and what cheats are possible in it, telling the difference between cheating and genuine skill paired with luck can be very difficult. The only situation where you can proof a cheat in a replay is when a player does something which violates the game mechanics, and these situations should be easy to detect automatically.

Delegating the verification of cheats to the community is maybe not the best idea. A group of players who want to bully another player could band together and flag all of his replays as cheating and get them banned although they didn't do anything wrong. The final decision whether or not to sanction a player for cheating should be left to a neutral admin.

On the other hand, you can expect that most replays won't be checked at all. I doubt that players will be interested in watching replays between matches of lower-class players. When you rely on the community to detect and report cheaters, you can expect that only the most prominent players will be examined thoroughly.

I would still recommend you to create that replay-feature. But not as a sole cheat prevention but because it's a really interesting feature the community will likely enjoy a lot.
> 5 votes

# Answer
A friend had a physics-based game with online score board, and tried doing score validation by offline verification.

If the simulation is perfectly deterministic, this is possible.

Unfortunately, if you use floats anywhere, you won't be perfectly deterministic. Different CPUs may have different internal floating point precisions, which means that as long as a value is in a floating point register, it'll be calculated at a higher precision. This is generally a good thing, but once it gets popped back to memory, the additional precision is lost. Now, if two different CPUs have different precision, a thousand iterations later you will end up with subtly different values.

To make things worse, different optimization passes may cause your compiler to generate slightly different FPU code, which means that even on a single machine, two compilations of the same source (with small changes that may not even seem relevant to the calculation) may cause subtle differences.
> 2 votes

# Answer
The important message to take here is that replays can be used for cheat detection *sometimes* and not protection. Even so, it may be hard or impossible to detect some types of cheats. It also begs the question what is considered plain cheating and what would be taking full advantage of tools that most players may not consider..

Here is an example:

In a strategy game with keyboard shortcuts, player A creates some advanced keyboard macros that allow her to build up a base faster than any human player using ordinary controls. Is that cheating? Perhaps. But who can tell the difference? Perhaps a machine doing some statistics. Is the implementation here worth it?

On the other hand, there is a competition going online in a deterministic single player game supposedly protected from cheating but player A again records her keyboard input until she loses, then she plays back her keyboard input and continues from the spot before she lost. She then repeats this process to allow her to basically save her state. Can anyone tell she is cheating? Yes but it will require someone to check and compare different playthroughs, even then it would be hard.

Another thing that may be destructive in a game like you specifically described is if someone creates an AI bot that listens to the packets and computes an optimal decision based on the state of the game. This could be impossible to detect.

Generally I think the conclusion is that when you are working to detect or prevent cheats (like any other security related matter), whatever technique you are using, is being used on people and they may outsmart your or simply pick another way you haven't thought of to cheat the system. Human and especially cheaters, are very resourceful.
> 0 votes

---
Tags: multiplayer, client-server, anti-cheat, browser
---


# Question
Title: Implementing a score cheating prevention system in an offline game with an online score board: How to protect game fairness?
This is hopefully a very simple question. It isn't about loading assets (which is all I found while searching)

Basically I have a template, say Object\_Monster that has stats, abilities, etc. But I don't want to abstract it and create Object\_Monster\_Witch, Object\_Monster\_Ghoul and so on.

I want to know the best way to store data for loading many "different" monsters for one monster class. But I don't want the data to be editable by players.

For example. Lets say a Ghoul has 50 max health, the name "Ghoul" and the Consume ability. I would want all those variables listed somewhere to then be loaded into Object\_Monster so he can act as a Ghoul.

I hear people use XML for this sort of thing, but that is of course, edited on the fly. Should I be using just an in-code list of #defines? An array of monster data?

# Answer
> 4 votes
When the players want to edit stuff, they will find out how. Hardcoding attributes won't stop a determined modder for long.

So I would recommend you to do the only sensible thing and put that data in a config file. XML is just one option. Some people prefer JSON or custom formats because they are simpler to write and read. When you don't want to make the files too obvious, you could bundle resources as zip-files, but not name them as such. That way a modder needs to put in at least a bit of effort to find out which file format they are dealing with.

# Answer
> 3 votes
Hardcoding this data as constants in the code would be terribly unpractical, requiring a recompile of the project for every change. Even for small games this is very annoying.

To make the game data opaque, you either have to write custom binary formats or pack every text file into a compressed (ZIP) folder. You might even go to the extreme of encrypting the data, but I've never heard of such case for things like game assets.

Like it was commented before, players of your game with a bit more technical skill will eventually find a way to crack custom file formats and edit the game. But think again about this, do you really want to make your game like so? A frozen piece of software that will eventually get old and go out of production and no one will ever be able to improve it or fix it? I have a very open mentality on this matter, and as a developer, I always prefer to make the technical details of my games as open as possible, either by giving away documentation about custom file formats or editing tools that the player can utilize to mod the game. I find that this not only greatly increases the lifetime of a game but also lead to the creation of modding communities that will ultimately do a lot of free publicity for your stuff.

# Answer
> 1 votes
According to your comments the question is: how to implement some form of score board cheat prevention in an offline game with an online score board. Obviously, if the game is played offline, the least of your concerns is that players modify the game elements to throw off the balance, use that to win and post an unwarranted high-score. Your main concern would be that they simply send a couple of packets that say "Hey Mr. Server I got a really great score" and the server will reply "OK, I'm just going to stupidly accept this ... because you claim this to be true, it must be so" and done. They have any score they want with their name on it. What the server should say is "Pics or it didn't happen!".

In order to have some minimal control over the correctness of the scores I would suggest you make the game's behavior deterministic (in this sense):

* Any randomness needs to be controlled by a seed (so it's reproducible).
* Any floating point computation needs to be removed or replaced by a deterministic alternative.

Now record the players input during the game and once the game is over send the recording if the score is high enough to warrant being checked. Play the recording on the server in a checker and see if the official game constraints are broken. This does not prevent them from creating something like a "TAS" (tool assisted speedrun) with some hacks on the machine. For additional measures you may want to have form of control over the seed of the game like seed `A` is reasonable if the game was started at time `T`.

If you want to prevents players from cheating offline: that's impossible. If it were possible then people would have found ways to prevent users from cracking games in the first place.

If you want to add some measures to make it more difficult to cheat offline and then publish that as an achievement online then there might be some more things you can do but this really deserves it's own question.

BTW, encrypting the data and then decryption it during run-time is just a form of obfuscation and isn't considered a real measure of protection.

---
Tags: c++, asset-management
---


title: Determine when to start modding a game

text:
# Question
Title: Determine when to start modding a game
I have not modded a single game in my life, but I really, really want to start. I'm a 3D animator (make no money from this, just a serious hobby) and a budding Object Orientated programmer (make all my money from my own web applications, I'm not a millionaire but I live comfortably and have bags of time on my hands) so I feel like I will be able to make some incredible mods.

Fallout is my favourite game series of all time, has a vibrant modding community, its open-world style means the sky's the limit (and occasionally further!), there are excellent modding tools available (such as the GECK), and Bethesda has an excellent attitude towards licencing (unlike those nazis over at EA), so I'm one-hundred percent sure that's what I want to mod.

However I have no idea what modding a game is like, and while the only way to find this out is by modding, what I'd really like to know is how do I determine when is the right time to mod? My heart wants to download the GECK (the fallout editor) right now and get stuck in, but I'm being sensible and writing this question.

The last fallout game (New Vegas) is nearly half a decade old (2010) and Fallout 4 is lurking in the future somewhere. I want to dive in modding new vegas, but where will I be when fallout 4 comes out? Will there be only a slight learning curve and then all the skills I've learned will be utilized to start modding really quickly in Fallout 4?

Or, in between games, are modders simply left in purgatory regarding future releases? Could I become a Fallout 3/NV mod ninja, and then have to learn everything again come Fallout 4? Or do companies such as Bethesda make an active effort to keep everything consistent?

I feel 3D engines are like web frameworks such as Zend and Rails. Basically, I've put all my eggs in Rails and have never looked back. I'm sure that as the web changes, Rails will change with it. I spend every moment of my professional life with Rails as I'm confident it will never die and I will be able to build on my existing skills until I retire. This attitude means I can really throw myself at projects, go the extra mile and learn new skills. **However, will I not be able to do this with modding? Will there always be lurking doubt that come the next game, everything I've learned will be useless? Will every new game hit me with a learning curve?**

Also (and this would me awesome if true but I kind of doubt it), are moden games similar enough that if I'm a Fallout ninja, the learning curve wouldn't be too crazy if I then wanted to mod Crysis or Portal or even a non-fps like Civ5?

# Answer
> 2 votes
Every game is different and offers different ways to mod it.

General skills like pixel art, music composing, 3d modeling and game design do of course transfer, but when it comes to getting these assets into the game and changing game mechanics, each game engine is completely different.

Some games expose various parts of the game logics in form of scripts, but these can come in all kinds of different scripting languages with all kinds of different APIs. Others require intensive reverse-engineering of the game binaries to get them to do something different than what they are supposed to do. When there already is an active modding community and/or the will of the developers to support modding, you will find documentation and tutorials to help you get started, but when there isn't you will need to apply some hacking skills to figure out how things work on your own.

When two games are based on the same game engine, you will often notice that lots of things work very similar. But when you switch to a game with a different engine, you will have to start learning from almost zero.

---
Tags: modding
---


title: [ C# ]xna to monogame

text:
# Question
Title: [ C# ]xna to monogame
I'm thinking of going back to xna and c# because I have used java 2d, slick 2d and some other libraries. I started off with xna and c# but ignored it for java. I'm thinking of going back, but I see xna isn't being developed anymore. I read there is away to convert it to monogame but seems very complicated. XNA look fairly easy, yet I havn't toyed with monogame yet. So what I want to know , is monogame related to xna or close in coding? Would it be easy to understand if you're good with xna?

# Answer
I've converted a few XNA projects to Monogame, with great success. The only major issue I have had, is converting Shaders. If you are not dealing with shaders, there shouldn't be much problems. Most likely, you will just have to point to the Monogame assemblies, and it will all work.

I think Monogame is a very good option for game developers.

If you have any specific concerns, ask them. I'll try my best to answer.
> 2 votes

---
Tags: xna, java, monogame
---


title: Game Design vs Game Development

text:
# Question
Title: Game Design vs Game Development
What is the difference between a video game developer and a video game designer?

# Answer
If you meant by developer is programmer, I'd really like to correct that.

Developer means any person that has a role in the development of the game. Consists of roles: Producer, Programmer, Artist, and Sound are the most basic high-level position in video game development. "A game developer is anyone who has any involvement with the creation of the game at all. Engineers, animators, modelers, musicians, writers, producers and designers who work on games are all game developers." (qtd. from *The Art of Game Design* by Jesse Schell)

If you really meant programmer/engineer when you said developer, then they are the ones who "program" the game; as in, putting all the pieces of the game - ideas, arts, sound, implementation, etc - into a whole playable state.

Designer, on the other hand, are the ones who "designs" the features in the game. Not strictly into just ideas, but rather, much more in-depth than that. Designers focus on giving details about how game features are going to be implemented. This doesn't mean they are the only ones who are limited to doing that, but it is the position where it's their sole role to think through things more in-depth. Typically, design just means "decisions about how the game should be" (qtd. Jesse Schell). But in reality says it's much more stricter than that if you mean the job position "game designer." Game Designers tend to have the most demanding wide variety of skills because you have to consider as many things as possible, including but not limited to business, animation, mathematics, music, communication, technical writing, psychology, and much more. It doesn't mean that you have to have all those skills, but the more knowledge you know the better.
> 11 votes

# Answer
A game developer is a person who can make a game from scratch by themselves, very difficult and hard to find actual qualified game developers. Development teams consist of game developers, artists (2d,3d,sound) and management level (producers, distribution managers).

A game designer is typically a game developer who has proven his/her worth in a team, has a vast amount of experience and at least one shipped title to their name. They are chosen to make executive decisions that effect the direction of development, thus why they need to be able to program, design & manage - so they can make calculated decisions. (when this is an individual it would be considered an indie developer and not a designer as designer is not an entry-level position in the games industry).

Hope this helps
> -7 votes

---
Tags: game-design, career
---


title: Pygame proble, moving picture

text:
# Question
Title: Pygame proble, moving picture
Thats my problem on the Picture...The stripes

How can i fix that?

My Code:

import pygame, sys from pygame.locals import *

pygame.init()

sound = pygame.mixer.Sound('start.wav') sound.play()

size = width, height = 1600, 848 speed = \[2, 2\] black = (0, 0, 0)

pygame.mouse.set\_cursor(\*pygame.cursors.broken\_x)

screen = pygame.display.set\_mode(size) background = pygame.image.load("background.PNG") dragon1 = pygame.image.load("dragon1.gif") screen.blit(background, (0,0))

x,y=0,0 clock=pygame.time.Clock() speed=250 movex, movey=0,0

while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type==KEYDOWN: if event.key==K\_a: movex=-1 elif event.key==K\_d: movex=+1 elif event.key==K\_w: movey=-1 elif event.key==K\_s: movey=+1 if event.type==KEYUP: if event.key==K\_a: movex=0 elif event.key==K\_d: movex=0 elif event.key==K\_w: movey=0 elif event.key==K\_s: movey=0 x+=movex y+=movey

```
screen.blit(dragon1, (x,y))
pygame.display.flip()

```

# Answer
> 0 votes
You need to blit the background image at each update or loop in your mainloop like so:

```
while True:
    #mainloop stuff
    screen.blit(background, (0,0))
    screen.blit(dragon1, (x,y))
    pygame.display.flip()

```

The way you are currently doing it you are only blitting the BG once then you are blitting the dragon but the screen isnt being refreshed so you keep seeing each place the dragon was blitted at before

---
Tags: python, pygame
---


# Question
Title: Drawing sprite shapes with triangles instead of textures
If I want to use no textures in a game (ie. no png images), could I just break down my drawing into triangles, combined into the shape I want to draw, and draw those triangles instead?

For example, I found this in Google Images, showing how an "arrow" graphic could be drawn as a triangle mesh instead of a textured sprite:

# Answer
> 2 votes
Yes, you can do that exactly as you describe.

I made a 2D game a few years ago where an artist decided to make all our "sprites" as meshes in Blender, due partly to a limitation in the v1.0 of the engine that didn't support textures (the engine I wrote for the shipping version did, but the character art was already made and the meshes were smaller than the corresponding rasterized sprite sheets would have been).

Note that that arrow is a bad example of triangularization. You want to avoid long and thin triangles. Rasterization hardware often works in such a way that works more slowly with long and thin triangles than with shorter triangles. This desire to avoid long triangles applies to many other contexts where triangularization is used, like navmesh generation.

# Answer
> -1 votes
I would suggest using alpha blended textures instead, as simpler alternative.

The texture would then look like this, and instead of triangulating it you just draw one textured quad with it:

The big advantage is that you will have much greater artistic control over it, since you can create textures like this with almost any application and can replace them by more complex sprites if you ever want to.

---
Tags: opengl, textures, vector-art
---


# Question
Title: How do you set the target location for a navmesh using a GameObject?
I am trying to get a GameObject to navigate through a map and get to the exit. I have created a navmesh for the map and given the player GameObject a navmesh agent. The exit is marked with a empty GameObject. Using the unity manual I made this script and atached it to the player:

```
function Start ()
{
    var agent: NavMeshAgent = GetComponent.<NavMeshAgent>();
    agent.SetDestination(GameObject.Find("exit"));
}

```

The porblem is that this script gives the error

"Assets/Scripts/enemy.js(4,29): BCE0017: The best overload for the method 'UnityEngine.NavMeshAgent.SetDestination(UnityEngine.Vector3)' is not compatible with the argument list '(UnityEngine.GameObject)'."

I think is is because unity wants a vector3 but I have given it a GameObject. How can I get this to work with a game object?

# Answer
You are passing in a GameObject, yet the function wants a Vector3.

To fix this, you could pass in `transform.position`:

```
function Start ()
{
    var agent: NavMeshAgent = GetComponent.<NavMeshAgent>();
    agent.SetDestination(GameObject.Find("exit").transform.position);
}

```

Function reference here.
> 2 votes

---
Tags: unity, javascript, unityscript, navmesh
---


# Question
Title: Making a cube follow my finger in Unity2d?
I would like to make a cube follow my finger when i touch an iphone screen and drag in unity 2d.

# Answer
The camera class has a method called `ScreenToWorldPoint(Vector3 position)` pairing that will the `Input.GetTouch(int index)` method, you can retrieve the position in the world where the user is touching on the screen. Remember to check the touch count before trying to retrieve touch points.

For example, adding a script to the cube with the following in the update method would probably work:

```
if(Input.touchCount > 0)
    this.transform.position = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);

```
> 1 votes

---
Tags: unity
---


title: Is networking programming quite generic

text:
# Question
Title: Is networking programming quite generic
I have only looked into the basics, at least I assume it gets more complex. So does network code really change from one game to the next or is it pretty much portable. For example I can create say a 2 person chat app, now if you want to make it multi-chat you then need to use mutli-threading, ie a new thread for every connection(load a new Winsock object for each connection). I am also reading about mutex ojects, blocking and non-blocking sockets.

You then have 2 base networking API's, Winsock and BSD sockets, there are various wrappers for these such as Boost.

The principle is that you then send a snapshot of all the gamestate data back and forth between client and server and have some kind of load balancing to take into account lag and general synchronicity.

I can't see how this would really change from game to game though, these are fairly linear principles and one set of networking code should be compatible with the next?

# Answer
In broad terms, there are a few standard architectures for networking systems.

In terms of **topology**, you have:

1. **Client-Server**: All clients talk to a single server, which may be a dedicated server executable, or may be another copy of the game, just operating in "server mode". (this is the one you mentioned)
2. **Promiscuous Peer-to-Peer**: Every peer talks directly to every other peer, either explicitly, or implicitly via multicast or broadcast transmissions.
3. **Connection Graphs**: Peers self-organise into a network, so some peers talk directly to each other, while others can act to forward messages between clients which can't talk to each other directly

Each of these approaches requires a different strategy for managing bandwidth, detecting joins/parts, for synchronising game clocks, and for handling other network events.

In terms of **synchronisation strategies**, there are four main approaches to keeping each client's view of the world in synch:

1. **Synchronise State**: Clients continually send messages which broadcast their full current state. (this is the one you mentioned)
2. **Synchronise Edge-Crossing**: Clients only send messages when their state *changes*. For example, an edge-crossing-style client likely will not send messages when it's idling; instead, it will inform other clients only when its position changes (and then, it will only inform about the updated position, not any of the rest of its unchanged state). This approach is great for cutting down on the amount of bandwidth required to play a game.
3. **Synchronise inputs**: Clients don't send their state at all -- instead, they send their control inputs, and the game instead relies on the game logic working the same way for each client. This is often how turn-based games are implemented; the turn doesn't happen until everyone has submitted their moves, and then everyone processes what happens next, and some old LAN-only action games also used this approach.
4. **Future events**: This is a more unusual approach, but high-latency game designs occasionally get built around queuing up future actions. Instead of each client saying "I'm here now", they say "in 20 seconds, I will be at this position." In a lot of ways, this is like a version of "edge-crossing" that's even more resistant to lag. See NetStorm for an early example of this approach.

There are also a few methods of **coping with latency**. Especially on the Internet, you can often have 300 milliseconds of latency, and there are a couple different ways to cope with that. Different approaches are appropriate for different types of games. Here are a few:

1. **Lockstep**: Nobody does anything until a synchronisation packet has been received from everyone. Once all synchronisation packets have been received, everyone can advance by one simulation step. This is usually the approach used by the "Synchronise inputs" synchronisation approach. And for obvious reasons, it doesn't work at all with the "Synchronise Edge-Crossing" approach.
2. **Dead-reckoning**: When we haven't heard authoritative information about the game state, we make an educated guess based upon the last state we knew about, and the amount of time since we last heard what the game state was. So if the last thing we heard was that a client was at a particular position and moving left, and it's been a second since then, we might make an educated guess that they've continued moving left since we last heard from them, and so continue moving them to the left. This process of making educated guesses is referred to as "dead reckoning"
3. Alternately, we can perform **Interpolation**, in which when we hear updated state data, we smoothly adjust our client's view of the world state over a short period of time, so that they don't appear to 'pop' around from place to place as they make unpredictable moves.
4. And of course, you can do *both* **Dead-reckoning** and **Interpolation**, making predictions about where things will go, **And** smoothly adjusting when you guessed wrong. This is almost always nicer than either of these two techniques on their own, but it makes the code a lot more complicated, since you're needing to perform interpolations on dead-reckoned positions, and be continuing to perform dead-reckoning while error-correcting interpolations are occurring. So you need to weigh up whether the implementation costs are justified for the benefit it gives.

So there's no one *universally right* choice for how game networking works. You need to pick what sort of system architecture (or architectures) are most appropriate for each individual game, bearing in mind the hardware and networks on which the game will be being played.
> 6 votes

# Answer
There are many issues that could be dealt with using a variety of techniques. Does the game have physics? If so, are physics being checked on the server securely? How is lag handled? What is the behaviour on the client-side when the round trip times increases?

Is there a logging system in place to allow further debugging or studying in case of errors, cheating and other unwanted occurrences? What do we log?

More importantly, is the system scalable? If the game is going to be player by a handful of users at the same time, it may not be an issue. Other times dozens or hundreds of players play together so the question becomes more prominent.

Another issue is what kind of tools are necessary for moderators. Are moderators needed? If so what tools do we provide them with?

I cannot think of all the reasons but there are differences in networking code, just like there will be differences in rendering code or in the code that handles user input. In theory we could have come up with a generic interface but it may not be suitable for every user (game developer).
> 2 votes

---
Tags: c++, networking, c, client-server, game-state
---


# Question
Title: How do I make a sprite appear to sway with the wind?
I'm trying to find a method to simulate the effects of wind on various sprites in a side-view 2D scene. What relatively simple technique could I use for this?

What I have in mind is to give these sprites a "spring" effect that I could hand a force that rotates them in a specific direction and eventually degrade the force and bring the sprite back to its "resting" rotation over time with a little bit of rebound/wobble/sway... I don't understand how I can mathematically create the elastic/spring effect using rotation, taking into account things like mass, resistance, or stiffness. How would I go about doing this in code? It doesn't have to be super realistic.

I'm hoping to set up a global wind variable that gets applied to sprites starting on one side of the screen and making its way to the other to look like a gust of wind passed through. I should be able to accomplish this once I have a method for applying a wind force to a single sprite.

How can I do this?

# Answer
> 4 votes
I use the following method in a 3D scene for grass and vegetation animation, but is easily transformed to 2D geometry.
The method is as simple as offsetting vertices of wind-affected geometry by some sine fuction. (vertex shader code follows)

```
float3 wind = sin(time+(pos.x+pos.y+pos.z)*0.1f)*wind_direction.xyz*wind_strength;
pos+=wind;

```

Here **time** is a shader constant which is an ever increasing number (system time for example). The **pos** variable is the vertex position of which I add every component to time when calculating sin for a nice variety, so it seems like wind travels nicely across the screen. **0.1f** is just a magic number. I just multiplied by it because it seemed nice after some tweaking (it makes the waves seem bigger). **wind\_direction** and **wind\_strength** are the wind parameters, a three component vector and a float.

If you want to use this with 2D sprites then you just need to forget the z component of the vectors (making them only two-component vectors) and it will work the same.

If you can't use vertex shaders for some reason it should also be applicable on the cpu, but you need to store the default vertex positions (or corners) for your sprite, but draw your sprites with your modified vertices (corners).

I hope I could help, also please note that this is not physically correct wind effect, but only something that is easy to compute and nice to look at. You can also check out this effect if you would be interested in this youtube video. The grass field and the tree leaves are both animated by this function.

---
Tags: xna, 2d, physics, sprites, graphic-effects
---


# Question
Title: Dealing with multiple animation state in one sprite sheet image using html5 canvas
I am recently creating a Game using html5 canvas .The player have multiple state it can walk jump kick and push and multiple other states my question is simple but after some deep research i couldn't find the best way to deal with those multiple states this is my jsfiddle : http://jsfiddle.net/Z7a5h/5/

i managed to do one animation but i started my code in a messy way ,can anyone show me a way to deal with multiple state animation for one sprite image or just give a useful link to follow and understand the concept of it please .I appreciate your help

```
 if (!this.IsWaiting) {
    this.IsWaiting = true;
    this.lastRenderTime = now;
    this.Pos = 1 + (this.Pos + 1) % 3;
 }
  else {
    if (now - this.lastRenderTime >= this.RenderRate) this.IsWaiting = false;
 }

```

# Answer
> 2 votes
When your animation system reaches a certain complexity, it becomes useful to pair each spritesheet with a separate animation manifest which says which animations are on that spritesheet and where the frames for each animation can be found.

The animation manifest could be a javascript object which says what animations the entity can perform, for how many different directions (between 1 and 8) it has separate animations for that action, and from which frames each of these animations are made up. These objects could look similar to this:

```
{  walk: [          // I have walk-animations for 4 directions, so a 4-entry array
       [ { frame: 0, delay: 100 },   // walk right
         { frame: 1, delay: 100 },
         { frame: 2, delay: 100 },
         { frame: 3, delay: 100 }
       ],
       [ { frame: 4, delay: 100 },   // walk down
         { frame: 5, delay: 100 },
         { frame: 6, delay: 100 },
         { frame: 7, delay: 100 }
       ],
       [ { frame: 8, delay: 100 },   // walk left
         { frame: 9, delay: 100 },
         { frame: 10, delay: 100 },
         { frame: 11, delay: 100 }
       ],
       [ { frame: 12, delay: 100 },   // walk up
         { frame: 13, delay: 100 },
         { frame: 14, delay: 100 },
         { frame: 15, delay: 100 }
       ],
   ],
   stand: [           // stanging is the same for all directions
       [ { frame: 4, delay: 0 } // just one frame borrowed from walk-down cycle
       ]
   ],
   attack: //...
}

```

The advantage of this is that you are not bound to a rigid structure regarding spritesheet organization. Any entity can have as many or few animations with as many or few frames as you want. It is also possible to reuse duplicated frames between animations to reduce spritesheet size.

# Answer
> 0 votes
For your animations, i suppose you are using a sprite sheet like this one :

To handle animation, you have to deal with :
• Sprites : array containing the textures coordinates of the frames of the animation. It is just the (x,y) where the sprites starts, and the width/height of this sprite.
• Animation : frame indexes : array containing the indexes of the frame, in the order of replay.
• Animations : array or object containing all the animations.

fiddle is here : http://jsfiddle.net/gamealchemist/Vn2Nt/6/

```
// ____--------------------------------------_______
//           --- Bird animation ----

// array containig texture coords of all frames.
var textureCoords = [];

// fill the textureCoords using image img, assuming
//   frames are tiled in a 'regular way', sized tw X th,
//   uses only cnt frames.
function fillTextureCoords(img, tw, th, cnt) {
    var w = img.width,
        h = img.height;
    var hCount = Math.floor(w / tw),
        vCount = Math.floor(h / th);
    for (var vIndex = 0; vIndex < vCount; vIndex++)
    for (var hIndex = 0; hIndex < hCount; hIndex++) {
        textureCoords.push({
            u: hIndex * tw,
            v: vIndex * th,
            w: tw,
            h: th
        });
        if (!--cnt) return;
    }
}

```

Now the frames index that form an animation :

```
// frames of the animation.
// Contains index to the textureCoords array.
var regularAnimation = [];
for (var i = 0; i < 14; i++) regularAnimation.push(i);

var shortAnimation = [4, 5, 6];

// we store all anims in a single array
var birdAnimations = [regularAnimation, shortAnimation];
// Rq : could be stored in an object
// for instance :
// var birdAnimations = { regular : regularAnimation,
//                          short : shortAnimation };

var currentAnimation = regularAnimation;

// duration of a single frame.
var frameDuration = 100;

// current time of the animation (ms).
var animationStartTime = 0;

// draws the current animation frame
function drawThatFrame() {
    var animationStatus = applicationTime - animationStartTime;
    var whichFrame = Math.floor(animationStatus / frameDuration);
    whichFrame %= currentAnimation.length;
    var tCoord = textureCoords[currentAnimation[whichFrame]];
    context.drawImage(myBird,
    tCoord.u, tCoord.v, tCoord.w, tCoord.h,
    10, 10, tCoord.w, tCoord.h);
}

```

Changing the animation is done with :

```
function switchAnim() {
    // switch array
    if (currentAnimation == birdAnimations[0]) currentAnimation = birdAnimations[1];
    else currentAnimation = birdAnimations[0];
    // reset time
    animationStartTime = applicationTime;
}

```

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


# Question
Title: Space between randomly generated objects
Im not sure there is a going to be a simple answer for this question but Ill ask anyway. I am programming an endless scrolling game where the player's character is constantly "falling." As they fall they dodge pinecones. I want the program to randomly generate pinecones (which it does right now); however, I need a way to check that there is enough space between pinecones so that the player's path is never accidentally blocked.

Simply programming a minimum distance between pinecones isn't hard. The problem is that I want to allow some cones to be right next to each other, but still check to make sure there is space between others for the player to safely dodge pinecones. Basically, I do not want an equal amount of space between each pinecone all the time.

I've considered making a grid pattern that the pinecone spacing must abide by, but Im having trouble comparing spaces on the grid so that while some cones are allowed to be next to each other, others are not. If the question is unclear let me know and Ill try to explain better and include pictures or something.

# Answer
You can split this into two stages:

Firstly generate some pinecones with such minimum distance between them that you need:

On second stage add some pinecones next to those placed already:

That way you will have have some single pinecones and some pinecones clumps, but all of those will be separated well apart.

You can tweak 1st stage to use slightly bigger distance than minimum allowed, to let 2nd stage have room to add pinecones. Or check on 2nd stage to make sure no newly added pinecones will be making the gaps too small.
> 2 votes

---
Tags: random, objects, spaces
---


# Question
Title: How do I calculate the motion of 2 massive bodies in space?
I'm writing code simulating the 2-dimensional motion of two massive bodies with gravitational fields.

The bodies' masses are known and I have a gravitational force equation. I know from that force I can get a differential equation for coordinates. I know that I once I solve this equation I will get the coordinates. I will need to make up some initial position and some initial velocity.

I'd like to end up with a numeric solver for the ordinal differential equation for coordinates to get the formulas that I can write in code. Could someone break down how from laws and initial conditions we get to the formulas that calculate `x` and `y` at time `t`?

# Answer
> 1 votes
To a first approximation, this behaves just like any other mass-under-a-force problem: since the gravitational force is `F=G*m1*m2/r^2`, the acceleration on body 1 is `a1=G*m2/r^2` and that on body 2 is `a2=G*m1/r^2` — note that these accellerations are in the direction of the other body.

To keep this pseudo-code relatively minimal, I'm going to presume that there's already a well-defined `Vector` class with all of the relevant operations (addition, subtraction, scalar multiplication and normalization) available, and all of my vector variables will be prefaced with a 'v'; e.g., `vVel1` and `vPos2`.

Given this setup, then a first approximation is pretty straightforward — but there's one huge caveat that I'll cover at the end.

First of all, there's a straightforward initialization step:

```
vPos1 = vInitPos1; vVel1 = vInitVel1;
vPos2 = vInitPos2; vVel2 = vInitVel2;

```

Then on every update, we first find the vector from the first body to the second — of course, the vector from the second body to the first is just the negative of this. While we're at it, we pre-scale it by the gravitational constant and the inverse squared distance between the two vectors; these values will be the same for both accelleration computations, so now's a good time to get them out of the way. Note that since we'll normalize vDeltaPos by dividing it by its length, and then we divide it again by its squared length, we could actually just divide by the length cubed - but vector normalization routines often have special code for numerical stability, so it's generally best to do this 'the hard way'.

```
vDeltaPos = vPos2-vPos1;
radSq = vDeltaPos.LengthSquared();
vDeltaPos.Normalize();
vScaledDeltaPos = vDeltaPos*(GRAVITATIONAL_CONSTANT/radSq);

```

Now with this in hand, the acceleration for the two bodies is easy; body 1's accel just points towards body two, scaled by body 2's mass, while body 2's accel points towards body 1, scaled by that body's mass:

```
vAccel1 = mass2*vScaledDeltaPos;
vAccel2 = (-mass1)*vScaledDeltaPos;

```

With the accelerations in hand, then the update step is just two iterations of the Euler method, updating velocity from acceleration and updating position from velocity:

```
vVel1 += deltaTime*vAccel1;
vVel2 += deltaTime*vAccel2;
vPos1 += deltaTime*vVel1;
vPos2 += deltaTime*vVel2;

```

And that's all there is to it! But... there's a huge caveat here. Actually, two huge caveats. The first is that Euler's method is as inaccurate as a differential equation solver can get while still being useful; there are methods that give you much better accuracy for a given delta-Time, but they're a lot more complicated. (If you're curious about these, the magic names to start with are *Runge-Kutta*).

The second, though, is a little more subtle, and the code above luckily accounts for it. You may notice that I update the velocity *before* I update the position; this means that the position update uses the updated velocity rather than the 'old' velocity. This minor tweak helps to correct for a problem with the naive Euler methods: they don't necessarily conserve the energy of the system, so that even a configuration that *looks* like it should be a stable mutual orbit can wind up with the two bodies flying off towards infinity. Using the updated velocity is a very simple version of a so-called *semi-implicit Euler method*, which helps with energy conservation (at least to the approximation provided by the timestep), but if you want guaranteed long-term conservation - i.e., stable orbits over long timescales - then you'll want to look even deeper down the rabbit hole, into methods that are guaranteed to be energy-preserving.

---
Tags: physics, simulations
---