title: Best way to store game-wide variables

text:
# Question
Title: Best way to store game-wide variables
I have an options screen for things like difficulty, resolution, full-screen, etc., but I'm struggling to find the "best" way to store/obtain these variables at run-time.

Currently, I've implemented a `Constants` class which contains all the `GameOption` enums, but how do I choose a default for all of these options? Also, how do I get the currently selected enum?

Regarding the resolution, specifically, I've decided to store the values, but I'm unsure of how to get the default, or currently stored, values. Any direction would be great; thanks! :)

```
namespace V1.test.RPG
{
  public class GameOptions
  {
    public enum Difficulty { EASY, MEDIUM, HARD }
    public enum Sound { ON, QUIET, OFF }
    public enum Music { ON, QUIET, OFF }
    public enum ResolutionWidth
    {
        SMALL      = 1280,
        MEDIUM     = 1366,
        LARGE      = 1920,
        WIDESCREEN = 2560
    }
    public enum ResolutionHeight
    {
        SMALL      = 800,
        MEDIUM     = 768,
        LARGE      = 1080,
        WIDESCREEN = 1080
    }
    public Boolean fullScreen = false;
  }
}

```

NB: I asked over at SO and they pointed me to this place. There is a comment there but I'd like to hear different ways of doing it / the most used ways.

# Answer
**Planning to grow:**
Hard-coded constants are fine for small projects but, eventually, as your software grows in size, you will wish you could change those settings without having to recompile everything. There are many times you will want to change settings while the game is running and you can't do that with hard-coded constants.

**CVars:**
Once your project grows, you might want to take a look at CVARs. A CVAR is a "smart variable", so to speak, that you can modify during run-time via a console, terminal, or UI. CVARs are usually implemented in terms of an object that wraps an underlying value. The object can, then, keep track of the value as well as save/load it to/from file. You can store the CVAR objects into a map to access them with a name or other unique identifier.

To illustrate the concept a bit further, the following pseudo-code is a simple example of a CVAR type that wraps an `int` value:

```
// just some flags to exemplify:
enum CVarFlags {
    CVAR_PERSISTENT, // saved to file once app exits
    CVAR_VOLATILE    // never saved to file
};

class CVar {
public:
    // the constructor registers this variable with the global list of CVars
    CVar(string name, int value, int defaultValue, int flags);

    int getValue();
    void setValue(int v);
    void reset(); // reset to the default value

    // etcetera...

private:
    int flags; // flags like: save-to-file, etc.
    int value; // the actual value
    int defaultValue; // the default value to reset the variable to
};

// global list of all CVars:
map<string, CVar> g_cvars;

```

**Global access:**
In the example above, I've assumed that the constructor of `CVar` always registers the variable with the global `cvars` map; this is quite useful, since it allows you to declare a variable like so:

```
CVar my_var = new CVar("my_var", 0, 42, CVAR_PERSISTENT);

```

That variable is automatically made available in the global map and you can access it from anywhere else by indexing the map with the variable's name:

```
CVar v = g_cvars.find("my_var");

```

**Persistence:**
When the game is shutting down, iterate the map and save all of the variables marked as `CVAR_PERSISTENT`, to a file. The next time the game starts, reload them.

**Case law:**
For a more-specific example of a robust CVAR system, check out the implementation featured in Doom 3.
> 32 votes

# Answer
Well first off an enum defines what the values *can be*, not what the values *are*. Thus you still need to declare another variable after you've declared the enum. For example:

```
public enum Sound
{
    ON,
    QUIET,
    OFF
}

public Sound soundValue;

```

In this example, you can now set `soundValue` to ON, QUIET, or OFF.

---

Then you still need to structure your code so that other parts of your code can access this "settings" object. I don't know if you need help with that part too, but common patterns to address this problem include singletons (those are frowned on these days) or service locators or dependency injection.
> 4 votes

# Answer
glampert solution is very complete, but I will add my personal experience.

I ran into this same problem, and my solution was to use an static Variables class.

The Variables class internally keeps a map from string to string (so far all my variables are only strings) and is accessed via getters and setters.

The point is that getting access to global variables can introduce all kind of subtle errors as totally unrelated parts of the code are suddenly interfering with each other.

In order to avoid this, I imposed the following semantics: using the `set` method throws an exception if a variable with that name already exists in the dictionary, and `get` deletes the variable from the dictionary before returning it.

Two additional methods provide what you would expect, `setAndOverwrite` and `getAndKeep`. The point of the semantic of the other methods is that you can easily spot errors of the kind "this method is supposed to initialize this variable, but other method did it before".

In order to initialize the dictionary, initial variables are stored in a json file, and then read when the game starts.

Sadly I haven't got too far away with my game yet so I cannot testify for the robustness of this approach. Still, maybe it can provide something interesting on top of CVARs.
> 1 votes

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


# Question
Title: Unity Rigidbody2D to act on certain gameobject only
I am creating a 2D game and the player object has a rigidbody2D attached to it. The game works fine until the player collides with a power up. The rigidbody physics get all messed up. So I was wondering is there a way so that rigidbody will only act on enemies and be disabled for power ups?

# Answer
> 0 votes
Yes, you can use layers, making the player and the power up different layers. This means they won't collide however, so it'll be difficult to detect when the player picks up the power up.

Alternatively, you can make the power ups have a collider, but set it to trigger. This means the power ups will not collide with other objects but rather only cause the `OnTriggerEnter` and `OnTriggerExit` events to fire when something collides with the power up.

---
Tags: unity, rigid-body-dynamics
---


title: Camera controller in a 2d platformer

text:
# Question
Title: Camera controller in a 2d platformer
I'm basically bumming around using Unity's 2D creation tools, and I've managed to create a little platformer physics demo. There's a lot of work to be done, but I've got basic movement down, some sounds working, basic jumping physics, and whatnot.

One of the things that's on my list of things to tackle is the camera system.

I experimented with locking the camera to the player position; it's simple, but works. However, I'd like to attempt to develop a more complex camera system that would follow level constraints, but still allow for free vertical and horizontal movement. Currently, I have the camera only matching the player's movement on the X axis, which means that jumping doesn't affect the camera. However, the camera won't follow if you climb a tall ladder.

