# Question
Title: What are my options other than game engines?
I'm a programmer. I've experience in Java, python, and c++. I see that some big games are built using game engines (Crysis uses Cryengine). However, other don't (Bayonetta for example). what's their approach ? Do they start coding from scratch using OpenGL or Directx ? is this approach feasible considering time, cost, porting to many platforms ?

I want to know what's the options before I start

# Answer
> 2 votes
The different options out there are essentially as follows:

1. Engine. An engine provides you with a high-level API through scripting and gives you many visual and non-visual tools to work with it. With an engine, you probably don't touch it's code, and the only thing you provide are resources which the engine loads at start of execution and that's it. Example: Kerbal Space Program, Unity Engine.
2. Scratch. In this case you write the entire program from scratch and optionally integrate some libraries. Pretty straightforward. Example: Super Hexagon.
3. Framework. A framework provides a common interface for all of it's different components. To use it, you incorporate it into a program written from scratch. Most times, you will find that you go into the frameworks source code and modify it to suit your needs. Example: XNA Framework (now obsolete :( ).

# Answer
> 2 votes
**The real question is what are you goals for this project?**

If you have a specific game in mind and just want to 'make it happen', then using something like Unity or Unreal is the sane approach. Creating an entire engine for anything but the simplest games is a huge endeavor.

If, on the other hand, you are trying to gain skills and/or create a demo to land a job in the game industry, then writing your own engine is more likely to teach you more and be more impressive. You won't get as far, but you can demo technology without demoing a whole game.

Do you have experience coding with OpenGL or DirectX? How about audio APIs like OpenAL, XAudio, or middleware like FMOD? If not, you have plenty to learn before you can really write your own engine.

---
Tags: opengl, directx
---


# Question
Title: Is there a way to exclude original sprites in spritepacker that's in asset bundle?
I use spritepacker with assetbundle. It's working great. Its memory assumption is about just 8 MB. However, when I looked at the disk space that asset took on android phone, it took about 25MB. Which is 4 times from 8 MB. If I sum up all original sprites that have been used to create the atlas in spritepacker, they will be about 25MB as they are. Is there a way to exclude original sprites out of the bundle? It waste too much space in the device. I think only output atlas that generate from sprite would be enough to pack within the bundle.

I'm sure of it. I tested with 18 sprites and use the packer to generate 1024x2048 atlas. If I choose 2 sprites to make asset bundle, it used 5.76 MB disk space. If I choose 3 sprites to make asset bundle, it used 6.62MB. Its different is about 0.9MB which is the size of each sprite.

# Answer
> 1 votes
You can use some sort of a hack:

* Use AssetDatabase.LoadAllAssetsAtPath to load your resources
* For sprites it will return an array with Texture2D and Sprite
* Add only the Sprite to the list of resources you want to bundle
* Do not use the CompleteAssets flag while building bundle with sprites

In this case only the generated atlas will be added to the bundle along with the sprites information required

---
Tags: unity
---


title: Sprites and Box2d

text:
# Question
Title: Sprites and Box2d
I'm starting to see how box2d works now, except I dont know how to scale the screen to diffrent screen sizes and how i can convert Sprite sizes to box2d units. I know box2d uses meters and such, but even with a conversion unit i don't understand how i can link a body to a sprite and set the sprite size to the body size.

Also, I read about viewports, but every tutorial i see does it diffrently and i don't know how to do it anymore

So how do i render my game so that it looks the same on every android screen, and how to i display sprite on box2d bodies? (how exactly does the unit conversion work?)

Thanks!

# Answer
> 1 votes
The conversion from a unit to another is a matter of a simple multiplication. You can implement a `ConvertUnits` static class with functions like `ConvertToGameUnits()`, and `ConvertToBox2DUnits()` to make it easier.

I haven't used libgdx or Box2D, but i have used Farseer Physics engine which is basically identical with box2D but made for C#. With that being said, bodies simply help you with physics simulation, you don't link bodies with sprites. If you wanted to have a rectangle in your game, `ConvertToBox2DUnits()` function to set the position/width/height of your rectangle, and then you would have to use the `body.Position` property and your `ConvertToGameUnits()` method, to draw your sprite on the current rectangle's position.

As for making your game look the same on every screen isn't exactly possible, since not every screen has the same aspect ratio with the game you are making. Lets say you want to draw a 720x1280(16:9) resolution texture on a 480x640(4:3) phone (horizontally). You would draw 50% less pixels (which is a simple scale down to 50%), and also you would have to either place `black bars` on the top and bottom side of you phone or stretch the image to fit the screen.

I think you should first check some example game written in libgdx and/or box2D and start from there.

---
Tags: libgdx, sprites, rendering, camera
---


title: Scaling sprites in XNA 4.0/Monogame

text:
# Question
Title: Scaling sprites in XNA 4.0/Monogame
So I looked up a tutorial on how to scale sprites in XNA and I think I have it all figured out.

The only problem is that I want to use a `spriteBatch.Begin()` method overload without changing anything except for the Matrix.

The only `spriteBatch.Begin()` method that has a Matrix as a parameter is this one:

```
public void Begin (
         SpriteSortMode sortMode,
         BlendState blendState,
         SamplerState samplerState,
         DepthStencilState depthStencilState,
         RasterizerState rasterizerState,
         Effect effect,
         Matrix transformMatrix
)

```

I don't really want to mess around with any of the parameters except to pass in my matrix. How would I do that?

# Answer
> 4 votes
If you simply want to scale a sprite you can do

```
spriteBatch.Begin();
spriteBatch.Draw(texture, position, null, Color.White, 0f,
Vector2.Zero, 0.5f, SpriteEffects.None, 0f);
spriteBatch.End();

```

or

```
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, null,
Matrix.CreateScale(0.5f));
spriteBatch.Draw(texture, position, Color.White);
spriteBatch.End();

```

Where 0.5f means 50% of the normal size of your texture. You could also use a Vector2(x,y) instead of a float, where the x would be the resize on width, and y the resize on y.

# Answer
> 2 votes
If you are looking to use a Matrix as a camera and to scale and rotate the scene then spriteBatch.Begin() is indeed what you are looking for. Now I know it looks like a lot of parameters but you can actually assign most of them null values. For example:

```
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, YourMatrix);

```

You can find out what the SpriteSortModes do here, but Deferred is usually what you'll want. It's really worth it to familiarize yourself with the other parameters though and you can find them on the MSDN docs as well.

---
Tags: xna-4.0, monogame, scale
---


# Question
Title: Why doesn't my game start in landscape mode?
I want my game to run on all Android devices in `LANDSCAPE_FIXED` mode, but this mode works only for some screen resolutions. `PORTRAIT_FIXED` works well for all devices. I'm testing this on and emulator.

How can I achieve this? Here's my camera/engine initialization code:

```
public EngineOptions onCreateEngineOptions() {
    cw=480;
    ch=320;
    camera = new Camera(0, 0, cw, ch);
    EngineOptions engineOptions = new EngineOptions(
        true,
        ScreenOrientation.LANDSCAPE_FIXED,
        new RatioResolutionPolicy(cw, ch),
        this.camera
    );
    engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
    return engineOptions;
}

```

# Answer
Try using the `android:screenOrientation="landscape"` option in the manifest file's activity tag.
> 1 votes

---
Tags: camera, andengine, aspect-ratio
---


# Question
Title: AI to help player by suggesting upgrades
Suppose I'm creating a racing game.. I would like to implement an awareness system AI, that will suggest to the player that he can buy that booster or some other upgrade, .. etc. How should I start implementing that? A FSM ? A decision tree ?

Suppose that I have variables like, how many crashes, how much is the damage, how many gates I have passed, .. etc how would I use those variables then to say for example you need to buy that stuff?

# Answer
I would use some sort of points system assigned during the race.

So each time a player crashes in the corner - add a point to "steering upgrade suggestion", each time he looses a race add a point to "engine upgrade", brakes for prolonged periods and misses an apex - "better brakes", gets overcome by an opponent in a straight line - "booster" and "engine" upgrades. You get the picture.

Detecting the right events can be tricky. You might need to add some cooldown period between adding more points or diminishing returns to the same item, so that e.g. multiple crashes during the same race wont make the steering upgrade score go sky-high. For example when player crashes into the corner you need to foresee and account for player could be hitting the walls of the corner a dozen of times before coming to a stop - that should be treated as a "one cornering fail", not a dozen. Said that, counters probably should be `float` values.

Another tricky part is to come up with the right triggers and balance the points required to fire up a suggestion.

Considering that events won't happen that often and will be read even rarer, optimizing the underlying data structure does not really matter.
> 1 votes

---
Tags: game-design, ai, game-mechanics
---


# Question
Title: Procedural generation of plausible genealogy tree with time query without history
So I'm laying out the basis for procedural generation of persistent and unique NPC across their entire life, many generation and space (travel).

But right now I'm stuck on plausible genealogy. Let assume that there is infinite ancestry and infinite descendant.

Now genealogy would be simple if we had a periodic symmetric tree (as the same number of children for all ancestor), ie all children are born at the same time. If we know the time of the first generation as an arbitrary number we know it's an offset that grow exponentially at each generation. For example assuming a binary tree, we know at arbitrary generation x that total birth was x² so every indexes in that interval belong to the same generation (and to find the total number of person who live once I'm sure there is a mathematical formula to found out). This is key we don't need to know the history to infer the population's size.

Let say you have a family line. You have a mother, she hit her fertility maturity's range and give birth to a random number of child at random time. So the genealogy have a random number of branch at random time from the root ... Less easy to infer generation locally.

Let's simplify the problem to a single line (a path in the tree from 1 ancestor to 1 descendant) and assuming that all NPC are women that spontaneously give birth (men don't give birth so they don't generate branch directly, they are dead end, so we can safely ignore this point).

We have a random series where each new point is the birth of a new npc, let assume you have an input t that is use to "query" the function such as it return if the character is born or not. The problem is that all descendant's birth time depend on the sum of all the previous interval between each birth + its new random interval, which is non local ... The same problem apply for the random branch, how do we know which "branch indexes" to not visit y generation down because it was never generated?

The think is there a plausible solution to this that would give at least the illusion of randomness? In a query without history?

**EDIT:** What I'm trying to determine is for a given time t, all the branches (list of indexes) that exist (character birth) without having the history of state (building the whole tree).

I have demonstrate it's possible with a symmetric ordered tree periodic on t (ie all generation happen at given interval, character indexes are predictable because of ordered tree).

I'm trying to determine if there is a pseudo random way to have a non symmetric tree with (apparently) non periodic branch and still query all the existing branch at time t.

OR if there is a better way to create the illusion of tree without the hassle to predict the tree random recurrence.

**EDIT2** The point was to avoid simulation like we do in generating landscape with perlin noise, hence why I'm investigating random interval in a tree (where each branch have a differing growth rate).

# Answer
> Let assume that there is infinite ancestry and infinite descendant.

If we can dial that down a little bit (because infinite simulations are hard), we can take a pretty simple concrete approach, and generate them up front.

Choose some parameters, like, say

* a stable population
* of one million people
* over one million years
* 50% gender balance
* fertility ages 15-50.
* (We don't necessarily need to choose a lifespan; keeping the population stable will imply one.)

psuedocode:

```
Generate initial population, one million records, random ages.

For year = 0 to one million:
{
    For each citizen:
    {
        Decide if they hook up, with whom, and reproduce
           Add new birth records
        Decide if they die (biased to keep population stable)
           Add date of death to their record
    }
}

```

If average age to reproduce is 33, and each female produces an average of 2 children (around age 33), then the number of records is:

```
1e6 * 1e6 / 33 = ~30 billion records

```

That's kind of a lot. Maybe 50,000 citizens over 10,000 years is enough? Then we have only:

```
5e4 * 1e4 / 33 = ~15 million records, quite tractable.

```

> is there a plausible solution to this that would give at least the illusion of randomness? In a query without history?

If your player is a traveler in time and space, we could generate this sparsely, only when they visit a particular time and place. Then we'll need to "stitch together" genealogical regions if they start visiting more of the nearby times or planets, with plausible genealogy.

Even if you show huge crowds, they only need to have a story if you meet them or click them...
> 1 votes

# Answer
After the edits, if I get it right - you are overcomplicating things:
you need a single level of n-ary tree that, looks like it has all previous levels generated randomly, right? Well, why not take n-ary tree level, for simplicity binary tree.
Lets say you want 6th level, that is 32 elements if that is full binary tree. Now generate random 32-bit integer AND it with the 32-member array if true, there is a person, if false there is null member.

```
int[] array = new int[1 << level];
for(int i = 0, int r = rnd.next(), i < 32, i++)
{
if(r & (1 << i))
   array[i] = new Person;
else
   array[i] = null;
}

```

to further enhance randomness, you can use the idea of perlin noise - "overlay" several random numbers, each with different "locality".

```
int r_alpha = rnd.next();
for...
if(i % 32 == 0)
   r_alpha = rnd.next();
if( (r | r_alpha) & (1 << i))
...

```

ofcourse, it will probably need to be more complicated than simple OR or AND(to simulate families, which should be probably aligned blocks of persons), but you will get a level of binary tree, PLUS you should be also able to compute next and previous levels if needed as you can tree it as array-stored binary tree(with computable index shift).
**Edit:**
Well, I *do* connect family here. That thing is a tree! You can query their parents - their "parents" are at virtual array index `floor((i - 1)/2)`, siblings are at `i-1` or `i+1` (depending one whether it is left or right sibling), as well as you know children of current generation will be at `2i + 1` and `2i + 2`. By virtual indices I mean indices for not-generated tree parts, and the `array[0]` is actually at virtual index of `all_previous_levels_count = (1 << level) - 1;`. I am sure you wont have any problems to exapand this binary tree example to 2-3 or n-ary tree. You can get the requested previous generation persons by querying siblings and determining whether their (grand) parents still live. As if there is a person, their parents *must* have existed at some point.
> 1 votes

# Answer
I think I should have describe it as "procedural persistence of infinite family line", the goal is to have a tool for world building and story generation, where the past and future are query from a formula rather than simulated. This last point open the scale to infinity as you remove dependence.

An *incomplete* method might be:

* To generate list each generation and use the growth formula to define the size. SO n² growth have t1=1, t2=4, etc ...
* For each generation list we group character's indexes in sibling group.
* We (pseudo) randomly assign those sibling to fertile parents.
* We offset birth time within the fertility range of parents.

This Method Have the advantage of giving more flexibility as you can do weird stuff with the growth formula and not depend on a tree (let say you want a an infinitely stable population, family lines with cycle of growth and decrease, or weird family lines that decrease from infinity to nothing as time progress)

The main problem is that all generation are still kinda sync together, we can't have a family line that grew more rapidly during a certain time. We can have multiple family lines with different growth rate and formula, but each family line is stuck inside it's growth rate profile. I wonder If there is a last method to shuffle this one a bit.
> 1 votes

---
Tags: procedural-generation
---


# Question
Title: Implementation of finding an index in a 1D array for a triangular grid
Am using a while loop to find an index within a 1D array, is there an easier, less-time-consuming and/or mathmatical way to find the index?

Consider the next grid:

```
 4   o
     |\
     | \
     |  \
 3   o---o
     |\  |\
     | \ | \
     |  \|  \
 2   o---o---o
     |\  |\  |\
     | \ | \ | \
     |  \|  \|  \
 1   o---o---o---o
     |\  |\  |\  |\
     | \ | \ | \ | \
     |  \|  \|  \|  \
 0   o---o---o---o---o

     0   1   2   3   4

```

To find an index in the triangular grid within a 1D array I have the next function:

```
//int size = 5;
int getindex( int x, int y )
{

    int columnCount = size;
    while( y-- > 0 ) x += columnCount--;

    return x;

}

```

The array (The numbers within the parenthesis are the coordinates and to simplify your view, in reality the (x,y) is in its whole the data):

```
pointdata data[ 15 ] = {
    (0,0), (1,0), (2,0), (3,0), (4,0),
    (0,1), (1,1), (2,1), (3,1),
    (0,2), (1,2), (2,2),
    (0,3), (1,3),
    (0,4),
};

```

# Answer
> 1 votes
This is rather problem to sum numbers between *n* and *m*, which is pretty widely known: it is sum of numbers 1 to *m* minus sum of numbers 1 to *n*(n-1 infact, but it gets eliminated in the code) plus *x*, ofcourse. In your example, it is:

`index = columnCount * ( columnCount + 1 ) / 2 - ( columnCount - y ) * ( columnCount - y + 1 ) / 2 ) + x;`
plus, since column count is static (presumably), you can pre-cumpute the first part or even better just use total length of your array.

---
Tags: algorithm, grid
---


title: Destroying object from object method

text:
# Question
Title: Destroying object from object method
My game uses an entity manager and entities to represent everything including the player, enemes, items, ..everything in the game. In my engine it's the responsibility of every entity to update itself.

Sometimes an entity finds out it has expired somehow, and thus needs to remove itself from the entity manager. My question is: Is it safe to have an object delete itself? I will illustrate what I mean.

```
void EntityManager::remove_entity(Entity* entity) {
    m_entities.erase(std::remove_if( //...
}

void Entity::update() {
    if (has_expired)
        m_manager.remove_entity(this); // <- safe?
}

```

I can't concretely prove a bug by using this, but it kind of looks and feels like it should at least be undefined behaviour. So is it OK? If not, what is a common practice for dealing with this situation?

# Answer
You could create a pool at the manager which will clean up all after or before the EntityManager::update. This way it is save. using 'delete this' will raise big issues amongst a lot of developers.

```
std::vector m_garbage;
void EntityManager::collect(Entity* entity) {
    entity->collected = true;
    garbage.push_back(entity);
}
void EntityManager::update(..) {
    // erase all in m_garbage
}

```
> 1 votes

# Answer
It depends on what `remove_entity` does. If you're freeing some memory then you shouldn't access the `this` pointer after calling `remove_entity`. If you're just marking the entity as "to be deleted later", then you can do whatever you want with it.

Usually what happens is entities add themselves to a buffer, and at the end of the game's update loop the manager loops over the buffer and deletes all the entities. This would be called delayed destruction, and is usually the appropriate way to do this sort of thing.
> 0 votes

---
Tags: c++, entity-system, gameobject, memory
---


title: What are .fxo and .cod files for?

text:
# Question
Title: What are .fxo and .cod files for?
I've been reading about shaders and looking at code. I found this in the code I'm looking at and it obviously has "Basic.fxo" there.

```
BasicFX = new BasicEffect(device, L"FX/Basic.fxo");

```

Now my question is what the file is for? I look in the folder and there is Basic.fx, Basic.fxo, and Basic.cod. I'm familiar with Basic.fx that's the shader? So I took out the .fxo and .cod reran the program and it just regenerated the files? What are the .cod/.fxo files for? Where do they come from? What do they do?

# Answer
> 2 votes
The `.fxo` files are compiled shader files. Think of `.obj`/`.o` files for C and C++, but for HLSL. They're the result of running the shader compiler `fxc.exe` over your shader files.

The advantages of `.fxo` files are three fold. First, the make reverse engineering of your shader code a bit more difficult, which is advantageous for some of the higher-end games with a lot of secret sauce in their shaders.

Second, some platforms do not actually allow you to use the HLSL compiler. Earlier iterations of Windows Store apps for instance did not allow applications to use `d3dcompiler_XX.dll`, so it was mandatory to precompile shaders for these platforms. Even on plain ol' desktop Windows, you are responsible for shipping `d3dcompiler_XX.dll` as it is not part of the end-user redistribution package.

Third, compiling HLSL takes time. Precompiling the shaders shaves off some load time for an application, though it's not necessarily much time at all.

In general it's good practice to precompile your shaders and ship the `.fxo` files.

I've never seen a `.cod` file and don't know what it's for; Google is not clearing it up.

---
Tags: c++, shaders, directx, hlsl
---


title: "aim at" in 3D space algorithm

text:
# Question
Title: "aim at" in 3D space algorithm
I'd to calculate the cartesian rotate values of "aiming" one point at another in 3D space.

**For example, assuming rotation order of XYZ:**
Point A is at \[0, 0, 0\] Point B is at \[2, 2, 0\]

If point A was "aiming" at point B with primary (aim) axis X, secondary (up) Y; point A's rotate values would be \[0, 0, 45\]. These values are what I'd like to calculate.

# Answer
It's assumed that point A is at the origin. Let **d** be the unit vector in the direction point A is currently looking at, and **p** be the unit vector in the direction of `B - A`.

Notice that **d** and **p** necessarily define a plane in 3D-space. If you can imagine this, then it becomes clear that a single rotation of **d** by an amount equal to the angle between these two vectors about the normal to this plane will orient point A towards point B. The goal is to find out what the angle between these two vectors and the normal to the plane they define are. (Don't worry, I will get to Euler Angles soon!)

With basic linear algebra we have (I am assuming a familiarity with these operations):

**acos(dot(d,p)) = the angle between d and p**, I'll call it **theta**.

**cross(d, p)/length(cross(d,p)) = unit normal to the plane defined by d and p**, I'll call it **n**.

With an angle to rotate by and an axis of rotation, we can define a quaternion to represent this rotation. (If you aren't familiar with quaternions at all, it's fine; they're only used as an intermediate step here to get to the Euler angles you want.)

This quaternion will be equal to:

**q** = cos(theta/2) + (nx**i** \+ ny**j** \+ nz**k**) * sin(theta/2), where nx is the x-component of **n**, and so on.

Finally, there is the formula for converting from quaternion to Euler angle representation of a rotation.

$$ \begin{bmatrix} \phi \\ \theta \\ \psi \end{bmatrix} = \begin{bmatrix} atan2(2(q\_0q\_1+q\_2q\_3),1-2(q^2\_1+q^2\_2)) \\ arcsin(2(q\_0q\_2-q\_3q\_1)) \\ atan2(2(q\_0q\_3+q\_1q\_2),1-2(q^2\_2+q^2\_3)) \end{bmatrix} $$

and in our case:

q0 = cos(theta/2)

q1 = sin(theta/2) * nx

q2 = sin(theta/2) * ny

q3 = sin(theta/2) * nz
> 1 votes

---
Tags: 3d, mathematics, coordinates
---


# Question
Title: Where can I find the DirectX SDK to work on D3D8?
I know this in unprofessional and probably doesn't follow the question asking conventions on this site, but I cannot find any other, more suitable (in my opinion) network on stackexchange to ask this question:

Where can I download the DirectX 8.0 SDK ? It seems all the download sources have vanished few years ago. Neither does Microsoft host 8.0 setup files anymore.

I have searched first 25 pages of google for "dx8sdk.exe" but not a single link is alive to download it.

Apologies..

**EDIT:**

I failed in finding the full SDK, but was able to get `d3d8.h` and `d3dx8.h` files for 8.0 version. So, if you download 8.1 SDK (easy), install it, and then replace the upper mentioned two files with ones from this thread: http://forum.ghbsys.net/index.php?/topic/2772-help-to-fixx/?pid=24384&mode=threaded you should have a hacky 8.0 SDK installed.

**EDIT2:** August 2007 SDK was the latest one to ship with pre-DX9 technology

# Answer
There is no need to have a DX8 SDK. Most of the older DX9 SDKs include the necessary files for D3D8 (include/lib).

This one includes the required files, for example: http://www.microsoft.com/en-us/download/details.aspx?id=10368

As for the 8.0/8.1 thing, if that's a concern - Microsoft never separated these as DLLs so it's safe to assume that they're quite compatible. One source confirms it being a minor upgrade: ftp://ftp.hercules.com/faqs/eng/her\_eng\_00044.pdf
> 0 votes

---
Tags: c++, directx
---


title: Problem with SLD/OpenGL

text:
# Question
Title: Problem with SLD/OpenGL
I've started to do sth. with SDL/openGL, but I haven't managed to get this tutorial running yet (http://www.sdltutorials.com/sdl-opengl-tutorial-basics).

Since this tutorial, or most tutorials at all, are written in SDL 1.2, I changed just this part of the tutorial's code:

instead of:

```
if((Surf_Display = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_GL_DOUBLEBUFFER | SDL_OPENGL)) == NULL)

```

to:

```
SDL_Window *window;
if((window = SDL_CreateWindow("SDLWindow", SDL_WINDOWPOS_UNDEFINED,
                              SDL_WINDOWPOS_UNDEFINED,
                              640, 480,
                              SDL_GL_DOUBLEBUFFER | SDL_WINDOW_OPENGL)) == NULL)

```

Now, all parts of the code seem to be correctly except the last one, this is "SDL\_GL\_SwapBuffers()";

Xcode says: use of undeclared identifier....

I think it's deprecated in SDL 2.0, but I couldn't find the right function in the migration guide, or is the problem something else?

Can anyone help me with that?

# Answer
The new function is `SDL_GL_SwapWindow()` and it takes your window pointer.
> 1 votes

---
Tags: opengl, sdl
---


# Question
Title: SetRenderTarget(null) clearing previous draw calls
I'm not sure if everything's working as it should be or whether I'm just not doing something properly, but I couldn't find anything that discussed this so I thought I'd ask here.

I'm using Monogame 3.2 for Windows.

In my game I'm drawing sprites to the back buffer, then I set a render target and draw to that, then I switch back to the back with SetRenderTarget(null) so I can draw my render target but I find that all the drawing I did before I set the render target the first time has been cleared. Is this just how it works or have I done something wrong?

EDIT: The pink rectangle is the render target.

Here is example code:

```
        // Render some stuff first
        spriteBatch.Begin();
        spriteBatch.Draw(mPixel, new Rectangle(10, 10, 500, 50), Color.Red);
        spriteBatch.End();

        // Render to target
        GraphicsDevice.SetRenderTarget(renderTarget);
        GraphicsDevice.Clear(Color.Pink);
        spriteBatch.Begin();
        spriteBatch.Draw(mPixel, new Rectangle(10, 10, 500, 50), Color.Blue);
        spriteBatch.End();

        // Render back to backbuffer
        GraphicsDevice.SetRenderTarget(null);
        spriteBatch.Begin();
        spriteBatch.Draw(renderTarget, Vector2.Zero, Color.White);
        spriteBatch.End();

```

Here is the result, I expected the first red rectangle to remain behind the render target:

# Answer
Having the exactly same issue here - the following code snipped works perfectly fine:

```
private void DoRenderSkybox (GameTime Time) {
  this.Device.SetRenderTarget(this.GridTexture);
  this.Device.SetRenderTarget(null);

  // compute a temporary transformation matrix containing
  // the combined world and projection transfromation
  Matrix WorldViewProjection = this.Camera.View * this.Camera.Projection;

  // set the render target to the back buffer in any case
  this.Device.SetRenderTarget(null);

  // assign the vertex - declaration and the vertex- and the index - buffer
  this.Device.SetVertexBuffer(this.SkyboxVertices);
  this.Device.Indices = this.SkyboxIndices;

  // choose the appropriate technique for the current render pass
  this.SceneEffect.CurrentTechnique = SceneEffect.Techniques["Skybox"];
  this.SceneEffect.CurrentTechnique.Passes[0].Apply();
  this.SceneEffect.Parameters["WorldViewProjection"].SetValue(WorldViewProjection);

  // finally render the sykbox with disabled depth stencil buffering
  this.Device.DepthStencilState = DepthStencilState.None;
  this.Device.DrawIndexedPrimitives( PrimitiveType.TriangleList, 0, 0, 36, 0, 12);
  this.Device.DepthStencilState = DepthStencilState.Default;

  //this.Device.SetRenderTarget(this.GridTexture);
  //this.Device.SetRenderTarget(null);
}

```

However, if I assign (and right away unassign) the render target at the end of the function like so:

```
    private void DoRenderSkybox (GameTime Time) {
  //this.Device.SetRenderTarget(this.GridTexture);
  //this.Device.SetRenderTarget(null);

  // compute a temporary transformation matrix containing
  // the combined world and projection transfromation
  Matrix WorldViewProjection = this.Camera.View * this.Camera.Projection;

  // set the render target to the back buffer in any case
  this.Device.SetRenderTarget(null);
  this.Device.Clear(Color.Black);

  // assign the vertex - declaration and the vertex- and the index - buffer
  this.Device.SetVertexBuffer(this.SkyboxVertices);
  this.Device.Indices = this.SkyboxIndices;

  // choose the appropriate technique for the current render pass
  this.SceneEffect.CurrentTechnique = SceneEffect.Techniques["Skybox"];
  this.SceneEffect.CurrentTechnique.Passes[0].Apply();
  this.SceneEffect.Parameters["WorldViewProjection"].SetValue(WorldViewProjection);

  // finally render the sykbox with disabled depth stencil buffering
  this.Device.DepthStencilState = DepthStencilState.None;
  this.Device.DrawIndexedPrimitives( PrimitiveType.TriangleList, 0, 0, 36, 0, 12);
  this.Device.DepthStencilState = DepthStencilState.Default;

  this.Device.SetRenderTarget(this.GridTexture);
  this.Device.SetRenderTarget(null);
}

```

nothing is being rendered - I got a purple screen! Does that make any sense to you!

P.S. I know the sample doesn't make much sense (like assigning and right away unassigning a render target). The real scenario here is much more complicated but I was able to narrow down the essence of the problem to this strange behaviour, which I can demonstrate in this very simple example!

EDIT: Just found the solution by further examining the API: Adding Params.RenderTargetUsage = RenderTargetUsage.PreserveContents; into the PresentationParameter structure solves the problem.

It looks to me that the content of the backbuffer is - like with render targets being destroyed whenever you switch to another render target.
> 4 votes

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


title: Unity2D Collision Issue

text:
# Question
Title: Unity2D Collision Issue
I have a crate setup (in pic below) with a rigid body component, box collider and 3 circle colliders(they allow me to push the crate most of the time without getting stuck on the floor textures which are normal box colliders) As you can see in the pic there are collisions detected between the crate and floor even though they are not physically touching.

How can i make the collisions more precise as my crate gets snagged on the floor textures when there is minuscule difference between the floor box colliders?

# Answer
I would reccomend removing your box collider and then add it back again. It will automatically resize to fit your texture. It looks like it is a bit off to me.

The ground detection looks fine, but both the corner circle colliders are too low. This will cause unrealistic looking collision detection, unless you have reasons for the collider offsets.
> 1 votes

# Answer
I would add a slippery physics material then adjust the friction to fit your game. It should fix any hang ups.
> 0 votes

---
Tags: unity, 2d, collision-detection, physics, collision-avoidance
---


# Question
Title: Manipulating vertices after multiplication with MVP matrix (OpenGL)
I'm making a collage of lots 16x16 renders on a 512x512 texture, of the same scene, from various viewing positions and angles, preferably lots of times per second. I've profiled my program (which contained a glDrawElements call per mesh), and the multiple glDrawElements calls seemed to slow it down a lot. In order to optimize, I've resorted to instanced rendering. However, the main problem I'm having is changing the viewport between, say, every 3 instance renderings, or so. I was thinking of adding a fourth matrix, which would scale the perspectively-projected vertices of a would-be 16x16 picture, translate them so that the little images don't overlap, and based on the little picture's position and size (16x16 pixels) on screen, use the \`discard' command in the pixel shader.

How do I scale the projected vertices from the current large viewport into a 16x16 smaller version of it and translate them inside the former at a certain position?

Or, more clearly, how do I change the viewport during a glDrawElementsInstanced call, every N instances?

**EDIT** Here's a visualization of what I'm trying to achieve:

Keep in mind, I can't change the viewport as I want to do this during a call to glDrawEleemntsInstanced, every 3 instances, or so.

How do I compute a matrix or what do I have to do to get the post-projection vertices scaled and translated so that I'll have the full image scaled in a 16x16 portion of the screen?

# Answer
From what I understand you are trying to render a scene many times from many views into a tilemap.

To do that I would make each tile a layer of a Texture\_2D\_Array, and bind to a 3D framebuffer.
In the first phase, render your scene instanced with view per instance, then in geometry shader (only place you can set it) set gl\_Layer = instance.
In the second phase simply render all layers of the array onto the tile atlas.

By using a framebuffer you eliminate the need to cull using discard, which would have a severe performance impact. It will also make the code much more readable than doing all of this in vertex stage.
> 1 votes

---
Tags: opengl
---


# Question
Title: C++, OpenGL: Building a polyhedron via geometry shader
I'm stuck with geometry shaders in OpenGL - c++ programming. I want to create simple cube by repeating 6 times drawing one rotated wall. Here is my vertex shader (everyting has #version 330 core in preamble):

```
uniform mat4 MVP;
uniform mat4 ROT;
layout(location=0) in vec3 vertPos;
void main(){
    vec4 pos=(MVP*ROT*vec4(vertPos,1.5));
    gl_Position=pos;
}

```

Now geometry shader:

```
layout (triangles) in;
layout (triangle_strip, max_vertices = 6) out;
out vec4 pos;
void main(void)
{
    for (int i = 0; i < 3; i++)
    {
        vec4 offset=vec4(i/2.,0,0,0);
        gl_Position = gl_in[i].gl_Position+offset;
        EmitVertex();
    }
    EndPrimitive();
}

```

And now fragment shader:

```
uniform mat4 MVP;
in vec4 pos;
out vec3 color;
void main(){
    vec3 light=(MVP*vec4(0,0,0,1)).xyz;
    vec3 dd=pos.xyz-light;
    float cosTheta=length(dd)*length(dd);
    color=vec3(1,0,0);
}

```

Well, there is some junk, I wanted also put shading into my cube, but I've got a problem with sending coordinates. The main problem is - here I get my scaled square (by MVP matrix), I can even rotate it with basic interface (ROT matrix), but when I uncomment my "+offset" line I get some mess. What should I do to make clean 6-times repeating?

# Answer
> 3 votes
Your geometry shader should take a single point (center of the cube) with a front vector and an up vector.

You can then output 12 triangles (6 faces x 2 tri for a quad) using the single point as the center of the cube and the cross-product of front & up for the right vector.

```
// table of all triangle vertices to make the cube
const vec3 face_table[12*3] = {
  vec3(1, 1, 1), vec3(-1, 1, 1), vec3(-1, -1, 1),  // first face Z=1
  vec3(1, 1, 1), vec3(-1, -1, 1), vec3(1, -1, 1),
  vec3(-1, 1, -1), vec3(1, 1, -1), vec3(1, -1, -1),  // second face Z=-1 (note the inverted X for culling)
  vec3(-1, 1, -1), vec3(1, -1, -1), vec3(-1, -1, -1),
  ... // and so on
};

```

Then generate the faces in a 12 triangle loop:

```
vec3 right_vector = cross(front_vector, up_vector); // or you can preset it as uniform

for(int i=0; i < 12*3; ++i){
  gl_Position = MVP*vec4((gl_in[i].gl_Position.xyz + face_table[i].x * right_vector + face_table[i].y * up_vector + face_table[i].z * front_vector), 1);
  EmitVertex();
}

```

Note that you can also use your ROT matrix uniform in the geometry shader instead: `right_vector = ROT[0]`, `up_vector = ROT[1]`, `front_vector = ROT[2]`.

And that MVP is now in the geometry shader. The vertex shader should be a simple pass-through `gl_Position=vec4(vertPos, 1)`.

EDIT: fixed vec4+vec3 error, flipped the face vertex order of -Z face for proper culling.

# Answer
> 2 votes
Instead of building the cube in geometry shader from a point, its better to do an instanced render of a simple cube VBO, and forego a geometry shader entirely.

The only time you wouldn't want to do that is if each cube has rapidly changing orientation and you need to recalculate its modelview every pass.
In which case, have position and orientation as vertex attributes, then build the mvp per point-cube in the vertex shader, then do as Stephane explained in geometry using a corner-table.

---
Tags: opengl, c++, geometry-shader
---


# Question
Title: OpenGL 4.4 LWJGL - How can i render text to the screen
I have been told that you need to create a texture atlas for the font, and individually assign each character to a texture and add them up to create the string you want to produce. This seems a little more difficult than it should be. Is there another way? If not there must be documentation or a library someone wrote to do this. Can someone help me out?

# Answer
You don't *have* to do it that way. That just happens to be one of the easier solutions that also give good results. You can also attempt to compile a font down to outlines and render those, but that's a lot harder. Note that what you're saying isn't that difficult because you can do it mostly automatically.

And yes, there are libraries that already implement most of that. Just google OpenGL font rendering libraries - you'll have to figure out on your own which of these is appropriate for your use case (e.g. what kind of OpenGL profile are you targeting, what kind of languages do you need to support etc etc).
> 1 votes

---
Tags: opengl, java, text
---


# Question
Title: How to create a line that is always connected to two Objects. (iPhone, Cocos2d)
I'm wanting to create a rope like animation effect. I don't need any kind of rope physics, all I need is a straight line connected to Object A and the other end connected to object B. Object A and B move relative to one another. So how do I make it so that the line is always attached to both Objects, even thought the distance between the objects decrease and increase?

The game is in 2D space.

# Answer
To draw a line:

https://stackoverflow.com/questions/691648/how-to-draw-a-line-with-cocos2d-iphone

To have it follow two points, simply keep track of the desired start and end points, and draw the line using those points for every update. In this specific circumstance, you would use the position of your two objects, something akin to this pseudocode:

```
Point start = objectA.position
Point end = objectB.position

glLineWidth(5.0f);
drawLine(start.x, start.y, end.x, end.y)

```
> 0 votes

---
Tags: ios, cocos2d-iphone
---


# Question
Title: Having trouble getting shader to work with sprite batch in XNA #4
I found a neat "CRT screen" effect shader on the web, but I've never used shaders before and I can't seem to get it working properly. If I do the second sprite batch in my code here normally without the effect of the shader, it renders fine. However, with the shader and the parameters I have provided, it just renders a few pixels up in the top left corner, where the faked "bezel" should be and sometimes the fake "screen" flashes one colour or an other.

Is there something wrong with the parameters I'm providing? I'm really stumped.

```
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        viewport = GraphicsDevice.Viewport;
        soldierFont = Content.Load<SpriteFont>("SpriteFont1");

        ShaderRenderTarget = new RenderTarget2D(spriteBatch.GraphicsDevice, spriteBatch.GraphicsDevice.PresentationParameters.BackBufferWidth, spriteBatch.GraphicsDevice.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.None);
        WorkingTexture = new Texture2D(GraphicsDevice, SCREENWIDTH, SCREENHEIGHT);
        WorkingTexture1 = new Texture2D(GraphicsDevice, SCREENWIDTH, SCREENHEIGHT);

        effect = Content.Load<Effect>(@"cgwg-xna");
        projection = Matrix.CreateOrthographicOffCenter(0, viewport.Width, viewport.Height, 0, 0, 1);
        halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
        effect.Parameters["World"].SetValue(Matrix.Identity);
        effect.Parameters["View"].SetValue(Matrix.Identity);
        effect.Parameters["Projection"].SetValue(halfPixelOffset * projection);
        effect.Parameters["Worldview"].SetValue(Matrix.Identity * Matrix.Identity);
        effect.Parameters["ViewProjection"].SetValue((Matrix.Identity * (halfPixelOffset * projection)));
        effect.Parameters["WorldViewProjection"].SetValue((Matrix.Identity * (halfPixelOffset * projection)));
        effect.Parameters["WorkingTexture"].SetValue(WorkingTexture);
        effect.Parameters["WorkingTexture1"].SetValue(WorkingTexture1);

```

and then

```
    protected override void Draw(GameTime gameTime)
    {

        GraphicsDevice.SetRenderTarget(ShaderRenderTarget);
        GraphicsDevice.Viewport = viewport;
        GraphicsDevice.Clear(Color.Black);

        //get rid of blurry sprites
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);

        if (_currScreen != null)
        {
            _currScreen.draw(gameTime, spriteBatch);
        }
        base.Draw(gameTime);

        spriteBatch.End();

        GraphicsDevice.SetRenderTarget(null);
        effect.Parameters["SourceTexture"].SetValue(ShaderRenderTarget);
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, RasterizerState.CullNone, effect);
        spriteBatch.Draw(ShaderRenderTarget, Vector2.Zero, Color.White);
        spriteBatch.End();
    }

```

the shader is pretty crazy and is as follows:

```
    // Matrix Definitions for Scaler Effects
    //

    matrix World                : WORLD;
    matrix View             : VIEW;
    matrix Projection           : PROJECTION;
    matrix Worldview            : WORLDVIEW;            // world * view
    matrix ViewProjection           : VIEWPROJECTION;       // view * projection
    matrix WorldViewProjection      : WORLDVIEWPROJECTION;      // world * view * projection

    //
    // Source Texture Definition for Scaler Effects
    //

    // Image Dimentions
    float2 SourceDims : SOURCEDIMS = {1024.0F, 768.0F};

    // Size of one Texel
    float2 TexelSize  : TEXELSIZE = 1.0F/768.0F;

    //
    // Source Texture
    //
    texture SourceTexture               : SOURCETEXTURE;

    sampler SourceSampler = sampler_state {
        Texture   = (SourceTexture);
        MinFilter = POINT;
        MagFilter = POINT;
        MipFilter = NONE;
        AddressU  = Clamp;
        AddressV  = Clamp;
        SRGBTEXTURE = FALSE;
    };

    sampler BilinearSourceSampler = sampler_state {
        Texture   = (SourceTexture);
        MinFilter = LINEAR;
        MagFilter = LINEAR;
        MipFilter = NONE;
        AddressU  = Clamp;
        AddressV  = Clamp;
        SRGBTEXTURE = FALSE;
    };

    sampler SRGBSourceSampler = sampler_state {
        Texture   = (SourceTexture);
        MinFilter = POINT;
        MagFilter = POINT;
        MipFilter = NONE;
        AddressU  = Clamp;
        AddressV  = Clamp;
        SRGBTEXTURE = TRUE;
    };

    sampler SRGBBilinearSourceSampler = sampler_state {
        Texture   = (SourceTexture);
        MinFilter = LINEAR;
        MagFilter = LINEAR;
        MipFilter = NONE;
        AddressU  = Clamp;
        AddressV  = Clamp;
        SRGBTEXTURE = TRUE;
    };

    //
    // Working Texture and Working RenderTarget
    // Same Dims as Source Texture
    //
    texture WorkingTexture              : WORKINGTEXTURE;

    sampler WorkingSampler = sampler_state {
        Texture   = (WorkingTexture);
        MinFilter = POINT;
        MagFilter = POINT;
        MipFilter = NONE;
        AddressU  = Clamp;
        AddressV  = Clamp;
        SRGBTEXTURE = FALSE;
    };

    texture WorkingTexture1             : WORKINGTEXTURE1;

    sampler WorkingSampler1 = sampler_state {
        Texture   = (WorkingTexture1);
        MinFilter = POINT;
        MagFilter = POINT;
        MipFilter = NONE;
        AddressU  = Clamp;
        AddressV  = Clamp;
        SRGBTEXTURE = FALSE;
    };

    //
    // procedural textures that selects which pixel to generate
    //
    texture OutputSelectTexture
    <
        string function = "GenerateOutputSelect";   // Function to generate from
        int width = 2;
        int height = 2;
    >;

    // TextureShader for the OutputSelectTexture
    float4 GenerateOutputSelect(float3 Pos : POSITION) : COLOR
    {
        float4 ret = (float4)1;
        if (Pos.x < 0.5 && Pos.y < 0.5) ret[0] = 0;
        else if (Pos.y < 0.5) ret[1] = 0;
        else if (Pos.x < 0.5) ret[2] = 0;
        else ret[3] = 0;
        return ret;
    }

    // Sampler for the OutputSelectTexture
    sampler OutputSelectSampler = sampler_state
    {
        Texture   = (OutputSelectTexture);
        MinFilter = POINT;
        MagFilter = POINT;
        MipFilter = NONE;
        AddressU  = Wrap;
        AddressV  = Wrap;
        SRGBTEXTURE = FALSE;
    };

    //
    // A Simple Texture that can do a modulo (or frac) by a lookup, rather than by
    // using a arithmetic instruction. Not entirely accurate
    //
    texture ModuloTexture
    <
        string function = "GenerateModulo"; // Function to generate from
        int width = 16;
        int height = 16;
    >;

    // TextureShader for the ModuloTexture
    float4 GenerateModulo(float3 Pos : POSITION) : COLOR
    {
        return float4(Pos.x, Pos.y, 0, 0);
    }

    // Sampler for the ModuloTexture
    sampler ModuloSampler = sampler_state
    {
        Texture   = (ModuloTexture);
        MinFilter = POINT;
        MagFilter = POINT;
        MipFilter = NONE;
        AddressU  = Wrap;
        AddressV  = Wrap;
        SRGBTEXTURE = FALSE;
    };

    // The name of this effect
    string name : NAME = "CRTFX";
    float scaling : SCALING = 1.0;

    // Comment the next line to disable interpolation in linear gamma (and gain speed).
    #define LINEAR_PROCESSING

    // Compensate for 16-235 level range as per Rec. 601.
    #define REF_LEVELS

    // Enable screen curvature.
    #define CURVATURE

    // Controls the intensity of the barrel distortion used to emulate the
    // curvature of a CRT. 0.0 is perfectly flat, 1.0 is annoyingly
    // distorted, higher values are increasingly ridiculous.
    #define distortion 0.05

    // Simulate a CRT gamma of 2.4.
    #define inputGamma  2.4

    // Compensate for the standard sRGB gamma of 2.2.
    #define outputGamma 2.2

    // Macros.
    #define FIX(c) max(abs(c), 1e-5);
    #define PI 3.141592653589

    #ifdef REF_LEVELS
    #       define LEVELS(c) max((c - 16.0 / 255.0) * 255.0 / (235.0 - 16.0), 0.0)
    #else
    #       define LEVELS(c) c
    #endif

    #ifdef LINEAR_PROCESSING
    #       define TEX2D(c) pow(LEVELS(tex2D(SourceBorderSampler, (c))), inputGamma)
    #else
    #       define TEX2D(c) LEVELS(tex2D(SourceBorderSampler, (c)))
    #endif

    //
    // Techniques
    //

    // combineTechnique: Final combine steps. Outputs to destination frame buffer
    string combineTechique : COMBINETECHNIQUE = "CRTFX";

    // preprocessTechnique: PreProcessing steps. Outputs to WorkingTexture
    //string preprocessTechique : PREPROCESSTECHNIQUE = "";

    struct VS_OUTPUT_PRODUCT
    {
        float4 Position     : POSITION;
        float2 pixel0       : TEXCOORD0;
        float2 pixel1       : TEXCOORD1;
        float2 abspos       : TEXCOORD2;
    };

    sampler SourceBorderSampler = sampler_state {
        Texture   = (SourceTexture);
        MinFilter = POINT;
        MagFilter = POINT;
        MipFilter = NONE;
        AddressU  = Clamp; //AddressU  = Border;
        AddressV  = Clamp; //AddressV  = Border;
        //SRGBTEXTURE = FALSE;
    };

    // vertex shader
    VS_OUTPUT_PRODUCT VS_Product(
        float3 Position : POSITION,
        float2 TexCoord : TEXCOORD0)
    {
        VS_OUTPUT_PRODUCT Out = (VS_OUTPUT_PRODUCT)0;

        // Do the standard vertex processing.
        Out.Position = mul(half4(Position, 1), WorldViewProjection);

        // Precalculate a bunch of useful values we'll need in the fragment
        // shader.

        // Texture coords.
        Out.pixel0 = TexCoord;

        // The size of one texel, in texture-coordinates.
        Out.pixel1 = TexelSize;

        // Resulting X pixel-coordinate of the pixel we're drawing.
        // Assumes (-0.5, 0.5) quad and output size in World matrix
        // as currently done in DOSBox D3D patch
        Out.abspos = float2((Position.x + 0.5) * World._11, (Position.y - 0.5) * (-World._22));

        return Out;
    }

    // Apply radial distortion to the given coordinate.
    float2 radialDistortion(float2 coord, float2 pos)
    {
        pos /= float2(World._11, World._22);
        float2 cc = pos - 0.5;
        float dist = dot(cc, cc) * distortion;
        return coord * (pos + cc * (1.0 + dist) * dist) / pos;
    }

    // Calculate the influence of a scanline on the current pixel.
    //
    // 'distance' is the distance in texture coordinates from the current
    // pixel to the scanline in question.
    // 'color' is the colour of the scanline at the horizontal location of
    // the current pixel.
    float4 scanlineWeights(float distance, float4 color)
    {
        // The "width" of the scanline beam is set as 2*(1 + x^4) for
        // each RGB channel.
        float4 wid = 2.0 + 2.0 * pow(color, 4.0);

        // The "weights" lines basically specify the formula that gives
        // you the profile of the beam, i.e. the intensity as
        // a function of distance from the vertical center of the
        // scanline. In this case, it is gaussian if width=2, and
        // becomes nongaussian for larger widths. Ideally this should
        // be normalized so that the integral across the beam is
        // independent of its width. That is, for a narrower beam
        // "weights" should have a higher peak at the center of the
        // scanline than for a wider beam.
        float4 weights = distance / 0.3;
        return 1.4 * exp(-pow(weights * rsqrt(0.5 * wid), wid)) / (0.6 + 0.2 * wid);
    }

    half4 PS_Product ( in VS_OUTPUT_PRODUCT input ) : COLOR
    {
        // Here's a helpful diagram to keep in mind while trying to
        // understand the code:
        //
        //  |      |      |      |      |
        // -------------------------------
        //  |      |      |      |      |
        //  |  01  |  11  |  21  |  31  | <-- current scanline
        //  |      | @    |      |      |
        // -------------------------------
        //  |      |      |      |      |
        //  |  02  |  12  |  22  |  32  | <-- next scanline
        //  |      |      |      |      |
        // -------------------------------
        //  |      |      |      |      |
        //
        // Each character-cell represents a pixel on the output
        // surface, "@" represents the current pixel (always somewhere
        // in the bottom half of the current scan-line, or the top-half
        // of the next scanline). The grid of lines represents the
        // edges of the texels of the underlying texture.

        // Texture coordinates of the texel containing the active pixel.
    #ifdef CURVATURE
        float2 xy = radialDistortion(input.pixel0, input.abspos);
    #else
        float2 xy = input.pixel0;
    #endif

        // Of all the pixels that are mapped onto the texel we are
        // currently rendering, which pixel are we currently rendering?
        float2 ratio_scale = xy * SourceDims - 0.5;
        float2 uv_ratio = frac(ratio_scale);

        // Snap to the center of the underlying texel.
        xy = (floor(ratio_scale) + 0.5) / SourceDims;

        // Calculate Lanczos scaling coefficients describing the effect
        // of various neighbour texels in a scanline on the current
        // pixel.
        float4 coeffs = PI * float4(1.0 + uv_ratio.x, uv_ratio.x, 1.0 - uv_ratio.x, 2.0 - uv_ratio.x);

        // Prevent division by zero.
        coeffs = FIX(coeffs);

        // Lanczos2 kernel.
        coeffs = 2.0 * sin(coeffs) * sin(coeffs / 2.0) / (coeffs * coeffs);

        // Normalize.
        coeffs /= dot(coeffs, 1.0);

        // Calculate the effective colour of the current and next
        // scanlines at the horizontal location of the current pixel,
        // using the Lanczos coefficients above.
        float4 col  = clamp(
                mul(coeffs, float4x4(
                        TEX2D(xy + float2(-input.pixel1.r, 0.0)),
                        TEX2D(xy),
                        TEX2D(xy + float2(input.pixel1.x, 0.0)),
                        TEX2D(xy + float2(2.0 * input.pixel1.x, 0.0))
                )), 0.0, 1.0);
        float4 col2 = clamp(
                mul(coeffs, float4x4(
                        TEX2D(xy + float2(-input.pixel1.x, input.pixel1.y)),
                        TEX2D(xy + float2(0.0, input.pixel1.y)),
                        TEX2D(xy + input.pixel1),
                        TEX2D(xy + float2(2.0 * input.pixel1.x, input.pixel1.y))
                )), 0.0, 1.0);

    #ifndef LINEAR_PROCESSING
        col  = pow(col , inputGamma);
        col2 = pow(col2, inputGamma);
    #endif

        // Calculate the influence of the current and next scanlines on
        // the current pixel.
        float4 weights  = scanlineWeights(uv_ratio.y, col);
        float4 weights2 = scanlineWeights(1.0 - uv_ratio.y, col2);
        float3 mul_res  = (col * weights + col2 * weights2).rgb;

        // dot-mask emulation:
        // Output pixels are alternately tinted green and magenta.
        float3 dotMaskWeights = lerp(
                float3(1.0, 0.7, 1.0),
                float3(0.7, 1.0, 0.7),
                floor(input.abspos.x % 2.0)
            );

        mul_res *= dotMaskWeights;

        // Convert the image gamma for display on our output device.
        mul_res = pow(abs(mul_res), 1.0 / outputGamma);

        // Color the texel.
        return half4(mul_res, 1.0);
    }

    technique CRTFX
    {
        pass P0
        {
            // shaders
            VertexShader = compile vs_3_0 VS_Product();
            PixelShader  = compile ps_3_0 PS_Product();
            AlphaBlendEnable = FALSE;
            ColorWriteEnable = RED|GREEN|BLUE|ALPHA;
            //SRGBWRITEENABLE = FALSE;
        }
    }

```

The shader was originally made for emulators like DOSbox and was made by cgwg, Themaister, DOLLS and gulikoza

# Answer
I Googled extensively yesterday and today screwing around with a similar issue. It turns out that, when using SpriteBatch with a custom effect that samples from textures, you must explicitly asign the textures to a register other than 0.

```
effect.Parameters["WorkingTexture"].SetValue(WorkingTexture);

```
1. SpriteBatch assigns this texture to register 0
2. SpriteBatch then assigns every other texure you've loaded to register 0
3. Spritebatch then assigns the "Source/Screen" texture to 0

Beta-testing occurs after release now-a-days... If and when you can get PIX to work, bludgeoning through your code with it is, occasionally, not a complete waste of time. PIX is how i found this bug. Using PIX, verify that you have 2 or more occurences of

```
IDirect3DDeviceX::SetTexture(0, 0xXXXXXXXX)

```

between this draw and the previous. They will have other instructions between them. Once you have manually specified registers, one texture will remain assigned to 0 (screen texture) and the rest will be assigned elsewhere. In my case, they were internally assigned to 257, 0, and 3.

```
IDirect3DDeviceX::SetTexture(257, 0x07388110)
IDirect3DDeviceX::SetTexture(0, 0x07387EC0)
IDirect3DDeviceX::SetTexture(3, 0x07387E18)

```

Try this in your HLSL:

```
sampler WorkingSampler : register(s1) = sampler_state {
sampler WorkingSampler1 : register(s2) = sampler_state {

```

Or, try this (**not tested**) in your C#:

```
GraphicDevice.Textures[1] = WorkingTexture;
GraphicDevice.Textures[2] = WorkingTexture1;

```
> 1 votes

---
Tags: xna, shaders, directx, xna-4.0
---


# Question
Title: How to handle dimension changes on tileset? (Tiled)
I am using Tiled map editor.

My question is: What should I do if I would like to change the dimensions of the graphic file for the tileset? The IDs will shift if I will not adapt the graphic accordingly.

My idea is to write a simple script that can swap/shift the IDs in the map.
Is there a better way? Or is there a script already that I can use?

# Answer
> -1 votes
Well, if I'm not wrong, the IDs won't shift unless you add/remove tiles from the tileset. So simply changing the dimensions (higher resolution for example) won't change the order of the tiles and therefore the IDs will stay the same. Have you already tried what happens?

If the IDs change you could implement some kind of mapping table. So that you use one simple tileset for drawing the map in Tiled, which is then, maybe depending on platform or resolution, mapped to the real tileset during map load. What do you think?

---
Tags: tiled
---


# Question
Title: Codes for walking on platforms along with jumping using actionscript 2.0
I want to know the shortest and most understandable code for walking on platforms using actionscript 2.0.

I know there are multiple ways in doing it but my method becomes too tedious when a lot of platforms are needed.

So I just want to know:

1.) A code for walking on platforms and an easy way for me to add another working platform

2.) Code for jumping.

Codes I've been using so far:

```
//Gravity Variables

var grav:Number = 0;

var gravity:Number = 5;

var touchingGround:Boolean = false;

//Jump Variable

var maxJump:Number = -40;

//Code for player1

p1.onEnterFrame = function() {

//Gravity code

p1._y += grav;

grav += gravity;

while (ground.hitTest(p1._x, p1._y, true)) {

    p1._y -= gravity;

    grav = 0;

}

if (ground.hitTest(p1._x, p1._y+5, true)) {

    touchingGround = true;

} else {

    touchingGround = false;

}

//Jumping

//Jump Code

if (Key.isDown(Key.UP) && touchingGround) {

    grav = maxJump;

```

Optional, but can someone explain this part for me:

```
while (ground.hitTest(p1._x, p1._y, true)) {

    p1._y -= gravity;

    grav = 0;

}

```

# Answer
> 1 votes
If you place all of your interactive objects (floor pieces etc.) inside of the 'ground' movieclip, then you only need to check the ground movieclip for the hit test, so it should not be too tedious when a lot of platforms are needed, as long as they are all inside of that ground movieclip.

1&2) This is how I would do it. For this set up you need two MCs on the stage, one named 'man' (short for jumpman) and the other being 'ground' (to act as the thing we can jump and stand on). The following can go on a frame in the root of your movie.

```
_root.man.onLoad = function(){
    //the speed in which the man is currently falling
    this.gravity = 0;
    //if the man is currently jumping, keeps from double jumping
    this.jumping = false;
}

_root.man.onEnterFrame = function(){
    // if you hit the jump button
    if(Key.isDown(Key.UP) && !this.jumping){
        //change the 'gravity' of the character, so he is repelled from the floor
        this.gravity = -3;
        this.jumping = true;
    }
    // if you hit the left button
    if(Key.isDown(Key.LEFT)){
        // move left
        this._x-=5;
    }
    // if you hit the right button
    if(Key.isDown(Key.RIGHT)){
        // move right
        this._x+=5;
    }

    //every frame, let gravity push you down the screen
    this._y+=this.gravity;

    // if you are hitting the ground
    if(_root.ground.hitTest(this._x,this._y,true)){

        //no more jumping for you
        this.gravity =0;
        this.jumping = false;

        //if you want him to butt up to the top of the hittestable object
        //move him up until he is no longer hitting the ground.
        while(_root.ground.hitTest(this._x,this._y,true)){
            this._y-=0.1;//this can be changed to be as granular as needed, lower number is more accurate but more calculations
        }
    }

    //the longer you are falling for, the faster you go
    this.gravity+=0.1;
    //the fastest you can fall, aka terminal velocity
    if(this.gravity>5) this.gravity = 5;

}

```

Bonus Point:

While works like this: When the argument for while is true, while does what is in its brackets instantly, after doing so, it checks the argument again and repeats. If while is used even within a 'on enter frame' event, it will execute over and over until the argument is false, BEFORE it goes to the next frame (a common mistake). If you never stop the while look from running (aka if you run: while(true){/*something*/} ), then the game will freeze, because it will not progress to the next frame until that function is completed, which it never will complete in that scenario, because it is always true and keeps running over and over again.

In English the code that you selected reads like this: Check if p1 is hitting ground, and if so, then change the p1's position relative to gravity, and reset grav to zero, then recheck if p1 is hitting ground and repeat as needed, until p1 is no longer hitting the ground.

Hope that helps!

---
Tags: actionscript
---


# Question
Title: How to check a value from the last frame, while using events in Unity
What I am trying to do is check if a value has changed from the last frame, while using events. Typically I could use threading to my advantage and have a check at the bottom of Update() to see if a value that is typically changed higher up in Update() was changed or not.

However, I am programming with Events, and I don't rely on Update() in several classes to change data. When an event is published, it makes method calls to all methods subscribing to that event. CameraUpButton() is called by the event manager, not by Update(). ClearUp() is called from Update().

I want to see how long an event has been constantly published for, essentially seeing how long the up button has been held. Checking how long it has been held is the easy part, clearing it once the button is no longer held is the hard part since I do not know how to see when an event stopped publishing (I don't know if that is even possible?). So I'm resorting to making some logic to figure it out for me.

In this case:

```
 private int up;
 private void CameraUpButton()
 {
     up++;
     Vector3 cameraPos = Camera.main.transform.position;
     cameraPos.y += 0.01f;
     Camera.main.transform.position = cameraPos;
 }

 private void ClearUp()
 {
     some logic to determine
     if up has changed since the last frame
 }

```

**Edit:** I can make a Input.GetButtonUp("") event, however I want to see if this can be solved without relying on an event triggered by the button coming up. I would prefer if it can be solved without that reliance.

# Answer
> 0 votes
If I am understanding you correctly, you have an event which you have created, and you want to know how long a button is held down for after the event has started.

One way is: You can make two events, one for when the event started (aka CameraUpButton), and one for when the event has finished (aka CameraUpButtonComplete). You can save the time when the event was started in a property (such as a DateTime), and use that to compare when the second event (the 'finished' event) is run.

The other way is to use coroutines. Start a coroutine when the event is run and also make a note at the time it was run (in a DateTime property or similar), which listens for 'the end' of that event each frame, and it reports back (perhaps with an event of its own or a callback of some sort) with how long the button was held down for. This way will require the use of Input.Get~~~ to check each frame if the button is still down or not.

Events typically do not 'spin' (run continually) until the event is completed, so there is no good way on the event itself to keep track of how long the event has been 'activated' for.

In either case, when the first event comes in, it should clear any previously used property that is used to keep track of the length of time the button is held for. So if you started it Now (aka; DateTime.Now), then when it is done compare it to Then (aka; DateTime.Now), and you can get the amount of time that has passed.

If you are talking about Unity 4.6 and it's UI revamp, then what you need is an 'event trigger' component. In the trigger component you can have the Pointer Up event, which you can respond to to check how long the pointer was held down for (using the first method listed above).

Hope that helps!

---
Tags: c#, unity, events, logic
---


# Question
Title: How to "piece together" an image in code, to render later?
I want to make a game in Dart and have decided to use the available port of the JS Phaser game engine. This will be my first time really making a game involving graphics so I guess I'll have a lot to learn as I go along...

The main thing I'm trying to reason about doing in code at the moment is as follows: a key part of the game will be that the grid-based map that will be rendered onscreen will be previously generated to be composed of various "tiles" by an algorithm. You could think of it as analogous to a patchwork quilt I suppose in that regard. So naturally with a map like this I need to have some way of piecing together multiple copies of all my base tile images to form the appropriate map configuration to render. So essentially my question is how would I approach doing this in code so that I can indeed programmatically put together the image of my map and not render it tile-by-tile or something like that.

# Answer
> 2 votes
In most cases, doing what you propose will be *less efficient* than rendering the maps as individual tiles. The tiled approach gets more efficient the more tiles are repeated, and provided that the tiles aren't too small.

With Phaser, the Tiled format is well supported, so you can follow this workflow:

1. Create a tile map using Tiled
2. Export to JSON
3. Load the map files in Phaser
4. Render the map layers

There is a handy example here.

---
Tags: 2d, html5
---


title: Why is my screen black?

text:
# Question
Title: Why is my screen black?
I'm developing an android game, and my screen is not displaying what I want it to. I've read various tutorials but they are either outdated or hard to follow. I have followed this tutorial and most of the code is identical. However, when running the game, the screen is black.

**Game logic loop:**

```
public void run(){
    while(running){
        long beforeTime = System.nanoTime();
        gameEngine.update();
        Canvas c = null;
        try{
            c = holder.lockCanvas(null);
            //synchronized (holder){
                c.drawRect(0,0,c.getWidth(),c.getHeight(),blackPaint);
                gameEngine.draw(c);
            //}
        }finally{
            if(c!=null){
                holder.unlockCanvasAndPost(c);
            }
        }

        this.sleepTime = delay-((System.nanoTime()-beforeTime)/1000000L);
        try{
            if(sleepTime>0){
                this.sleep(sleepTime);
            }
        }catch(InterruptedException e){
            Logger.getLogger(GameThread.class.getName()).log(Level.SEVERE,null,e);
        }
    }
}

```

**Main activity:**

```
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                         WindowManager.LayoutParams.FLAG_FULLSCREEN);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_main);
}

```

**engine.draw(Canvas c):**

```
public void draw(Canvas canvas){
    Paint bluepaint = new Paint(Color.BLUE);
    canvas.drawRect(50,50,100,100, bluepaint);
}

```

**EDIT:**

@wondra I did test the break point, and the thread does actually get started, or so I think. The app runs and there are no errors thrown to the log console. Someone also suggested it was the emulator not running properly.

@fadden I have implemented what you suggested, still nothing... does starting the view from the xml and not from the Java have to do anything to do with it? Does the instance still exists if I don't declare it in Java?

# Answer
It looks like you're drawing on a SurfaceView surface. Bear in mind that the surface is a completely separate layer that, by default, sits behind everything else. The View part of the SurfaceView is a transparent "hole" that the layout code uses to adjust everything else around it. The most common way to get a black screen is to define an opaque background color for the View part.

A simple thing to try: use SurfaceView#setZOrderOnTop() to put the surface on top of everything else. You need to call this before the surface is created (`onCreate()`). If your rendering appears, then your render code is fine but your Views are obscuring your surface.

You may want to change your `blackpaint` to some other color (red) so you can see if any of it is visible.

Other tips: use `Canvas#drawColor()` to clear the screen, rather than a rectangle. Get rid of `postInvalidate()` -- by definition you are drawing on a separate layer and you do not need or want the Views to do anything. You don't need the `synchronized (holder)` either.

You may also want to read about game loops in the graphics architecture doc.
> 2 votes

---
Tags: java, android, rendering, game-loop
---


# Question
Title: How to remove the jitter from my pong AI movement?
I am developing Pong using Monogame / XNA and my AI paddle is really jittery when the ball is moving more horizontally than vertically.

My AI is very simple and works as follows:

* If the ball's position is greater than the paddle position I increase the paddle's y position by 3
* If the ball's position is less than the paddle position I decrease the paddle's y position by 3

Where is the flaw in my logic that would cause jittering when the ball is moving more horizontally than vertically?

# Answer
> 4 votes
What your algorithm doesn't account for is if the ball's vertical speed is less than your paddle's speed (in your specific scenario, 3).

Consider the following example:

* The ball is moving perfectly horizontally (y speed is zero)
* The AI paddle uses a vertical speed of 3 units as in your exact scenario
* The paddle's y position is 10
* The ball's y position is 11
* List item

How this will play out is as follows:

* Frame 1: The paddle is lower than the ball. We increase the paddle's y position by 3. The paddle's new y position is 13 while the ball's y position remains 11
* Frame 2: The paddle is now higher than the ball. We decrease the paddle's y position by 3. The paddle's new y position is 10 (same as the original position) while the ball's y position remains 11.
* Frame 3: Repeats the same as frame 1.
* Frame 4: Repeats the same as frame 2.
* Frame N: You're stuck in a loop here until the ball actually moves vertically and only after the ball has moved more than 3 units.

An algorithm that you could potentially use that would fix the above problem is to modify your exact algorithm but also accommodate for when the difference between the paddle's y position and the ball's y position is less than the paddle's vertical speed.

* If the ball's y position is less than 3 units greater or lower than the paddle's y position then set the paddle's y position to be the same as the ball's y position.

---
Tags: c#, xna-4.0, ai, monogame
---


title: Arbitrary text for chat room

text:
# Question
Title: Arbitrary text for chat room
In my game I want to have a chat room where users can enter arbitrary text. I don't think bitmapped fonts will work for me since it must include multilingual characters and emojis (could be wrong about this not working, but my assumption is that bitmapped fonts are really best suited when you have have a small set of characters that the you want to draw text with inside the game). The font rendering should be crisp and clean for high density screens.

I am using libGDX, although a solution doesn't require libGDX specifics, but be aware that this must also run in a webGL context so certain solutions may not apply.

How is arbitrary user text like this typically implemented?

# Answer
You need to check that with your game, wherever or not this is a viable solution.

Our game supports 26 languages including Chinese and Japanese. We use bitmaped font generated from Arial, cos it has all the codepages/characters and is easy to read.

Tricks we used to keep the RAM usage at bay:

* Alpha8 texture
* Single font-size
* Bin-packing into atlases
* On/Off menu option to load Chinese characters range, since 97% of our player base is not from China region.
> 1 votes

---
Tags: fonts, text
---


# Question
Title: Upload Games to Steam without Greenlight?
I've been working on a little game, (which is **nowhere** near completion) and wanted to know, that when I'm finished, if I would be able to release it onto Steam without having to get it Greenlit.

The reason why this is, is that I already payed for tools and editors for **making** my game, and don't want to have to pay another $100 in order to release my game.

Is this possible?

# Answer
> 18 votes
No

Quoting Steam's description of the Greenlight process:

> **Who should submit their games to Steam Greenlight? Is there another way to submit my game to Steam?**
>
> Steam Greenlight has replaced our previous submission process. Any developer or publisher who is new to Steam and interested in submitting their game to the platform should submit their game through Steam Greenlight.

The idea behind Greenlight is to do an effort to prevent very low quality games into Steam, and let in only games that users are genuinely interested in (whether or not it succeeds at it is another discussion).

In my experience, getting a game through Greenlight is **hard**. There are so many games with so many interesting concepts, and so many games with much larger teams and budgets, that it is very difficult to gain enough traction to get released.

In addition, *making* a game is **very hard**. Just like anything in life, making good games takes practice, and I would say it would take at minimum 4 or 5 completed games to actually start making games that people like, and therefore get voted on greenlight.

Don't despair though, Steam is not the only way to get your game known. Focus on making your game, focus on *finishing* the game, show it to other people, make a blog about it, sell it (or give it away) on your site, and before you know it, you will have a few games under your belt, hundreds of loyal followers, and enough traction so the next game you make will actually make it on steam.

---
Tags: game-maker, steam
---


# Question
Title: Balancing Attack to Defense in a text based RPG
I understand that there is no correct or incorrect way of doing this, and its all down to a matter of trial and error in terms of perfecting the system.

What I am after is some advice or even get thoughts on how others have tackled a situation like this.

Right now I have a very basic attack formula

```
$attackPower = $baseAttack * 4;
$percent = $attackPower / 100;
$percent1 = $percent * 10; // Gets 10% of the users attack power

```

Using the above code I then use rand to work out a users attack power, so it varies rather than a single number

```
$power = rand($attackPower - $percent1, $attackPower + $percent1)

```

So that's the users attack power calculated.

However if I used the same formula to calculate the opponents defense, and then calculated the Attack minus Defense equals the damage

```
$totalDamage = $power - $defense;

```

This may sometimes result in a negative value (especially if the opponent has a considerably higher defense stat to the users attack)

Above I have used

```
$attackPower = $baseAttack * 4;

```

For calculating the defense would this be efficient?

```
$defensePower = $baseDefense * 2; // Could have this set to rand? 1 - 3??

```

Is there anything that could be changed to balance the stats out a bit more? Could there be a much simpler formula?

# Answer
## Handling negative values

There are ways to handle negative values aside from *healing* the high-defense enemy with your sword strike (which is weird).

You could introduce a **block** mechanic, where if `target defense > attack power`, the damage is nullified.

But this is imbalanced. This might mean you might encounter an opponent who you will never hit. Of course you don't want that.

## Rethinking defense

1. Your attack power *fluctuates*, which is understandable. Sometimes you get a good strike in (up to `10%` more damage), sometimes you don't (up to `10%` less). You could apply the the same mechanic to defense.
2. Instead of defense being **additive**, which might lead to an enemy never ever being damaged, you can make defense **multiplicative**. Instead of blocking of **N flat damage**, you can shave off **X% of the damage as a whole**. The increased complexity to this is that you either have to set a min and max defense reachable, up to a possible 99% damage reduction, or let defense scale from `1 to infinity` but as defense approaches infinity, the damage reduction increase should lessen.

Think of it like this graph :

Where X = Defense and Y = Damage Reduction
> 2 votes

# Answer
Why not use an IF statement:

```
IF ($power > $defence) {
 $totalDamage = $power - $defence;
} else {
 $totalDamage = 0;
}

```
> 0 votes

---
Tags: rpg, php, mathematics
---


title: AI movement in 2D

text:
# Question
Title: AI movement in 2D
I've got a prototype of a game I've been mocking up and found myself struggling to find a solution for AI movement in a 2D tile based game. Here's the issue: The player is free to roam throughout the grid on floats. Enemies are to be able to move in the same manner. I've used simple a\* pathfinding for the enemies to use but unfortunately I can't seem to think of a logical/tested solution for getting my enemies around the map in a fluid manner.

In this situation, how can I achieve fluid / not gridlocked movement?

# Answer
I've had some trouble with this myself. I've never actually found a perfect way to do it, but a\* pathfinding with Jump point search should make it possible. Take a look at this: http://gamedevelopment.tutsplus.com/tutorials/how-to-speed-up-a-pathfinding-with-the-jump-point-search-algorithm--gamedev-5818
> -1 votes

---
Tags: xna, java, 2d, tilemap
---


# Question
Title: Better ways to parse text adventure commands?
Currently I have got a system set up where I split each sentence handed to me into it's baser parts and then compare each word against a list of known words. Once I have the verbs, adjectives and nouns contained in each sentence (ignoring all other words in the sentence) I go left to right in the list and try and create a recognisable command from it. However this doesn't allow for multiple commands in one line.

e.g. get the shiny sword and hit troll.

This would read get, shiny, sword, troll. It would ignore the hit part because currently I've only written the parser to handle one verb per line, but this would not be a recognisable command and would tell the player that it doesn't know what they're asking them.

I think my current system of tokenising the words and parsing them as arguments to an arbitrary action function is simple enough but not very elegant.

So I was just wondering what are some good ways to implement text adventure parsers? Are there any tried and true algorithms or ways to approach it?

# Answer
> 0 votes
I think you are going at this the right way. Always keep in mind the English grammar (predicate, object) with adjective in between. If a second sentence is concatenated with "and" you have to re-run the parser again.

I would implement much more verbs, objects and adjectives than are used in the game. That way you can recognize the sentence structure even if less-common words are used.

Btw. you could implement some sort of "auto-correction", e.g. "I don't see 'sword', did you maybe mean 'swan'?" or "I can't 'kick troll', did you maybe mean 'kill troll'?" :D

# Answer
> 0 votes
I have one primary answer to your question, but first a few thoughts:

* There seem to be two forces you have to balance between with commands; helping a new user by supporting more natural and less idiomatic syntax, and helping minimize growing frustration with long/expressive syntax.
* Prepositions can be really useful, because you can have a short list of prepositions that are relatively stable and useful when it comes to chunking actions into smaller parts that do something recognizable and then figuring out what nouns they're referring to. At, from, in, into, to, and with alone are a good start, while a number of the locational prepositions (above, below, between, besides, through etc.) may be worth looking for if you have any commands that need this sort of detail.
* Be aware that letting the user execute multiple logical commands in a statement introduces a lot of ambiguity due to everything we infer from this proximity that your parser will have trouble resolving. Is `get the shiny sword and hit troll` to be expanded as `pick up the shiny sword and put it in my inventory` then `hit the troll with whatever I am already wielding`? or are the commands going to try to infer that the user wanted to hit the troll with the new weapon instead of the old, since they're on the same line?
* Regarding the actual act of parsing, I guess the scale might run from:
    + a large centralized parser which attempts to understand each command without the command itself doing any syntax parsing. This will make it easier to have predictable, well-controlled syntax, avoid re-inventing wheels per command, and is more or less essential for something like sensibly inferring what one command should do based on what another in the same line is doing; it can also make edge-case syntax cumbersome for you, or awkward in the game.
    + a smaller centralized parser that is just trying to figure out where it can hand the command off to for further parsing. The light-weight central parser can give you tons of flexibility in individual commands, but may mean you're re-implementing similar features again and again. It may also mean you're implementing them slightly differently in a way that makes sense for the command but surprises a user.
* Write down a long list of syntax examples you'd *like* to be able to support for a variety of commands. Try to pick a few commands that are similar but not quite logical copies, as well as many that differ much more. Start picking these apart for structural similarities. Try writing both the most expressive and terse versions you can imagine wanting to support. You'll probably notice some heuristics you can use (like where prepositions, verbs, and targets tend to fall) that can help.
* Write a script that feeds this list of commands into your parser and meaningfully communicates the results back to you as a test-case.

Ok--to the point:

Depending on a lot of things like your skill/comfort, how many commands you think you'll have, and how long you plan to work on the game--I would consider writing a small command-syntax-specification format, and parsing this format into rules the command parser itself will use. This is more like an advanced version of the large centralized parser above (especially since you need two parsers--one for your specification format, and one that can apply the rules it generates). For a small number of commands this inevitably won't pay dividends. With something like this you could declare your kill syntax as: `kill <targ:living>( with <weap:weapon>)` and your get syntax as `get <obj:object>( <prep:from|out of> <where:container|room>)` and your parser can walk the statement and give each matcher a chance to ingest part of the command or object to the syntax with a message about what didn't work. If your game doesn't let the player attack peaceful npcs, you might have two commands like: `kill <targ:aggressive>( with <weap:weapon>)` and `talk <prep:to|with> <targ:peaceful>( about <topic:word>)`.

---
Tags: input, text, text-based
---


title: Implement a Vision cone in 3D

text:
# Question
Title: Implement a Vision cone in 3D
I'm looking at how to implement a vision cone for my AI. Everything I look at talks about a forward vector, but in my situation, and I'm not that great with math, I have a vector but it doesn't give any orientation just the 3D point of where the entity is. The entity does have a separate rotation value. When people talk about forward vector are they talking about the rotation vector?

So if I just have a rotation vector and a location vector how can I make a vision cone in 3D from those values with say a variable degree of vision in both "left/right" and "up/down"?

I have some math functions available like ATan2()/Tan(). Not 100% sure how those play into this though.

# Answer
> 2 votes
You need a way to convert that rotation vector into either a Matrix or a Quaternion. Some math librarys have a built in method for doing that. If you choose a Matrix, then assuming you are in a Y-up world, the 3rd row or column (depending on if you are using DirectX or openGL) is a vector representing the direction your entity is looking (call it entityForward or something). This vector is probably already normalized but if not, then normalize it (divide it by it's own length).

If you choose a Quaternion then you must transform your world's forward vector by the quaternion and that will give you the same vector as the 3rd row/col that the matrix did.

Once you have that, you use it to measure the angular difference to any other object you want using the dot product.

```
Vector toOtherObject = otherObjectPosition - entityPosition;
toOtherObject.Normalize();
if(Dot(entityForward, toOtherObject) > 0.707f)//.707 == 90 degrees field of view. 1 == 0 deg, 0 == 180 deg.
{
  //otherObject is in view
}

```

---
Tags: 3d
---


# Question
Title: Validating victory report to PHP leaderboards
I have decided to begin working on some sort of leaderboard server for my PC game.

For starters, I decided to write some PHP scripts to handle it. The script doesn't actually receive a score - it just receives a player ID. Then the server increases their score. When submitting a "victory", the game performs a connection to the server of this form:

```
http://www.example.com/doVictory.php?ID=Joe

```

As you can see, the server just receives the player ID and then it does its own scoring stuff (the score value of a victory changes overtime).

My concern is pretty simple: what if some guy figures this out? They would be able to spam the above address several times and keep increasing their score.

One option:

* Don't accept victories from the same player within a short amount of time.
    + Due to the nature of the game, players can have a victory as fast as within 1 minute. If somebody is having a victory every minute, I would not be able to tell whether they are cheating or just very good.

---

I have found an answer here: https://gamedev.stackexchange.com/a/4185/4779

> * Send a JSON message over plain HTTP (not HTTPS). Include a MD5-hash of all fields plus a magic string.
> * On the server, check the integrity of the message with the same operation.

But as far as I'm concerned, this doesn't quite work with my scenario because I am not really sending a score - just reporting a victory.

# Answer
What you will need to do is replay the entire game on your sever. If you use randomness in your game then store for each player the random seed you send them on your server and then have the server play the game to validate that their moves do indeed lead to a victory. This has the advantage that other types of cheating won't work either. If it's multi-player you can also ask the loser to send a message as well and then make a sanity check to see if the same player keeps losing against the same opponent.

Now let's for example look at a game of chess: As you might know it's easy to represent chess games as strings. If you receive such a string it's fairly trivial to detect any illegal moves and games that didn't end in a win. So you can at least check for a valid game now. If you play against an AI you can also look at what seed the AI used while playing (send this to him from the server and store it or else a player can keep playing against the same AI by messing with the seed-\>keep sending the same message without actually playing). You can now check if the moves the AI made check against the behaviour you would expect it to have given it's current state. If you are smart you even can even tinker with the random generator to be based entirely on the original seed and the moves made so far as this means that you will not have to validate every AI move but can just sample a few of them (and if a player repeatedly sends bad AI moves you can simply ban him).

If you play against another player you can also let him validate the game and check to see if a given player/IP-adress is losing far more then they should.
> 4 votes

# Answer
**EDIT: Just read your JSON link, and this approach is very similar.**

Another option is to hash the information. Send the player ID, the date, and a hashed string representing the data. You can encrypt a bit of data in the string to make it uncrackable.

eg.

```
Name = Joe
Timestamp = 2015-01-15 13:23:44
Your Secret = uniquecode

```

Then you can concatenate into a string, and add a hash.

(e.g. using MD5)..

```
Joe,2015-01-15 13:23:44,uniquecode
=
998156c21a891abcbee2afd1988d6a0c

```

Then send this data to your server...

```
http://www.example.com/doVictory.php?ID=Joe&Timestamp=2015-01-15%2013%3A23%3A44&Hash=998156c21a891abcbee2afd1988d6a0c

```

You can then recreate the string on the server from the 'ID' and 'Timestamp' parameters, and your 'secret key'. You can then recreate the hash, and check if it's the same as the one supplied. Providing the timestamp also means you can check when the information was sent, and act accordingly.

This way, you can choose to add to the score if the timestamp is within the last minute. The hash should also be un-recreatable as the user doesn't know your secret key.
> 1 votes

# Answer
Just change the method, from GET to POST. That will send the needed information but it will not be visible in the link.
> -1 votes

---
Tags: php, leaderboards
---


# Question
Title: In AS3, is it necessary to remove the children from a parent who is also being removed?
My point is this:

```
addChild(parentMC);
parentMC.addChild(child1);
parentMC.addChild(child2);

```

If I want to then remove `parentMC` from the current container, is it necessary to also remove `child1` and `child2` from `parentMC` in order to properly clean-up? Or is that handled automatically through removing `parentMC`?

# Answer
Once you remove `parentMC` and set it as `null`, garbage collection will take care of its children.

When you remove the parent from the Flash display list hierarchy its children won't exist in the display list. You could remove children before you remove the parent from the display list, but that isn't necessary unless you wish to move the child to another container. But when you call `addChild` on the second parent (`parentMC2.addChild(child1)`) it will be automatically removed from `parentMC`. Assuming that `parentMC` does not hold any variables linking to the `child1` instance, you are safe.

If your children listening to `Event.REMOVED_FROM_STAGE` and you would like to make a dispose function for your parent you could simply remove all the children from the parent one by one:

```
while( parent.numChildren > 0 ) parent.removeChildAt( 0 );

```

and then execute your dispose code after all the children have been removed. But yet again unless it's absolutely necessary for your program logic it would be a waste of time
> 1 votes

---
Tags: actionscript-3
---


title: Using box2d with starling

text:
# Question
Title: Using box2d with starling
In my game I have a **Main** class in which i am initializing starling framework by passing **Game** class like below

```
myStraling = new Starling(Game , stage);

```

In the game class I have Instances of **Welcome** class and **InGame** class these two classes extends **starling.display.Sprite**.I have a **PhysicsHandling** class seperately. Now i want to make instance of **PhysicsHandling** class in the InGame class. The physics handling class does not extend any class because it only does calculations. I have made its some variables public to position starling sprites accordingly.

My question is. Is it the right way to integrate physics in starling **Performance wise** .I mean is there a better way to do that

# Answer
Should be alright if you are not using too complex shapes or too much bodies at once. If so you could reduce the `Box2D` frame rate ( lets say the game runs at 60 fps so you can call `Box2D` update on every second frame and double the `ms` ) or play around with `velocityIterations` and `positionIterations` to maximize performance. I actually used this trick in a game that I'm currently working on ( `Starling` \+ `Box2D` ) and it increased the frame rate from 30~40 fps to fluid 60 fps :)

I know that physicseditor allows you to trace polygon points from images but i personally found the result data too complex for my game.
> 0 votes

---
Tags: physics, box2d, actionscript-3, starling
---


title: Multi texture obj files?

text:
# Question
Title: Multi texture obj files?
Im downloading some free 3d models off the internet to test things in my game. When I download the package, it gives me a bunch of texture files and the obj model. What I dont understand is what I do with those textures? Are they used as source image files within the object? If so how can I export the uv map of the model with all these textures on it? Ive been trying to get a working example of this and havent been able to. Can someone guide me in the right direction? I edit my files with blender, and realize this question is a little bit off topic, but im lost!

EDIT:

Example of the textures I am using now:

# Answer
An `.obj` model file may come with a companion file with the extension `.mtl`. Such a file is a material library that contains entries mapping from a material name to properties, including texture filenames to use for things like diffuse and specular.

In your obj-file, there are `mtllib a.mtl` directives to indicate the material library to use, and `usemtl aaaa` directives to select which material in the library that applies to the next occurence of the directive, or the end of the file.

When you load a file, you typically split it up by geometries (which correspond to submeshes) and by material, so that each thing you draw has a single material. From there, it's simple to set the textures indicated and draw.

From an authoring standpoint, an entry in the material library will correspond to a separate material in the editor, and each part using a material is likely a separate submesh or mesh.
> 3 votes

---
Tags: textures, blender, uv-mapping
---