(Think of the viewport from the Megaman X SNES games; there are many vertical and horizontal segments, but the camera is smart enough to let the player character (X) jump or cling to walls at the edge of the viewport without moving, yet move when the player is in an open area. This is the type of camera I'd like to achieve.)

I'd like to know how this problem is commonly approached. I thought about creating a spline, perhaps, and having the camera follow the spline path while still tracking the player. This spline would be specific to each created level. However, I'm not sure if this is the correct solution (and I'm not sure how it would work in open areas). The other thing that might be possible could be to set bounds for the actual camera limits, and not allow the camera to move outside of that, but I feel as though that might be a brittle solution in tighter areas.

Could someone with experience point me to any resources, or suggest advice to go in the right direction? Thanks!

Edit: To make this more clear, I've included a link to Flame Mammoth's stage in Megaman X. Notice how, in the first part of the stage, X can dash along the ground, while the camera tracks his x-position; later, it tracks his y-position when he falls down a shaft. Further on, there's a large room where the camera tracks X's movement without any boundaries until he gets close to the top of the screen; the camera doesn't pan past those boundaries.

Of note, I found a solution here that helps with jumping; I believe that MMX uses a variant of this. However, notice that in the custom game at the bottom, the camera is allowed to pan "out of bounds" as it's not limited by the level.

# Answer
Just go really simple. Add a flag to the player that tells the camera when they're jumping. If they're jumping, don't follow them up.

The other situation you need to handle is when the player jumps up or down to different levels. In this case it would be pretty simple to start tracking again when the player touches down, or if the player goes below the starting position of the jump, the camera will start following again.

For keeping the camera in bounds, you have a few different options.

* Create a bounds object that the camera tests before moving to ensure that it doesn't move outside. This is a quick and easy thing to implement, but only deals with the camera position, and not the view frustum. This means you might have to do a lot of tweaking to the bounds to make sure it doesn't see anything outside the bounds, and gets tricky-er if you have any kind of zoom. To implement this, you can create a number of objects with bounds, add them all to the same layer, something like `CameraBounds`, then, when testing a new position before moving there, do something like a physics overlap sphere (passing in the `CameraBounds` layer mask) to make sure the new position is inside one of your bounds objects.
* Unity has a method called `OnBecameVisible`. You can place objects near the outside edges of your level. When these become visible to the camera, they tell the camera to stop tracking in that direction. This'll take some tweaking to get a smooth feel, but would ensure that no matter the zoom or camera position, you wouldn't see anything outside the level.
* Finally, you have a predefined path. This is a path that the camera will "gravitate towards". The camera will also follow the character, but the farther it gets from the predefined path, the less effect the character's position has on the camera position. This will likely give you the best results, but is also probably the most work.
> 1 votes

---
Tags: 2d, unity, camera, platformer
---


title: Issues compiling .fx shader to MGFX

text:
# Question
Title: Issues compiling .fx shader to MGFX
I've been trying to port Catalinzima's 2D lighting example over to MonoGame to try and get some basic understanding around it and adapt it for use in my engine. I've been trying to convert the two .fx files provided with it to MonoGame compatable .mgfxo files. The first file ran through the converter and compiles successfully. However, the second file ran into issues converting; cmd Dump:

```
C:\Program Files (x86)\MSBuild\MonoGame\v3.0>2MGFX.exe resolveShadowsEffect.fx /DEBUG
C:\\Program Files (x86)\\MSBuild\\MonoGame\\v3.0\\resolveShadowsEffect.fx(213,8):
error X5608: Compiled shader code uses too many arithmetic instruction slots (85). Max. allowed by the target (ps_2_0) is 64.
(1,1): error X5609: Compiled shader code uses too many instruction slots (99). Max. allowed by the target (ps_2_0) is 96.

Failed to compile the input file 'resolveShadowsEffect.fx'

```

So i thought fine, ill just change the PixelShader model to ps\_3\_0. Now this converts fine, but fails to compile in visual studio with the following errors:

```
A namespace cannot directly contain members such as fields or methods (1, 1)

```

and..

```
Unexpected character '' (1, 5)

```

In the visual studio error message this character shows as '|' but its not the same when i paste it out.

I've tried comparing the first lines of the files, but have not been able to notice any differences.

I'm pretty new to using shaders, so i haven't been able to debug whats going on effectively. Any ideas?

You can find the original shader files and compiled versions here: http://puu.sh/9ZfMe/efe8fbaf9d.zip

# Answer
> 0 votes
This has been resolved. i had the effects file set to 'Compile' instead of 'Content'

---
Tags: shaders, monogame
---


title: neon effect to textures libgdx

text:
# Question
Title: neon effect to textures libgdx
I am working on a live wallpaper with Libgdx . I am wondering if I can give neon glow to my textures , at runtime . Is this possible? If yes can anybody give me any pointers?

# Answer
Theoretically, sure. Two approaches come to mind:

1. Write a shader
2. Fake it

For faking it, you could draw four copies of the sprite (offsetting horizontally and vertically by 1px above/below/right/left of the main image) and tinting that to your neon colour.

I haven't tried it, so your mileage may vary.
> 0 votes

---
Tags: libgdx
---


title: How do I create a knockback-movement?

text:
# Question
Title: How do I create a knockback-movement?
I am a web developer new to game development, and with limited math knowledge. I am writing a character movement controller in Unity. The game has an isometric *Diablo*-like camera. The character moves on mouse click within a limited area.

The character moves like this now:

I want it to move like this:

I don't need you to write the code for me: I just want to understand what the math for this looks like. A Unity- and C#-specific explanation would be great, but not necessary.

# Answer
First code, code the normal movement of the character to progress a constant distance toward the target position every frame (ie. inside the Update() function).

Then put that movement code inside an if statement for if the character is being knocked back. Only move toward the target if not being knocked back.

If being knocked back, move toward the knockback target instead. Set the knockback target and the "is being knocked back" variable when the player is hit, and clear them when the knockback target is reached.

For the actual decelerating movement toward the knockback target, there are a number of ways to do something like that. One simple way is by decrementing the movement distance every frame; instead of moving a constant distance every frame, the "distance to move" variable gets smaller every frame.

Another way would be using what are called tweens, setting an "ease out" value for the movement. Tweens are slightly more complicated to setup, but once setup will make it very easy to do short targeted movements like this all over your game.
> 1 votes

# Answer
The proper way to make this 'knockback' movement is by applying an impulse on the knocked object. The impulse will be in the direction of the velocity of the hitting entity (the projectile), scaled to some number that fits your game (that should probably take into account the masses of the two objects).

To make the entity slow down gradually after the hit and eventually stop, you need to constantly (every frame) apply on it an 'air friction' force (actually more of an impulse applied every frame since it changes), which is a force opposite to the entity's current velocity, scaled to some number. Do this for all entities every frame. This will make them always slow down gradually after being hit. (This is also (generally) what makes a car in the real world not move forever after being hit by another car, but gradually slow down and stop moving). This will allow you to apply an impulse on an entity in a collision and then not worry about it anymore, things will take care of themselves.

To understand this you need to have a good basic understanding of vector math and basic physics. If you're not familiar with these topics I suggest you learn them. Once you understand them a lot of physics-stuff becomes simpler.
> 0 votes

---
Tags: c#, unity, mathematics, movement
---


# Question
Title: Top-Down Octree Generation of Procedural Terrain
I'm trying to implement a voxel-based terrain generation system in Unity3d (C#). I have successfully implemented a uniform 3d grid system, and have extracted the isosurface out using Marching Cubes and Surface Nets algorithms.

I quickly bumped up against the inherent issues in representing all space with a 3d grid. Much of this space was either above or below the surface, and I turned to space partitioning with octrees, as it didn't seem too difficult. One of the great things about octrees is that octree nodes that that don't have edges intersected by the surface don't need to be split again.

I researched, and found a couple resources to construct my code. One is Volume GFX, and another is the original Dual Contouring paper by Ju et al. My edge-checking is done by the Marching Cube's checking from Paul Bourke's code. If the "cubeindex" is either 0 or 255, then no edge is intersected, and the octree node does not need to be split.

My Octree generation code works for something like a quarter-sphere, where the surface features are extremely normal:

As seen in the picture, only octree nodes containing the surface are subdivided. Working great.

Now, however, when we move to something more complex, like Unity3d's PerlinNoise function: GASP! What's that hole doing in the mesh at the lower-right corner? Upon closer inspection, we see the octree didn't subdivide properly (red lines highlighting the offending node's dimensions): This turns out to be the same issue Jules Bloomenthal highlights in her paper on polygonization, page 10, Figure 10. Traditional methods at generating top-down octrees ("Adaptive Subdivision"), are sensitive to fine surface features relative to the size of the octree node.

The gist:

```
X-------X
|       |
|       |  <- Node
X--/\---X     X's - tested values, all outside of the surface!
  /  \  <- surface

```

The surface breaks the surface, but comes back down before it goes over a vertex. Because we calculate edge intersections by looking at the signs at the two vertices, this does not flag the edge as crossed.

Is there any method to determine if these anomalies exist? Preferably, the solution would work for more than just the Unity3d noise function, but for any 3d noise function (for cliffs/overhangs/floating islands, etc).

UPDATE

Thanks to Jason's awesome answer, I was able to answer my own questions I asked (in the comments under his answer). The issue I had was that I didn't understand how I could create a bounding function for trigonometric functions (sine,cosine,etc) due to their periodic nature.

For these guys, the periodicity is the key to bounds functions. We know that sin/cos reach their extrema values at a set interval, specifically every `π/2`. So, if the interval we are checking contains any multiple (cos) or half-multiple (sin) than 1/-1 is the certain extrema. If it doesnt contain a multiple (i.e. the interval `[0.1,0.2]`), then the range is simply the values of the function evaluated at its endpoints.

UPDATE 2:

If the above doesn't make sense, check Jason's answer to my comments.

# Answer
> 6 votes
I will assume that you have a function `f` such that the surface is defined by `f(x,y,z)==0`. Right now, all you have is the function `f` itself, and so with no further information, it is impossible to know when to subdivide. It is always possible for the surface to do what you describe, i.e. the function `f` can have arbitrarily thin "fins" which can require you do go arbitrarily deep in the octree.

The only solution that allows top down generation is to have additional information on `f`. Right now you have a *point query*: you can determine what the value of `f` is at any particular point, but you have no guarantees about what the value will be at any other point, even ones right next to it. Instead, you need a *bounds query*: given a AABB, it determines what the maximum and minimum value of `f` is over that range.

Now it is simple: for each octree node, perform a bounds query. If the minimum is greater than zero or the maximum is less than zero, do not subdivide. Otherwise, subdivide unless you are at the smallest size, in which case you can use the point query on the corners as usual to construct the surface.

It is easy to write the point query for interesting functions, but it is not clear how to write the corresponding bounds function. However, our job is made easier by the fact that we don't need to be precise: calculating the exact min/max is not going to be particularly useful anyway, because we are just going to compare them to zero. So really we just need to calculate and interval \[a,b\] which completely contains \[true\_min, true\_max\] over the given AABB bounds. If we are close to the true range, we will subdivide mostly things which actually contain the surface, and if we are loose and give much bigger ranges we will end up dividing more nodes than is necessary. However, as long as we make sure to contain the true range we will never miss part of the surface.

As an example, we can construct the bounds function for the sphere function. (To see why your technique doesn't work even in this case, start with a sphere which is entirely contained in the starting cube. The algorithm will terminate immediately!). The point function is `f(x,y,z) = dist(<x,y,z>, center) - radius`. We see that this function depends only on the distance from the point `center`, so is really at its core a 1D function. First, we determine which range of radiuses our AABB covers. A simple but slow way to do this is to determine the distances for the 8 corners and take the minimum and maximum distances. The only special case is that if the center is contained in the AABB, then the minimum is zero. Now we have a range of radiuses, and by plugging in the function `f(r) = r - radius` will give the desired range for values of `f`.

Of course, that was a simple example; you probably want something more complicated than spheres. The nice thing about this approach is that you can combine such bounds functions. For example, if you add two functions together, say `f + g`, the bounds function for the sum can be easily constructed in a conservative manner as: the min and max are just the sum of the mins and maxes respectively of the two functions. To see this is conservative, consider the functions `sin(x)` and `-sin(x)` in 1D. Clearly over any range greater than 2pi these each have a range \[-1,1\], and so the calculated range is \[-2,2\], but the real range is the interval \[0,0\] containing just 0! All hope is not lost, however: if we zoom in on a small range for x, then the interval gets smaller (closer to \[0,0\]) as well.

This means if you can bound one octave of Perlin noise, then you can bound a full fractal noise, which is just a sum of many individual octaves. Actually, if we can bound individual functions, we can use the rules of interval arithmetic to construct more interesting functions. In particular for procedural synthesis, summation, minimum/maximum, domain distortions, and scaling by constants can all be handled by interval arithmetic, which let us add surface texture, place objects, and distort & scale without needing to write complicated bounds functions. So we can write `f(x) + min(g(x), h(x)) * 4 + h(2*x)` for the point query, and automatically (but imprecisely) construct the corresponding bounds function, assuming we have the bounds functions for `f`, `g`, and `h`.

Finally, some functions are not easily expressed as a simple combination of others. In that case, you can often bound the derivative and use that to bound the value of the function. This is somewhat more math intensive though, so I won't cover it here.

### Implementation note

It is probably easiest to represent a function `f` by a pair of functions:

1. a point query `f_point` which is a function taking a point to a float.
2. a bounds query `f_bounds` which takes a AABB to an interval \[min,max\].

Then you can write combinators like Sum, Scale, etc. which take these pairs and return new ones which are the combination given. You can represent these as tuples, objects, etc. depending on the language.

---
Tags: unity, graphics, procedural-generation, terrain, voxels
---


# Question
Title: Why might a PC game have a set number of resolutions?
There's an obvious reason games choose to use a set number of resolutions in fullscreen mode - a machine only has access to its own set of resolutions, and the intersection of the two sets determines what resolutions the game can run. However, even in windowed mode the user is often limited to some set of resolutions. What are some reasons games might opt to limit the size of the window in this way, rather than let the user dynamically resize the window themselves?

# Answer
Limiting the set of available resolutions has a few benefits:

* Reduces the set of testing permutations. From a testing perspective, limiting the end user is great :). When testing to make sure a level in the game is seen in its entirety, or the GUI layout looks right or whatever the case may be, having a limited set to test is easier than having a dynamically sized window.
* Fixes the aspect ratio to ratios your game supports. Many developers assume the game will be viewed in a certain aspect ratio. This allows them to layout their game in a certain way to fit that aspect ratio. This includes the shape of the perspective (the shape of game levels in something like a top down game, or the , the art assets used to create the GUI and more.
* It's what's expected. Having an available list of resolutions for the user to choose from is an expected option. (yes, this doesn't mean the developer can't have both).
* It's easier. Developing a dynamic resolution game has a number of challenges, including those mentioned above.

Dynamic resolutions are essentially an additional feature that needs to be planned for, developed and tested. It's not altogether clear that it's a feature that a majority of gamers want either. This can make it not worth spending the resources to develop that functionality.
> 4 votes

---
Tags: pc, window-management
---


# Question
Title: Designing Character Movement Need Advice
(This game is written in C++ with GDI+ It's a simple side-scroller.)

I am having a problem deciding on how I should handle player movement. Currently it runs at 20 frames per second (I just chose that number, it could no doubt run at higher fps.)

Now I have one function that moves the character 1 pixel. It checks collisions with anything around.

There is two ways I can do this (because moving 20px/ second is too slow.)

* I can use a for loop and then I can move any amount of space per frame. One minor problem is that the player will be moving several pixels between screen updates, so the player moves 5px (or any amount) increments every second.
* I can turn up the fps, and then, consistently move the character 1px per frame, and it would be smooth movement.

I am having trouble deciding which way of doing this is better and need a bit of input, ideas, advice, etc...

Thanks.

# Answer
There is nothing wrong with moving multiple pixels per frame. In fact, that's typical of most games. Even 2D games often store the character's position using floats, typically in a different space (world space), and then translate that to view space and then to pixels before rendering.

The main problem you might run into is that is the character moves really fast, and you only check collisions once per frame, you might actually miss a collision. In practice this only happens for objects that move REALLY fast, like bullets. In this case you can do multiple collision checks, like you suggest in your first option, or do collision using a different test that takes into account the movement (Google Continuous Collision Detection).

I would strongly advice to decouple the movement from the framerate, so you can tune the velocity of the character without affecting the smoothness. Also, bear in mind that some systems may have inconsistent framerate, which will make the game play badly.

Finally, 20 fps is low for most games, especially action games like a side-scroller. Aim at least for 30 fps, try for 60 if your game requires quick reflexes.
> 2 votes

---
Tags: c++, game-design, movement
---


# Question
Title: Unit turning in navmesh-based pathfinding
I'm working on an RTS game, and I'm using navmeshes for unit pathfinding. I do know how to find a general path within a navmesh, but how do you determine if the unit have enough space to turn?

I have units of different shapes (mostly rectangles with different dimensions), and with different turn radii. Additionally some of units can turn in place, and some can move in reverse.

So, how to find a path which unit can follow, considering that it can not rotate easily?

# Answer
> 2 votes
First of all, a warning. The problem you're trying to solve is complex enough that most professional games don't even bother unless it's a key part of the gameplay. So my advice would be to cheat as much as possible.

For vehicle radius, I would try to use the worst case (the largest dimension) and then treat the vehicle as a cylinder (or a circle, in 2D) for pathfinding. With navmeshes, you can either have a different set of meshes that take into account the different radii, or make the pathfinder stay away from the wall a certain distance. In either case, picture pushing the edges of the navmesh inwards and rounding the corners (this is technically called a Minkowski Sum). Then you can treat the vehicle as a point, in this expanded navmesh.

If you want to take into account turning, you'll have to encode those rules in the pathfinder itself, as it expands. For instance, if a vehicle can't turn in a tight radius, you'll have to both discard some of the polygons offered as connections from the current one, and use this information when optimizing the path during string pulling. In general, you'll also want to encode some of this logic in the heuristic, so that paths try to minimize turns and look as natural as possible.

# Answer
> 1 votes
If you can define the minimum width of the passage that a particular unit requires to be able to pass through then you could subtract that to narrow the polygons on a candidate route on the navmesh. If a part goes negative then you see that it can fit through. Perhaps you can create a passable solution this way, even just by defining safe such width requirements manually for the units.

That is not at all perfect as does not take into account how steep corners are difficult for example for very long vehicles. I suppose there are algorithms to fit shapes inside containers and detect if they don't fit (a simple intersection check would do that but I don't know how to come up with the candidates to check, apart from brute force). Even that would not take into account the turning radii and whether the unit can reverse or not.

# Answer
> 1 votes
Apparently the Corridor Map Method (CMM) is an accepted answer in this similar question, 3D RTS pathfinding

It seems to take account the turning radii in the steering but I did not see anything about the dimensions of the vehicle so not a complete solution to your problem I think.

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


# Question
Title: Problems with Obstacle Avoidance steering behavior
I learned how to implement the Obstacle Avoidance steering behavior from this tutorial. The approach depicted in this tutorial (simplified) is this (note that I'm using rectangular OBBs for obstacles, not circles):

The entity that avoids obstacles will have a 'ahead' vector, representing the entity's 'sight'. It will be equal to the velocity vector, but scaled to some length (the "sight distance").

For each entity in the "sight distance" radius from the entity, we check if it contains the the 'edge' of the ahead vector, marked with a red dot (actually the vector itself treated as a point):

For an entity that contains the red dot, we calculate the vector from the center of the entity to the red dot:

This vector (scaled by a scalar `MAX_AVOIDANCE_FORCE`) is the avoidance force. We apply it on our entity, and it should avoid the obstacle.

However, what happens in practice after applying the force is this:

As you can see, the entity is about to get stuck on the obstacle. That's because it doesn't sense it's about to collide, because the obstacle doesn't contain the edge of the 'ahead' vector.

So: what would be a good solution to this problem? How should I implement the algorithm?

# Answer
> 2 votes
One good solution is to send 2 rays from the upper and lower bound of the object rather then in the middle. You can then use the algorithm you were using before but use collisions for both rays rather then one. Don't forget to set the direction to the correct value of only one ray hits something (that is away from that ray). If both rays hit an object just make a choice (or ask the object what it's upper and lower bounds are and move towards what is closer)

# Answer
> 0 votes
One way to solve this, given you're treating you entity as a point, is increase the size of the avoid targets by the size of the main entity.

With circles you just add you radius to each target.

Also circle targets are quite easy to check if you compare the squared radius. So you don't need to take the root of vector of differences of the points.

some code to demo, if you have a pow function or macro:

```
#define pow2(a) ((a)*(a))

```

then for each entity to store a squared version of it's radius:

```
entX.powrad = pow2(entX.rad)

```

then to compare the `ahead` in your picture verse `entC` you can do:

```
pointInCircle = (pow2(ahead.x-entC.x) + pow2(ahead.y-entC)) < (this.powrad + entC.powrad)

```

I'm sure this is simpler than using a square.

# Answer
> 0 votes
If you want to keep your agents as OBBs, then you'll have to do a proper intersection test.

The problem you're having is that you're treating the moving entity as a point, and doing a simple raycast. You'll have to do a sweep test.

If you're sticking with OBBs that can move in arbitrary directions an exact solution will be hard work. This article explain how to do sweep tests but only covers circles and AABBs. This question answers how to do OBB intersection, but doesn't include sweep tests. But an extruded OBB is no longer an OBB, so you'll have to do general convex shape collision, which is harder. Here's a discussion.

Alternatively, you can cheat a little by doing multiple OBB tests, moving the entities a bit each time. Depending on the speed at which they move, two or three tests might be enough (one halfway, one at the end point).

If you don't find an intersection, all is good, the path is clear. If you find one, then you need to find the direction of steering. For that, you can just check which side of the movement direction the obstacle is, by doing some vector math (cross product is your friend). You can use the center point of the obstacle for this, like in your example.

This solution will address your problem but is not perfect. This steering method is fully reactive, and will get in trouble in certain scenarios (like a cul-de-sac).

---
Tags: ai, steering-behaviors
---


title: Game AI Implementation

text:
# Question
Title: Game AI Implementation
I'm very new to game development, but an experienced software engineer. As an introduction to game dev, I'm making a 2D zombie game in Python, using pygame. The game is almost done, but I still have to write the AI for the other humans and the different zombies in the game.

Should I have a centralized AI module that looks for the position of each character and zombie and determines the best way to move each of them? Or should each instance of a zombie or human be responsible for its own behavior?

In my mind it is more straight forward to make each unit responsible of it's own behavior and I think that it would be easier to give them a more "natural" look implementing it this way. However it's probably a lot more inefficient in memory and processing time that a centralized one. Again, I'm super new to games so any example of how is the AI implemented in some major games would be appreciated.

I understand this is probably a very subjective question, but I'm looking for an answer that covers something like pros vs cons, industry standard or known cases of each one.

# Answer
If it were me I would give each NPC agency of their own - if each one has a simple goal ( get as far as possible from Zombies/get as close as possible to humans ) that they act on, you can get quite interesting behaviours from relatively simple inputs without too much processing.

The downside of this is that if you have a lot of them around you are going to need to do a lot of processing on each decision cycle so if you have large levels you may want to have an overview AI for the area outside of the user's viewport, just controlling how many NPCs are in the area and occasionally posting some new ones into view, and then the agent-based approach for those that are currently visible.

The best approach for your particular case will undoubtedly be to experiment with the options and find the simplest case that is fun. As a general rule, the more complexity you add the more frequently it will fail. Because AI tends to be non-deterministic it is way harder to validate its operation with automated tests, but fortunately manual tests are often either interesting or hilarious, so it has its merits.
> 5 votes

# Answer
The first decision has to come from what the gameplay requires. There are some behaviors that are going to require coordination, and will be easier and more efficient to implement in a centralized way.

To look at it from a purely performance/architecture point of view, let's assume that you want individual behavior. It's unlikely that you can reuse a lot of computation, as AI is usually very context-aware. You have to pathfind and cast rays from the position of each character, so the results will be different. Besides, unless required by the game design, if all characters react in the same way at the same time you'll get a very poor result, with everybody moving in perfect sync.

In practice then, the only CPU benefit you're going to get from running all the behaviors in a centralized way is saving the instruction cache. Because you're coding in Python, I'd say that's not a prime concern :)

In terms of memory, the best way to store the information is to split it between shared data and instance data. Shared data will include definitions, tuning, etc. If you use behavior trees, the behavior tree can probably be shared. Instance data is what relates specifically to that character: their position, their state, which BT node is active, etc. This will give you most of the savings you'd get from centralizing the AI.

Finally, when you need some coordination, look up Blackboard architectures. Create a common place where individual characters can add pieces of data to communicate with each other (for instance, if you only allow one character to attack the player at once, you could put a reserve token there).
> 1 votes

# Answer
In this article the autor is talking about Group behavior. Still I guess it depends on your requirements whether you decide to implement a centralized AI or not.
> 0 votes

---
Tags: architecture, ai
---


title: Identifying groupings of objects

text:
# Question
Title: Identifying groupings of objects
I have a cloud of objects, each with a 3D position, and I want to pick out tight groups of these objects.

Specifically, I want to find all objects which form a grouping of radius r within a large cloud of objects. It is likely that the objects are spaced out in vague groupings already, but I need to identify these and essentially put a sphere of radius r around them.

I would prefer to avoid a brute force method if possible - which I presume would be a process of comparing objects against each other to find two within a distance 2r of each other, then putting a sphere in the middle and determining what other objects are within this sphere.

My actual use case is not games related at all, but if an game based example use case would help, here is how I might use it in a game;

The player is flying a plane over a battlefield and has been given orders to bomb the enemy.

To assist the player I want to highlight tight groups of enemies that make prime targets, however the troops on the ground do not move or coordinate in a flocking system, they move completely as individual entities.

Given those criteria, how might I identify the largest groups of objects within the bomb's blast radius?

# Answer
To avoid brute-forcing, you could store the coordinates of your objects in a three-dimensional tree data-structure like a kd-tree or an AABB tree. These data-structures are very efficient at getting all objects withing a certain *box-shaped* area. To get all objects within a *sphere-shaped* area, you could first get all objects within a box which is large enough to contain the sphere to get a pre-selection.

But before you invest all that effort: Are you sure it actually matters? Did you measure it with a profiler? When your number of objects isn't very high, a  algorithm which calculates the distance between every object and every other object might not actually be so slow that the player notices a framerate drop.
> 3 votes

# Answer
A kd-tree or AABB tree is a great data structure, if the objects are going to be static, or mostly static, as they are not cheap to update.

But it seems like those structures would be more useful to find what's around a certain point, rather than to figure out the largest cluster of objects.

For that, I'd use a simple grid. Have each object register itself in a square in a rectangular grid. This will effectively simplify the problem, so you can then go and score each square based on how many objects there are inside, plus some factor from the neighbors. The complexity will be related to the number of squares in your grid, instead of the number of objects in the map.

And as objects move around, you just remove that object from a square, and add it to another.

Finally, the grid will also allow you to run queries to find objects near a point if you want, by considering more than one square and then calculating distances with the objects inside it.
> 1 votes

# Answer
The other's have suggested kd tree's but I think that a more appropriate data structure for you would be using an R-Tree which is specifically for retrieving *collections* of near objects.

You can find out more here: http://en.wikipedia.org/wiki/R-tree
> 1 votes

# Answer
A high-powered family of algorithms you may need to look into are all "clustering" algorithms. These algorithms find groups of data points which could be Cartesian points or any other property (color, weight, etc.).

See K-means Clustering for one such algorithm. It's not a terrible algorithm to run in real-time, depending on how many entities you need to compare and how often you need to run it. Since there's presumably only one player and you only need to identify clusters nearby to the player, you shouldn't have much trouble with this algorithm.

There are other simpler algorithms to this, though I'd just start with k-means until you have firm evidence that it won't work for you.
> 1 votes

---
Tags: c++, collision-detection, ai
---


# Question
Title: How to find point on a circle that's opposite another point?
How do I find the coordinate of point and angle value on circle sprite which placed on opposite side of sprite from a touch point and the center point of the sprite?

I know A position, B position and sprite circle size. How do I calculate the position of C? and the angle it is around the sprite circle?

# Answer
Calculate a vector from B to A, normalize it (divide by the vector's length), then multiply by the circle size:

```
vx = A.x - B.x
vy = A.y - B.y
length = sqrt(vx*vx + vy*vy)
C.x = vx / length * size + A.x
C.y = vy / length * size + A.y

```

For the angle you can use the atan2 function, if your language has it.
> 8 votes

# Answer
to complete the answer:

```
angle = atan2((C-A).y, (C-A).x) + PI/2;

```
> 4 votes

---
Tags: vector, linear-algebra, angles
---


# Question
Title: Modeling "singletons" in an Entity-Component System
I'm writing a basic Asteroids implementation as an exercise in learning how to think in entities and components, and most of it is fairly straightforward. But one thing I keep running into is situations where a given system needs a certain entity/component and I know there's only ever one of it. Examples:

* `MovementSystem` needs to know the bounds of the `World` component so it knows when to wrap to the other side of the screen
* `LevelSystem` needs to know the `GameState` component so it knows whether it should create new asteroids
* `InputSystem` needs to know the state of the `Keyboard` component

(etc.)

The ECS I'm using is hand-rolled but conceptually similar to Adam Martin's Entity System RDBMS Beta - Java. What I find myself doing repeatedly for cases like the above is asking the `EntityManager` for "all" components of the given type and taking the "first" (aka only) one:

```
World world = entityManager.getAllComponentsOfType(World.class).iterator().next()

```

This works but seems clunky, and makes the code annoyingly non-obvious. Alternatives I've thought of:

* make each system loop over 'all' of these components, just as they would any other component type
* add explicit support for 'singleton' components to the `EntityManager`
* don't use components for these things; inject them into the systems some other way, and live with the fact that this makes the design significantly less pure

Is there a typical or well-known solution to this problem?

# Answer
> 14 votes
Remember to not get carried away with entities and components. It's totally fine to *not* have your `World` as a component. If you know for sure there's only going to be one of something, it doesn't make much sense to make it a component. Components are made to be reused in numerous entities, combined with other components.

This doesn't make the game less pure, it makes the code cleaner. Entity systems are just a tool for part of your game, it doesn't need to be all encompassing to be a good system. Use it only where it makes sense to *you*.

# Answer
> 1 votes
As others have said, singletons don't have to be implemented as components. Storing that data directly in the systems or some external singleton class is fine, as long as only systems are accessing it. However, if you really want to keep your design 'pure' (it makes serializing the whole game state much simpler if all the data is in components, for example), consider using a static field or getter in the component directly, e.g. "World.instance".

# Answer
> 0 votes
One way of doing that is to implement a messaging system in your application. You can then generate events on the creation of specific components.

`MovementSystem` can simply register to the event manager for the event `WorldComponentCreatedEvent` and when you create your world component, the `MovementSystem` will receive the event which can hold a ref to the world as the event data.

---
Tags: entity-system
---


# Question
Title: Copy unaligned XMVECTOR and use the copy?
I know XMVECTOR has to be 16-byte-aligned and therefore shouldn't be a member of a class (unless I ensure the alignment). However, can I do sth like this?

```
class A
{
    public:
    XMVECTOR vect;
};

void fun(void)
{
    A a;
    XMVECTOR localVect = a.vect;
    // can I now use localVect correctly?
}

```

Edit: My question isn't "Can I use `XMVECTOR` as a member variable?". It's "Can I copy an `XMVECTOR` **instance that's not guaranteed to be 16-byte aligned** into **one that is** and then **use the latter one** without any problems?".

# Answer
> 1 votes
Answering the question after the edit:

If `XMVECTOR` was allocated on the stack then the compiler will automatically force it to be 16-byte aligned.

The only case that you have an unaligned XMVECTOR is when it's allocated on the heap, but should't be used at all, because it will result in a seg-fault.

On the other hand if you are accessing the XMVECTOR as a memory chunk using its address, in other words without doing any computation it won't be copied to the SSE registers. You can copy it just like any other POD. The problem isn't accessing the memory, the problem is about using it, so **copying it is OK as far as you don't do any math operations that use SSE registers.**

# Answer
> 1 votes
If you are only building for x64 native, this code is perfectly fine since it is always 16-byte aligned.

```
class A
{
    public:
    XMVECTOR vect;
};

void fun(void)
{
    A* a = new A;
    XMVECTOR localVect = a.vect;
}

```

To make it portable to x86 or ARM (32-bit), you have one of three choices:

1. Create an overloaded new for the class A that uses \__aligned\_malloc(,16);
2. Create a global new overload that does this (which is not recommended)
3. Just use XMFLOAT4 or it's kin and explicitly use XMLoadFloat4/XMStoreFloat4

The following code results in the identical compiled code as the block above except that one movaps is now a movups:

```
class A
{
    public:
    XMFLOAT4 vect;
};

void fun(void)
{
    A* a = new A;
    XMVECTOR localVect = XMLoadFloat4( &a.vect );
}

```

As such, there's no point in messing around with aligned allocations unless it's trivial to do for some other reason (such as DirectX Tool Kit's use of the pImpl idiom which means we might as well align the internal class allocations to make it convenient).

If your complaint is just the extra work it takes to use XMVECTOR correctly with respect to the alignment, you could take a look at using SimpleMath from the DirectX Tool Kit.

---
Tags: c++, directxmath
---


# Question
Title: How to change the Android NDK jni calls dynamically?
Some people are using NativeActivity for working with Android projects exclusively in C++, but this also carries some disadvantages, so I, like many others, decided that I'd use instead a Java glue code; just a single Java file wrapping all things I need from C++, where pretty much everything runs.

With this said, as far as I know, using this Java code forces me to implement the native function calls in Java, where the Java calls a function that is actually called within the C++ part of the project, with the JNI.

In C++, the native function being called has a prototype like this:

```
JNIEXPORT void Java_com_package_name_nativeTouchDown( JNIEnv*  env, jobject thiz, jfloat x, jfloat y );

```

My problem is that I started working with scripts exclusively and would like to find a way to not having to recompile the C++ code anymore. So when I want to make a new project, I just copy-paste my C++ compiled code and change the scripts and be allowed to change the package name of the app without any recompilation.

Is this possible somehow? At the point I am at, I simply have to recompile my C++ to conform to a new package name (the one in the format `com.company.game`). Can't I make C++ fully abstracted from this package name or change it dynamically?

# Answer
> 1 votes
Your package name doesn't need to match the package where you put your classes.

When you write your AndroidManifest.xml you specify both the package for the game and the path to your activity. So use something like `com.company.engine` for your activity and your C++ and just create a new package name for the game.

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


# Question
Title: Conversation tree and question locking/unlocking
I have been having issues with managing a conversation tree. I am using PAWN as a scripting language (I have no other options, unfortunately) and I use MySQL databases to store user and game data.

My current issue is storing game conversation trees using SQL. Currently, I have the following table:

```
TABLE NAME: dialogue
ID: global ID of conversation option
Prompt: question or sentence shown on player's screen
Answer: NPC's answer
[some other stuff related to conditions and mood checks, etc.]

```

Now, my problem is the following. Suppose I greet the NPC, this would be something like this:

```
ID: 1
Prompt: Hello there.
Answer: Hi, how's it going?

```

I want my conversation tree to progress after the player greets the NPC. This is not problematic, I simply use an additional SQL table for that:

```
TABLE NAME: dialoge_unlock_lock
ID: global ID of dialogue element
Unlocks: option this element unlocks
Locks: option this element locks.

```

My problem is the following: suppose I greeted the NPC, this would unlock 5 conversation options for the player to choose from (they would have IDs 2-6 for this NPC, and perhaps 241-245 for another NPC). I choose question #2, this would unlock question #8 and lock question #7.

How could I check what questions the player has locked in the current dialogue tree? In this example, I don't want the player to just see question #8, but I want him to see every question that is currently available to him (that is, questions 2-6 & 8).

I have been sitting on this for days and I can't figure out a way to do it. This pretty much sums up my attempts, any help would be greatly appreciated.

# Answer
Because you say you use MySQL to store user data, I'd imagine that you'll want to use it to store which questions are locked/unlocked, as the player interacts with the game.

In that case, you'd have some tables to represent the state of the player. Something simple like:

```
TABLE NAME: unlocked_options
ID: global ID of options unlocked

TABLE NAME: locked options
ID: global ID of options locked

```

In this way, as the player makes choices, you add and remove lines to those tables. Then you query them to present the player with the right options.

If you don't want to store the state in the database, then you'll have to keep track of it in memory, using a Pawn data structure. Two simple arrays should do the trick, one for locked, one for unlocked, and again you add and remove IDs are the player progresses. If you don't need the persistence of the database, this might be a faster alternative.
> 1 votes

---
Tags: sql, npc, dialogue-tree
---


title: How to use sprite as font in Unity?

text:
# Question
Title: How to use sprite as font in Unity?
I've started working on my first game in Unity; It's very simple, there's a spinning block in the middle, and there are spinning blocks coming from all sides. When they hit the middle block, you lose a life. You have 3 lives. I've hit a bit of a brick wall, here, though; I can't seem to find anywhere how to use a sprite atlas as a font, or at least be able to sprite my own font. Does anyone know how to do this?

# Answer
> 2 votes
If you don't need fancy texture in your fonts, Unity supports True Type fonts, so you can render your text easily using the GUI system (for instance, drawing a Label).

In order to use Bitmap fonts you'll have to write the code yourself to translate the characters into sprites, or use one of the libraries available, like NGUI or Daikon Forge.

---
Tags: unity, javascript, sprites, unityscript
---


# Question
Title: how to retain the animated position in opengl es 2.0
I am doing frame based animation for 300 frames in opengl es 2.0

I want a rectangle to translate by +200 pixels in X axis and also scaled up by double (2 units) in the first 100 frames

Then, the animated rectangle has to stay there for the next 100 frames.

Then, I want the same animated rectangle to translate by +200 pixels in X axis and also scaled down by half (0.5 units) in the last 100 frames.

I am using simple linear interpolation to calculate the delta-animation value for each frame.

Pseudo code:

The below drawFrame() is executed for 300 times (300 frames) in a loop.

```
float RectMVMatrix[4][4] = {1, 0, 0, 0,
                            0, 1, 0, 0,
                            0, 0, 1, 0,
                            0, 0, 0, 1
                           };   // identity matrix
int totalframes = 300;
float translate-delta;  // interpolated translation value for each frame
float scale-delta;  // interpolated scale value for each frame

// The usual code for draw is:
void drawFrame(int iCurrentFrame)
{
 // mySetIdentity(RectMVMatrix); // comment this line to retain the animated position.
  mytranslate(RectMVMatrix, translate-delta, X_AXIS); // to translate the mv matrix in x axis by translate-delta value
  myscale(RectMVMatrix, scale-delta); // to scale the mv matrix  by scale-delta value
  ... // opengl calls
  glDrawArrays(...);
  eglswapbuffers(...);
}

```

The above code will work fine for first 100 frames. in order to retain the animated rectangle during the frames 101 to 200, i removed the "mySetIdentity(RectMVMatrix);" in the above drawFrame().

Now on entering the drawFrame() for the 2nd frame, the RectMVMatrix will have the animated value of first frame

```
e.g. RectMVMatrix[4][4] = { 1.01, 0, 0, 2,
                            0,    1, 0, 0,
                            0,    0, 1, 0,
                            0,    0, 0, 1
                           };// 2 pixels translation and 1.01 units scaling after first frame

```

This RectMVMatrix is used for mytranslate() in 2nd frame. The translate function will affect the value of "RectMVMatrix\[0\]\[0\]". Thus translation affects the scaling values also.

Eventually output is getting wrong.

How to retain the animated position without affecting the current ModelView matrix?

---

I got the solution... Thanks to Sergio.

I created separate matrices for translation and scaling. e.g.CurrentTranslateMatrix\[4\]\[4\], CurrentScaleMatrix\[4\]\[4\].

Then for every frame,

I reset 'CurrentTranslateMatrix' to identity and call mytranslate( CurrentTranslateMatrix, translate-delta, X\_AXIS) function.

I reset 'CurrentScaleMatrix' to identity and call myscale(CurrentScaleMatrix, scale-delta) function.

Then, I multiplied these 'CurrentTranslateMatrix' and 'CurrentScaleMatrix' to get the final 'RectMVMatrix' Matrix for the frame.

Pseudo Code:

```
    float RectMVMatrix[4][4] = {0};
    float CurrentTranslateMatrix[4][4] = {0};
    float CurrentScaleMatrix[4][4] = {0};
    int iTotalFrames = 300;
    int iAnimationFrames = 100;

    int iTranslate_X = 200.0f; // in pixels
    float fScale_X = 2.0f;
    float scaleDelta;
    float translateDelta_X;
    void DrawRect(int iTotalFrames)
    {
        mySetIdentity(RectMVMatrix);
        for (int i = 0; i< iTotalFrames; i++)
        {
            DrawFrame(int iCurrentFrame);
        }
    }
    void getInterpolatedValue(int iStartFrame, int iEndFrame, int iTotalFrame, int iCurrentFrame, float *scaleDelta, float *translateDelta_X)
    {
        float fDelta = float ( (iCurrentFrame - iStartFrame) / (iEndFrame - iStartFrame))

        float fStartX = 0.0f;
        float fEndX = ConvertPixelsToOpenGLUnit(iTranslate_X);
        *translateDelta_X = fStartX + fDelta * (fEndX - fStartX);

        float fStartScaleX = 1.0f;
        float fEndScaleX   = fScale_X;
        *scaleDelta  = fStartScaleX + fDelta * (fEndScaleX - fStartScaleX);
    }

    void DrawFrame(int iCurrentFrame)
    {
        getInterpolatedValue(0, iAnimationFrames, iTotalFrames, iCurrentFrame, &scaleDelta, &translateDelta_X)
        mySetIdentity(CurrentTranslateMatrix);
        myTranslate(RectMVMatrix, translateDelta_X, X_AXIS); // to translate the mv matrix in x axis by translate-delta value
        mySetIdentity(CurrentScaleMatrix);
        myScale(RectMVMatrix, scaleDelta); // to scale the mv matrix  by scale-delta value
        myMultiplyMatrix(RectMVMatrix, CurrentTranslateMatrix, CurrentScaleMatrix);// RectMVMatrix = CurrentTranslateMatrix*CurrentScaleMatrix;
        ... // opengl calls
        glDrawArrays(...);
        eglswapbuffers(...);
    }

```

---

I maintained this "RectMVMatrix" value, if there is no animation for the current frame (e.g. 101th frame onwards).

# Answer
> 1 votes
First, keep in mind that the order in which you apply the transformations is important. This is because matrix multiplication is not transitive: `A*B != B*A`

I'm guessing your intent is to scale the rectangle first, then translate it to the right position. If you do it the other way around the distance translated will be scaled as well, which is probably not what you want.

So let's say you have your transformation (X), as a multiplication of a translation (T) and a scale (S): `X = T*S`

If you combine them in the same way, after frame two you'll have: `X = (T1*S1)*(T2*S2)`, which is why you're having problems.

What you need to do is group them like this: `X = T2*(T1*S1)*S2` In this way, the translations accumulate on one side, the scales accumulate on the other side and the end result is what you'd expect.

---
Tags: animation, opengl-es, matrix
---


title: demographics of paying mobile gamer

text:
# Question
Title: demographics of paying mobile gamer
I was googling for this now for a while but didn't find any relevant data.

Does someone know any statistics of the demographics of mobile gamers that actually spend money on their games? It's clear that this data may vary over different genres but any kind of analysis in this direction would be interesting for me.

# Answer
If you're talking about payers for mobile games, you're talking about whales, who represent the majority of the revenue.

Though it varies from game to game, a report from analytics firm Swrve found that only 1.5% of players spent money on mobile games.

Within that 1.5% the revenue follows a power law, with most of the money coming from big spenders - with the aforementioned report stating that 50% of the revenue came from the top 10% of those who spent any money.

Some effort has been put to identify what makes whales tick. Here are some links:
> 1 votes

# Answer
I found this with little effort and this was the second google entry. I only know that people with iOS devices and/or Macs are more likely to spend money to purchase your game, to do in-app purchases, or to click on any publicity included in your app i.e.(don't bother with android or Windows Phone) although PCs are popular gaming machines you asked for mobile games.
> 0 votes

---
Tags: mobile, monetization, business, demographics
---


title: Approaches to timed puzzle elements

text:
# Question
Title: Approaches to timed puzzle elements
I'm working on a side scrolling game that has a number of timed puzzle elements. As a simple example: I have a number of moving platforms that have been setup to transition in a pattern. Ideally I'd like to ensure that as the player first approaches them, they are in an *ideal state* -- whereby the player can witness the full transition and more experienced players (i.e: speedrunners) can complete the puzzle immediately without having to wait for the current transition to complete.

The issue here, in a nutshell, is that because these platforms begin transitioning at the start of the level, it's impossible to correctly calculate when the player is likely to stumble upon them.

I've done a fair bit of Googling but haven't managed to turn up any decent resources with regards to solving a problem like this. The obvious solution is to only begin updating the objects when the player (or more likely: the camera) first encounters them. But this becomes difficult when you consider more complicated situations.

It seems like potentially the easiest way of handling this is to have an invisible trigger volume that will tell any puzzle elements located inside of it that the player has 'arrived' upon first colliding with the player. But this would mean I'd have to logically group puzzle elements, which could become fairly messy in a hurry. Take, for instance, a puzzle that appears to the right of the screen. It may take the player a number of seconds to reach it. It would look strange if the elements involved were to remain stationary. But by the time the player arrives, it's likely things will be 'out of sync'.

I wanted to post here in the hopes that others know of, or have implemented, a decent solution to this problem?

# Answer
> 1 votes
Have you considered using a messaging system like the observer pattern, or the publish/subscribe pattern. You could create a trigger object, register any platform that needs to be notified with the trigger object. Then when the trigger goes off it informs all those that are listening that the event has happened. The nice thing is you can have as many or as few event listeners that you need and they do not have to be aware of each other. Just place the trigger somewhere before the player gets to the platforms. If the trigger is a non-drawing game object, the player will be completely unaware of it.

```
public class TriggerableGameObject extends GameObject {
    public void start() {
        // Override this in derived class.
        // Start action
    }
}

public class GameObjectTrigger extends GameObject{
    private ArrayList<TriggerableGameObject> gameObjectList;

    public void register(TriggerableGameObject gameObject) {
        gameObjectList.add(gameObject);
    }

    public void unregister(TriggerableGameObject gameObject) {
        gameObjectList.remove(gameObject);
    }

    public void notify() {
        for (TriggerableGameObject gameObject : gameObjectList) {
            gameObject.start();
        }
    }

    public void onDraw() {
        // leave blank if you do not want the trigger to be visable
    }
}

```

Obviously I am making some assumptions about your class hierarchy, but I think you get the idea. This behavior would work well for what you are asking about, as well as animatiable floor switches and pressure plates. Also, implementing something like this would allow you to make a trigger control more than just a platform, for example: dropping block, swinging chains, flooding rooms, etc. Anything you derive from `TriggerableGameObect` can be registered with a `GameObjectTrigger`, (or more than one if you like).

# Answer
> 1 votes
If the concern is for speed running, you can measure how far the player is from the puzzle "entrance" by the time they first see a part of the puzzle, calculate how long it will take to reach the puzzle entrance at top speed, and rewind the puzzle state by that many seconds.

Most games just make periodic events happen often enough that you're unlikely to miss one by too long. If you're making a game for speedrunners, you should allow for some creativity when navigating sections anyway.

# Answer
> 0 votes
In the past I did something exactly like what you said, Group the Puzzles elements, and trigger then on player distance, this ensures that they are in the same state no matter what time it took to reach there, after that its the player responsibility to move fast toward it or to wait, this will make speed runners have pretty much the same puzzle once they reach there, only varying based on their performance to reach the goal.

Clarifying the distance concept, the easier way ( I am assuming its 2D) its just to check the max BoundingRect of all the puzzle elements, if the player ViewArea intersects that of the puzzle + some offset, start the puzzle mechanics. This works quite well to tell the truth.

The only draw back is the time needed to setup the puzzles.

---
Tags: puzzle, timing
---


# Question
Title: Single texture or one texture per light for shadow mapping
The basic implementations of shadow mapping that I have seen create a depth texture for each light source affecting the scene. I'm just curious as to why this might be done rather than using and reusing a single texture for all of the lights in the scene so as to save on memory.

To clarify, is there any benefit in the following:

```
for light in lights
    render scene depth to light.shadowTexture // One texture object per light
end

for light in lights
    render scene with light (blended)
end

```

as opposed to:

```
new Texture shadowMap // One texture object, written to by all lights

for light in lights
    render scene depth to shadowMap
    render scene with light (blended)
end

```

# Answer
In addition to bogglez answer (you don't need to re-render shadow maps which haven't changed between frames), there is also the possibility to render several lights at once if each light has its own shadow map. This is more of an issue with a forward (i.e. non-deferred) renderer where you want to avoid churning through all the geometry in your scene for each light.

You can also group lights together according to which geometry objects they intersect and re-use a small pool of shadow maps if you can't afford to have a shadow map per light.
> 2 votes

# Answer
In the first solution you can keep the shadow map if nothing changed, in the second solution you always need to re-render the shadow map. That makes the first solution better for scenes which are somwhat static.
> 2 votes

---
Tags: graphics, shadows, shadow-mapping
---


# Question
Title: How can I name and organize resources at design time?
I'm having a very hard time trying to figure out a good way to add new resources to my game project in a way that's convenient for designers.

To try and better understand the problem, I'm trying to create a very simple game. It's in the style of an old text adventure. The user begins in a room, and at the start of each turn an image of the room is displayed and some text describing the room is printed. Then several options are shown (in a multiple choice format). The user picks one and option and the result of the action is printed to the screen. Then the turn ends and the next turn begins (the new image and description are shown, more options are printed, etc).

This game will require several resources: \- String tables (to hold the text) \- Images (Shown in each room) \- Places (links to the image and description, as well as the list of options) \- New Game Scenerio (used to initialize game. Just tells the user where the starting room is)

I would like to create an editor where designers can just start it up and then start adding and editing rooms.

The straight forward approach would be to create a simple, stand alone editor that can load and save independent Place files. It would use relative file paths to locate the linked images and string tables. These Place file format would be XML which would later be compiled to a binary form when the final resource archive containing all resources is compiled.

The trouble with using paths, though, is that if you rename and move files (as you likely will as the project get larger), the paths that point to it will break (at well as any relative paths it points to itself).

Relative paths can also be a problem if you need to refer to resources that are in a completely different branch off the root. For example, let's say I have the following resources in my project:

/item/MagicWand.xml /place/grassyPlain/castle/DarkTower.xml

If I want to place a MagicWand in my DarkTower, I'd have to use a relative path that looks something like "../../../item/MagicWand.xml". That's pretty cumbersome. It would be nicer to use something like "item.MagicWand".

Also, since these resources are going to be compiled, if I need to refer to them from my scripts I will need something to call them. If my user is in the DarkTower and selects the option "go to the griffon pen", I'm like to be able to do this with code similar to

```
getUser().setLocation("place.grassyPlain.castle.GriffonPen");

```

All this suggests importing my resources into some sort of super editor project that knows how to handle all resources and provides names for them (and even provide interactive editors for some of them). While this would simplify the naming problem, but would be a lot of work - especially if more than one person need to design resources at the same time. (for multiple users, I'd need a database-like locking mechanism to make sure multiple people weren't renaming things or working on the same file at the same time). The whole thing would have a look and feel that calls to mind the Flash editor.

My thinking keeps leaning toward this super-duper editor solution, since I've been exposed to tools like this before. However, this seems like a lot of work, especially for so simple a project. I can't help but think that I'm over thinking this. I would like to have a system for managing my game's resource that is simple yet, flexible and which integrates well with my code/scripts.

Does anyone have any thought on what makes a good resource managment/naming system?

# Answer
> 3 votes
I believe creating this super editor will distract you from your true goal, to create a game. From the sound of it the editor will be more difficult to create than the actual game.
Furthermore I don't believe you need such a tool for your project.

An easy way to approach this is by breaking all different resources the game needs into categories and create a different directory for each resource.
Then create a simple system to locate each resource based on its category.

```
resourceManager.Root = "/Reources";
resourceManager.Items = "/Items";
resourceManager.Places = "/Places";

resourceManager.GetItem("wand"); //located within Reources/Items
resourceManager.GetPlace("castle/DarkTower"); //located within Reources/Places/castle

```

This `resourceManager` can be initialized with the paths to each category and even have a specialized way to load up its resource. For instance, when you load a place it will parse an xml file and the load up all items this place may have.

If for any reason you need to change the path to any category you will need to change only a single path.

# Answer
> 1 votes
Building tools to aid in the development and management of content is an *excellent* idea. However, it costs quite a bit of time and energy, so you need to weigh those costs carefully against the needs of your project (and potential future projects which would use the same technology platform) and decide if it's going to be worth the investment or not.

Tools allow you to create abstractions that allow your game assets to be interpreted by two (often quite different) world views: that of the programmer consuming the resources in the game engine, and that of the designers producing those assets.

### Renaming

For example, in an ideal world, you'd refer internally (that is, in code) to resources by a fixed identifier that will never change regardless of what you do to the resource (for example, a UUID). When assets are referred to by name, renaming or moving an assets correctly involves finding all existing references to that asset and update them. This can be quite slow, and cause quite a few problems (especially in larger teams). But using UUIDs sidesteps that problem entirely. You can move and rename assets all day long, and since the relationships between them are established via identifiers that never change, there's no problem.

Of course, UUIDs are ugly and cumbersome to remember and talk about. Thus, you build content management tools that expose primarily the names of assets, allowing designers to reason about assets by name, but which internally maintain the links between assets by GUID.

You can build anything along the sliding scale of that abstraction: you can have no tools, have designers hand-edit XML files and manually deal with UUIDs; you can build a complete toolchain for them that deals with everything; or you can do something in between.

For example, you can refer to everything by name, eschew UUIDs, and provide a much simpler tool that does assists in renaming or moving assets when needed (handling all the fixups, et cetera). This involves much less effort and investment and solves a good percentage of the serious problems involved with reference-by-name systems.

### Collaboration

There are similarly two simple solutions for dealing with the collaboration problem you mentioned: either use exclusive editing... "locking," which you mentioned, which you can define by policy -- if somebody has a file checked out, don't edit it -- or enforce via tools; in both cases the practicality of this approach is gated by whether or not your source control system exposes that notion. Distributed systems like Git do not, but systems like Perforce do. If your SCM doesn't do it you'd have to manually implement it, and that's a fair bit of investment alone right there.

You can also design the pipeline to support merging. You can either choose a text-based format that is suitable for manually merging (XML is possible to hand-merge, but it's not the *best* option, and it's easy to make mistakes), or you can build a system where your content data is actually transactional when stored (instead of "this value is five" you store "this value is changed to five") and built a merge system yourself using that transactional data. We did this at ArenaNet for Guild Wars 2, and it is the crux of how the game can ship such extensive content updates every two weeks.

This again is a choice along a sliding scale: the system built at ArenaNet is *powerful* and saves tons of time. But it also took a lot of time to implement (two full-time engineers over a few months). You will need to make hard choices about what problems you really need to fix and what problems you can live with based on the needs of your project and your available resources; it's quite possible your team is small enough you can solve the collaboration problem with zero engineering effort by just having everybody talk to eachother and coordinate work.

### Tips

If you're going to go and invest in building a full-featured editor for your content, I'd strongly advise you to consider an approach where you don't hand-build every editor screen. It's a massive time sink; instead, consider an approach where you can *generate* the UI based on the properties of the object you are editing (much like the Windows Forms `PropertyGrid` does). This approach, combined with a simple extensibility system for plugging in editors for the very few types that might need special editor views, is *much* easier to develop and maintain. It's the basic premise we used at ArenaNet for our tools platform, and it saved man-years of engineering time.

You should also focus on doing the smallest, fastest thing that could work first. Create a minimum viable product and iterate on that towards a larger future goal: don't stop all other development for two months sinking time into some kind of crazy super editor. Always keep in mind what you *actually* have to accomplish for your project and what your *actual* available resources are. Make sure you are chasing after features and tools you need and not those that sound cool or sound useful.

---
Tags: assets, asset-management, asset-workflow
---


# Question
Title: Trajectory Projectile with Collision Detection
Right now I am trying to create projectile for cannon in which I want to detect collision also.

At present I have simple working projectile after using two references

Unity – How to display projectile trajectory path in Unity 3D?

Path/Trajectory prediction – What path will the object take

But in this I also want to represent bounce in projectile path. I searched everywhere but didn't find any useful content.

Please provide some guidance here.

# Answer
> 0 votes
The simplest possible solution would be to maintain the horizontal velocity, and flip the sign of the vertical velocity, after multiplying it by an elasticity factor.

```
vec2 velocity;
vec2 position;

position += velocity * dt;
if (collision)
{
   position = adjust_position(); // to not collide anymore
   velocity.y = -velocity.y * elasticity;
}

```

If you're only concerned with a 2D projectile, on a flat plane, this should work.

The elasticity factor will control how far the projectile will bounce. If you make it 1, it will bounce as high as the initial path. Typical values are lower than 1, which means the projectile will lose energy with each bounce.

---
Tags: unity, collision-detection, physics, projectile-physics, trajectory
---


# Question
Title: How to calculate move while avoiding deep copy
Suppose in a turn-based game, I have an object holding the current status of the game (like players, board information, positions of pawns, things like that). Now I want my AI to calculate the best move (or at least a good move).

My first try was to determine all allowed actions and generate a new game object for each action the player or computer could do. Then I would repeat the process for all resulting game objects. This would yield a form of tree with all the future possibilities, from which the AI simply could select the optimum.

But it turns out that this approach is cruelly slow, mostly to me deep copying the game object thousands of times and holding thousands of copies of the game object in the memory.

I am now searching for a better approach to calculate a good move. Are there technics for this type of problem. I am aware that this probably depends on the kind of choices the player or AI has to make in the game. But I am more interested in general technics used to tackle this kind of problem.

Any help is appreciated. If this question is more appropriate for somewhere else (for example StackOverflow), please move it there. Thanks!

# Answer
When you develop your game object-oriented, this might be a good application for the flyweight pattern.

In this context, a flyweight would be an object which acts as a copy of the gamestate, but actually references the original gamestate it was created from while also having one or more modifications to it.

To create a flyweight, you need

1. a reference to either a gamestate or another flyweight which is the base of this flyweight (the "parent")
2. the change or changes you want to make to that parent

When a value is read from a flyweight, it first checks if the value which is read is the or one of the changes. When that's the case, it returns the changed value. When this isn't the case, it delegates the read to the parent.

The advantage of this pattern is that the creation of a new copy is very cheap. The complexity in both memory and runtime only depends on the size of the changes. However, access is slightly less efficient and will get less and less efficient the more flyweights you nest into each other to represent multiple changes which build onto each other. However, in a typical game AI these reference chains shouldn't be very deep.
> 4 votes

# Answer
You may want to try to optimize it, copying data should be relatively lightweight.

Some things you can do:

* Allocate enough memory for the copy beforehand, instead of allocating for every single object. Each allocation call is expensive and you should be able to reduce it to a single one. This is probably the biggest bottle neck in your case.
* Reduce the size of the single objects.
    + Split the definition of objects (e.g. stuff that doesn't change after the object was created) and the object itself, this should make it possible to reduce the size of the single object by a lot.
* Mem-copy large blocks of data, rather than calling copy constructors for each one. Much easier to run in parallel and you shouldn't run into any cache misses that way.
> 2 votes

# Answer
While there have been several answers focusing on the question you asked I think you're barking up the wrong tree here.

If the cost of copying is bogging you down you have a lot of game objects and thus the tree you are describing will grow **very** fast. I doubt you are going to get enough depth to the tree to be of much value here.

Exhaustive trees are only an option in games where the choices are simple. After all, even chess has a tree that is beyond computation.
> 2 votes

# Answer
Instead of replicating state in each new node you could just keep state differences between a node and its parent in the tree. By traversing the tree from the root node to a node at depth n you can calculate the new state at n.
> 1 votes

# Answer
It would be useful to know which language you're using, as memory management changes a lot. Some general ideas:

* When searching, you don't have to generate the whole search space up front. If you're using something like alpha-beta prune or any heuristic so you early out branches of the tree, then you can copy the nodes only as you need them, and save a lot of sections that will never get explored.
* An alternative to copying is to keep a single copy of the objects, apply the action to see the results, then undo the action, before evaluating the next node. Rinse and repeat. This is much cheaper memory-wise, but requires you to be able to undo all the actions to do the search.
* In general, I'd recommend having a simplified representation of the objects, for AI reasoning purposes. This is different from the Flyweight pattern suggested by Philipp. You may need to recreate the transformations that the actions apply to the objects and distill it to the minimum (so for instance, you don't update animation states if the AI doesn't care about it).
* Finally, standard optimization advice applies. Profile, see what's expensive to copy, then make it cheap :)
> 1 votes

---
Tags: ai, turn-based
---


# Question
Title: Can I take a finished game based on a licence to the holding company?
Ok so I went through 11 pages on here and have done a decent amount of Google searching, but found nothing specific to my question. I'm working on a game based on a movie. For the purpose of this I'm going to use a different movie as my example. Let’s say I'm making a game based on "Driving Miss Daisy" (because why not?).

Now I've seen plenty of questions about taking an "idea" to a company (both game and rights holders) and trying to get funding but I have no reputation and this is a side project at this point so that's probably not a good idea. But let’s say I work on my "Driving Miss Daisy" game for a year or so and at some point call it "finished". It has good art, co-op, a campaign, and achievements (because, why not?) all made 100% by me and me alone. Does anyone know the process or the likelihood of me going to Warner Bros. and their games division with some kind of deal splitting profits if they allow the release or help with it etc etc.

Even if I hear "There’s no way, ‘Driving Miss Daisy: the Game’, while awesome, will never see the light of day", I'll probably keep working. I just wanted an idea of what kind of outcome could come from this and this is a different situation than I've generally seen asked. Like I said, most are about getting money for the development itself or trying to re-release old games that have been abandoned.

Thank you to anyone who might have information about this.

# Answer
> 15 votes
The likelihood of this approach producing the results you want is effectively zero.

First, if you have built your prototype using the actual IP, then you have almost certainly committed (in most jurisdictions) copyright infringement or some similar IP law violation -- it doesn't matter that you have kept the project private. It's unlikely that the IP holder will appreciate that, and will likely simply issue a cease & desist (many forms of IP law mandate that the IP holder take the requisite action to protect their IP or they lose the right to do so; so it's not necessarily out of malice).

But that assumes they even look at it. Most game companies will refuse to look at / open unsolicited game submissions in order to protect themselves from potential litigation in the future. Some variant of this holds for other media companies. It's very hard to find the right contacts to get a proposal heard; this is generally not how most games get made. Game studios have their own talent and massive pool of ideas, and non-game companies tend to be the ones who want to do the approaching, and have their own list of people they like to work with. "Knowing somebody" really helps.

That isn't to say that it's impossible -- there are cases where this has worked. But it's extremely unlikely and a huge risk for you in terms of your opportunity cost. If they see it and say "no" they will almost certainly do so in a way that legally required you to abandon your work.

My advice to you would be to build the game you want without invoking somebody else's IP at all. Then establish contacts with business representatives of the company holding the IP and pitch the project. You still have a very slim chance of getting anywhere, unless the company is small and/or you are already an established developer with a track record, but at least yo won't have anything they can take away from you, and if they never even want to talk to you you can still apply your own IP to the game and ship it.

# Answer
> 13 votes
People I have worked with have done this before.

First time: programmer who worked for me made a PC version of a board game (I made some art for it just because it was a fun little project). This was 25 years ago. He approached the rights holders, a large toy company. They had no idea what to do with the game, and after a few months of considering it they told us to drop it. A few years later they made PC games from several of their board game properties and gave them away; their games were about the same quality as ours, and they paid someone else to make them.

Second time: 18 years ago, several of my students make a prototype of a game to be given away for free with "Happy Meals". They tried for a year to contact McDonalds and make a presentation. They finally determined that to get a meeting with someone who could make a decision was going to cost 60-100K in agent fees, and the project died.

Third time: big-budget movie game, company negotiated the rights with the mega-studio, sinks 4 million into production, then after a few month's work a lawyer shows up and explains that a certain crucial IP belongs not to the studio, but to his client, who designed the IP for the studio but only gave them the movie rights; he retained all other media rights. Designer wants money and what turns into totally unworkable artistic control; project is eventually cancelled, despite the fact that the game was looking great up until then.

My advice: don't sink much time into a project that you don't have iron-clad rights to. Either make a simple/small prototype and pitch it, or make the game without the IP, and pitch it somewhere along the way (but be prepared to leave the IP out and continue).

# Answer
> 3 votes
To add to Josh Petrie's answer when you want to use someone's copyright you have to negotiate with them, if you already have your game you can't really go back and will have to take whatever deal they offer you and they know this. This makes first making a game and then getting copyright a great way to lose any potential income/be forced to ask money for it to pay for the rights to the game.

# Answer
> 2 votes
I have spoke to the "right people" at a couple of studios that own IP for large/successful IP typically in the TV/film space, and asked them if they want to use their IP in one of our super, cool, amazing, etc. projects - a great opportunity for them I thought. Their response has been go off and make the game with our own IP, when it has been a proven success they will consider putting their IP in it.

Essentially a better business model for them is to pick a game with a proven financially successful track record and have a branded version of that made, it is a much easier sale internally (often the people making the calls are more interested in facts and figures and bottom lines than qualities that are hard to define and maybe personal). While I would like them to say yes to me, if I was in their shoes I would do the same thing unless the studio with the proposal had a very good track record of making profitable games.

That said, I wish you the best of luck, my experience is limited to responses from a couple of studios, if you excite the right person at the right company maybe you will find success.

---
Tags: legal
---


# Question
Title: Best practice for organizing the physics of objects?
Apologies because this is a long post and I am inexperienced. I would really appreciate the input from some experienced developers.

These are my two goals for this project:

1. **To learn the best method of managing the game loop** and flow of the program so that it is easily understandable, clean, and reusable.
2. **To learn about how to efficiently and *cleanly* handle the physics calculations of a game**. I would like to learn the method that is implementable on a scale that can accommodate a lot of collisions.

The project will be written in using **Javascript/HTML 5**.

The way I was thinking about it is to include attach implement an physics object constructor that attaches a physics object to each class object that will have physics done to it.

For example:

```
var playerBullets = [];
playerBullets.push(Bullets()); //Bullets() is the constructor

//inside the Bullets() constructor I would have the following:
this.physics = Physics();  //where Physics() is the constructor for a physics obj

```

The physics object would be set up like the following:

```
{
  x: 0,
  y: 0,
  xVelocity: 0,
  yVelocity: 0,
  xAccel: 0,
  yAccel: 0,
  mass: 0,
  restitution: 0,
  angularVelocity: 0,
  linearDampening: 0,
}

```

Then from the gameLoop:

```
Function gameLoop() {
  ...
  update();
  draw();
}

Function update() {
  ...
  //code here to iterate through objects to update them individually
  handleCollisions();
  handlePhysics();
 }

Function handleCollisions() {
   ...
   //detect collisions between objects and mark which ones have collided with each other
}

Function handlePhysics() {
   ...
   //code to iterate through objects and update the velocities
   handleCollisions();
}

```

**Questions**

1. What might be some problems I would run into by doing it this way?
2. Should I include any methods in the physics object or should I handle all of my physics operations in a special function inside the gameloop?
3. Is it better to handle the physics together, or handle the physics of each object separately in its own update function?
4. What is the best practice way to handle physics in a game?

**EDIT** I learn better by seeing examples so it would be very helpful, and I'd really appreciate it, if I could see some accompanying pseudo-code.

# Answer
Typically a physics engine will follow these steps:

* Broad-phase collision detection. Typically using bounding volumes, this reduces the set of all objects to a small subset of potentially colliding objects. Some data structures to handle broad-phase are AABB trees, KD-trees, Octrees, etc.
* Narrow-phase collision detection. From the subset of potential collision, test if a collision actually occurred by using the actual physics body. This typically involves calculating things like point of contact and normals.
* Solver. Resolve collisions by pushing objects apart and enforcing constraints.

Because of the global nature of these calculations, it's typical to have physics objects centralized. You'll have them classified in a hierarchical structure, organized based on their bounding volumes (which is also handy for spatial queries, like finding objects near me). You might also want to separate static and dynamic objects, for efficiency (as only the latter can move, so the former don't need to be updated).

It's ok to put the physics object inside the normal game object as long as you also register it with the physics system. When you find a collision you'll want to notify the game object back; this is typically done by embedding a piece of data in the physics object that points back to the game object, so they both know about each other. You can do that in the Bullet constructor, in your example.

You can add methods to the physics objects like you would do with any other object in OOP. It may make sense for internal operations, related to the physics body, physics material, etc.

I'm curious why you didn't show a time delta in your update functions. Was this omitted for brevity or are you assuming a lockstep framerate? I find having a variable timestep gives you more flexibility but it can make the physics engine unstable (due to integration issues) if you don't run it at a high enough framerate. I've seen engines run several physics updates per frame in these cases, while still running the logic and rendering only once.

EDIT: If writing a broad phase is too much, I'd probably start with a simple array that contains the physics objects, and test everything against everything (which will become expensive once you have many).

```
PhysicsManager.physicsObjects = [];

// In Bullet constructor
this.physics = Physics();
PhysicsManager.physicsObjects.push(this.physics);

// Then in physics update
for (var i=0; i<physicsObjects.length; ++i)
    for (var j=0; j<physicsObjects.length; ++j)
         if (i != j && collides(physicsObjects[i], physicsObjects[j]))
               // Handle collision

```
> 1 votes

---
Tags: algorithm, physics, performance, game-loop
---