title: Why is shadow mapping the standard?

text:
# Question
Title: Why is shadow mapping the standard?
Though I am a programmer by trade, I have barely touched game development at all. I've had this question for some time, and now that I'm looking into game development I thought it would be a good time get ask.

Why does shadow mapping seem to be the exclusive way games use to make shadows? To be blunt, it looks terrible. Even modern games with shadow settings maxed have jagged block-y shadows that are very distracting.

Doom 3, made 11 years ago used shadow volumes that looked much better than any shadow map implementation I have ever seen, that includes AAA games released the same week this question is being posted. Third party mods for Doom 3 even softened the edges of the shadows, making them even more visually impressive.

Is there some kind of technical problems or limitations with implementing things like shadow volumes? Are shadow maps just so easy to implement that devs don't even consider anything else?

The only information I've been able to find on the subject is that the polygons that make up the the volumes can be quite large, becoming more demanding. Perhaps shadow volumes have much higher system requirements, but if that is the case how did they get away with using them in 2004?

This question isn't specific to shadow mapping vs shadow volumes, They are simply the only 2 I've seen used in full products and I just haven't been able to find much information on any other techniques.

# Answer
> 53 votes
Shadow mapping and stencil shadows (shadow volumes) are definitely the big two, as you've mentioned, so I'll stick to comparing the two. And since you've pointed out the most obvious shortcomings of shadow mapping and advantages of stencil shadows, I'll do the opposite.

**Stencil shadow shortcomings**

1. Shadows match the shape of the casting mesh. This is *very limiting*, and is probably the **biggest technical reason not to use stencil shadows**. Tree leaves, bushes, wire fences, rips in cloth, and other common shadow-casting game elements use alpha transparency to define the shape of the object. But since stencil shadows match the mesh and not strictly the visible parts of the texture on the mesh, they can't be used for such objects. For example, a cluster of leaves in a tree will usually be a texture of a cluster of leaves on a quad. Stencil shadows would only be able to show the shadow of the quad itself (and it'll have problems with that since a quad isn't a closed mesh, but this is a minor detail I'll skip over for this answer, as it's generally able to be worked around).
2. Can't do accurate soft shadows. You've pointed out that Doom 3 has been modded to allow soft shadows. This version here, at least, uses shadow mapping for soft shadows. I've also seen screen-space techniques for softening hard shadows, but they're prone to all sorts of problems.
3. Can't do shadows on transparent objects. There are workarounds for this -- rendering shadows for transparent objects in separate passes and compositing them afterwards. But besides difficult workarounds, the nature of stencil shadows is such that each pixel on-screen is *either* in shadow or not. This is also the reason for no soft shadows as mentioned before.
4. The generally preferred and most robust implementation of stencil shadows, often called "Carmack's Reverse", is actually patented, as Angew pointed out in the comments. (Not patented by Carmack; he had to work around it for the open source version of Doom 3). As person27 notes, this patent has since expired.

**In favour of shadow mapping**

Apart from being without the limitations I listed specifically for stencil shadows, there are a few extra advantages to shadow mapping:

1. Scalability. While shadow mapping is neither cheap nor perfect (*ed: but stencil shadows aren't cheap either*), it's relatively easy to trade fidelity for performance by changing the resolution of the shadow maps or changing the filtering for shadows. This makes it relatively easy to tune the shadow quality / performance for different systems. As you've pointed out, this often isn't perfect, but a lot of this will depend on the perceptiveness of the player, and the resolution they're playing at (higher screen resolution will make it easier to see the blockiness of shadow mapping). Some AAA games (like Fracture) do an amazing job with shadow mapping just by picking the right filters and tuning the right knobs, while many just slap it in there and say "good enough".
2. Cookies (textured shadows): Add the texture of a spotlight, or stained glass, and you can emulate all sorts of real-world light sources. This is doable with stencil shadows, too, by the way, but involves almost all the setup of shadow mapping anyway (the same projection matrices used for projecting the light's texture on objects are the ones used for shadow mapping).
3. Transparent shadows: Most games don't attempt much with this, but transparent shadows are possible with shadow mapping. I don't just mean alpha cutouts like trees and fences like I mentioned before, but I mean partially transparent shadows, like from smoke and dust.

Neither of those lists are exhaustive.

So while your observations about shadow mapping and stencil shadows are correct, the shortcomings of stencil shadows are show-stoppers for a lot of desirable effects, and shadow mapping has a few advantages of its own.

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


# Question
Title: Why are my Mecanim animation curves not staying within the entered range?
I have an in-place animation that I added curves to (In the rigged FBX which has the animation). I created 2 float parameters in the relevant controller with the same names as the curves in the animation clip.

Now, when I get the value of the float using `animator.GetFloat()`, the values I get are not in the value range I entered in the curves. My range is between 0.0f and `4.0f` but what I get is approximately `-0.6f` to `0.03f`. Why is this? From what I could gather from other threads, there is some blending going on with some other curves. What is this blending? And if there is some blending happening, how can I remove that?

I'm using Unity 5.1.1.

# Answer
EDIT

Ok so after messing around a lot I figured that this behaviour happens only when you evaluate the curve in OnAnimatorMove () function (with Animator.GetFloat). If I do the same in say FixedUpdate then the values received are correct. Don't know why this is and FixedUpdate is not the place where I would want to do this so continuing to further explore this. A bit irritated with the lack of documentation on this to be honest.

---

I have now posted a thread on Unity support forums and followed up on Issues tracker with an issue that pretty much has the same content as my question.

Unity Issues Tracker has closed the issue saying that this behaviour by design. That seems to make some sense. However, I am still puzzled by this because we don't know (I don't know) exactly what the design is. As it is, it seems that these values are coming out of nowhere. I have requested for some documentation on how this blending actually happens. If someone else here has a clue then please do let me know.
> 1 votes

---
Tags: animation, curves, mecanim
---


# Question
Title: Why is my Box2D Body only colliding with one type of Object after a new level has been built?
So developing for an android mobile game, using Android Studio and developing for the API 17, with Box2D implemented.

**FIRST LEVEL**

For some reason, one the first level everything is running okay:

When I complete the first level - still good:

**SECOND LEVEL**

Here is when the problem occurs, on the second level, as you can see the first player square (the upper, smaller square) to the left is not disappearing along with the target square (the bottom, bigger square):

Here is when the second player square has gone through on that very same second level, and it has disappeared as it should:

My process for transitioning between levels (this function is in my level class):

```
public void newLevel()
{
    // Clear the current level.
    levelGenerator.clearLevel();

    // Increment the current level number.
    levelNumber++;

    // Decide what levels I want here.
    if(levelNumber == 2)
    {
        // Generate a new level.
        levelGenerator = new LevelGenerator
        (
                context,        // Game context.
                world,          // Box2D world.
                background,     // Game background, relative layout in this case.
                screenWidth,    // The screen width of the device currently being used.
                screenHeight,   // The screen height of the device currently being used.
                3,              // The number of columns.
                7,              // The maximum number of platforms (both moveable and breakable) per column.
                1               // The number of enemies.
        );
    }

    // Builds the new level.
    levelGenerator.buildLevel();

    // Updates the UI thread to add all of the new level objects to the screen.
    game.render();
}

```

**Clear The Current Level**

* Remove any textures/colours (set the alpha to 0 for colours) from the level objects.
* Destroy the body of each object in the level objects vector. (A vector which stores animated sprites.).
* Finally, remove all the elements from the level objects vector.

```
public void clearLevel()
{
    // If there are objects in the vector.
    if(!objects.isEmpty())
    {
        // Iterate through each of the objects in the level.
        for(AnimatedSprite object : getObjects())
        {
            // If there is an object.
            if(object != null)
            {
                // If the object is an enemy.
                if((object.getID() == ObjectID.STATICENEMY)
                    || (object.getID() == ObjectID.DYNAMICENEMY))
                {
                    // Take care of the bullets separately.
                    // Enemy bullets are only in the enemy class and are not part of the level objects vector.
                    Enemy enemy = (Enemy) object.body.getUserData();
                    enemy.enemyBullet.setColour(0, 0, 0, 0);
                    enemy.enemyBullet.destroyBody();
                }

                // Removing all of the sprites from the screen.
                // If the object does not have a texture, but is using standard colours.
                if(object.colour != null)
                {
                    // Set the alpha value to 0 and RGB to 0.
                    object.setColour(0, 0, 0, 0);
                }
                // Otherwise, the object has a texture.
                else if(object.image != null)
                {
                    // Set the texture to be transparent.
                    object.removeTexture();
                }

                // If the object still has a body.
                if(object.body != null)
                {

                    //
                    // Problem may be here???
                    // Screenshot may be showing a body in the way of the target square?
                    //

                    // Destroy the body of the object.
                    object.destroyBody();
                }
            }
        }

        // Remove all of the objects from the list.
        objects.removeAllElements();
    }
}

```

Here is how I am destroying the bodies (in my animated sprite class):

```
public void destroyBody() { body.destroyShape(body.getShapeList()); }

```

**Increment The Level Number**

* Will be random levels, but for testing/debugging purposes, using set levels.

**Check The Level Number**

* Generate the new level using my level generator class.

**Put The Level Together And Populate The Level Objects Vector**

* This will add in all of the new level objects, using the values specified in the constructor for level generation.

When I checked the size of the vector after the clear function, it was all as expected, and the same for when a new level was created.

When debugging through the second level and monitoring collisions, I use contact listeners from Box2D, I did find that the first player square was always colliding with a column, I do not know why, here is the log entry:

First player square:

08-30 10:50:46.636 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 6 08-30 10:50:46.636 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 6 08-30 10:50:46.656 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 6 08-30 10:50:46.656 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 6 08-30 10:50:46.785 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 6 08-30 10:50:46.785 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 6

Second player square:

08-30 10:50:46.935 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5 08-30 10:50:46.935 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5 08-30 10:50:47.226 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5 08-30 10:50:47.226 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5 08-30 10:50:47.406 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5 08-30 10:50:47.416 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5 08-30 10:50:47.566 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5 08-30 10:50:47.646 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5 08-30 10:50:47.696 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5 08-30 10:50:47.696 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5 08-30 10:50:47.746 15664-15770/com.example.app.jason.jasons\_app D/TKT﹕ Player colliding with 5

```
public class ObjectID
{
    //
    // Other ID tags.
    //

    // The ID's from the log entry.
    public static final int MOVEABLEPLATFORM = 5;
    public static final int COLUMN = 6;
}

```

Does anyone have an idea why the first player square, when I create a new level, ONLY registers collisions with my columns? I have no idea and I would really appreciate any help. If you need any further clarification please comment/message me.

Thank you.

**\[EDIT\]**

So I have fixed my initial problem mentioned above! For anyone wondering it was to do with how I am deleting/removing bodies from the world.

A body, or multiple bodies were not being fully removed correctly, and were carrying over to the next level.

My answer to the problem is below.

# Answer
The problem was a body from the previous level seemed to be left behind for some reason in that spot in the screenshot from level two.

To correctly and definitely remove the bodies, I now do this:

```
// Loop through all of the current bodies in the world.
for(int bodyNumber = 0; bodyNumber < world.getBodyCount(); bodyNumber++)
{
    // If the body still has a shape list.
    // Later versions of Box2D I think this is replaced with fixtures.
    if(world.getBodyList().getShapeList() != null)
    {
        // Destroy the shape list of the body.
        // Again, replaced with fixtures in later versions.
        world.getBodyList().destroyShape(world.getBodyList().getShapeList());
    }

    // Get the next body in the world body list.
    world.getBodyList().getNext();
}

```

The player can advance the level, and the first player square is no longer getting stuck!
> 1 votes

---
Tags: android, box2d, jbox2d, android-studio
---


title: Shadertoy getting help moving to glsl

text:
# Question
Title: Shadertoy getting help moving to glsl
I spent some time writing a shader on shadertoy but now, when I try to translate my code to opengl I don't know how to calculate the `uv` that they describe as like this:

```
vec2 uv = fragCoord.xy / iResolution.xy;

```

How can I do that in a typical opengl 330 core fragment shader?

# Answer
You have two options:

1. Use `gl_FragCoord` and pass a uniform variable for `iResolution`. Everything else will work exactly like in your ShaderToy code.
2. Pass texture coordinates from the vertex shader: Every vertex shader needs to output `gl_Position` and `gl_Position.xy / gl_Position.w` is defined to be a pair of screen coordinates ranging from -1 to 1. That means that you can easily compute "screen texture coordinates" from that in your vertex shader and pass it to the fragment shader like this:
`uv = (gl_Position.xy / gl_Position.w) * 0.5 + vec2(0.5)`.
Note that `gl_Position.w` is 1 for the typical ShaderToy scenario, since you likely want to render a flat, screen filling triangle/quad that does not have any "perspective properties".

If you do not need the resolution somewhere else, I would recommend the second solution: Both solutions pass data per fragment, but only the first solution need to pass a uniform (which requires some more CPU side code).
> 3 votes

---
Tags: opengl, fragment-shader
---


title: Ball oblique impact physic in Java?

text:
# Question
Title: Ball oblique impact physic in Java?
I know **Q3 + Q4 = 90**

I searched internet and many physic topics, but not found how to calculate this values in Java?

(I found V3 and V4 but not found Q3 and Q4)

So how can i calculate **V3**, **V4**, **Q3**, **Q4** values after the collision in Java?

# Answer
So, you want the angle of velocity relative to the x-axis? That'd be `atan(V3.y/V3.x)` and `atan(V4.y/V4.x)` for **Q3** and **Q4**, respectively.

Though, since the balls are almost aligned along the y-axis in relation to each other, it looks like maybe you're looking for the angle of V3/V4 relative to the surface at the point of impact, even when that doesn't line up with the x-axis.

In that case, you need the **normal** of impact (most collision functions will give you this as some of the output, but it's easy for spheres/circles anyway -- just normalise `ball1.xy - ball2.xy`). Anyway, you can use that normal and **V3** to calculate **Q3** like so:

`acos(DotProduct(normal, V3.Normalised()))`.

It'll vary a little depending on what libraries you're using, but basically: the dot product of two normalised vectors (that is, vectors with a magnitude of **1**) will be the cos of the angle between the vectors. Apply the inverse cos function (**acos**) and you get the angle between them.

For **Q4**, replace "V3" with "V4".
> 1 votes

# Answer
It's much simpler than you think:

Just use the "relative velocity" to calculate the impulse

```
relVel = vB - vA;

```

Then, use it to project against the normal to find the impulse.

```
normal = (posB-posA) / Length(posB-posA);

coefficient_of_restituition = 0; // (100% energy lost)
coefficient_of_restituition = 1; // (0% energy lost)

impulse = -(1 + coefficient_of_restituition) * dot(relVel, Normal) / (invMassA + invMassB);

```
> 1 votes

# Answer
maby this can help you http://en.wikipedia.org/wiki/Coefficient\_of\_restitution there is a break down of the entire problem
> -1 votes

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


# Question
Title: How can I edit a game level using jmonkeyengine?
I liked the quake level that comes with jME3. But if I want to edit that level, make it bigger or so, what editor or programming can I use to edit the level? If I open the zip file it's a bunch of texture files that I don't know how to combine to a level. Was the level constructed using some editor like Blender or similar?

# Answer
You can create q3 levels with GTKRadiant. GTKRadiant saves levels as .map which stores the geoemtry as planes in a CSG fashion.
> 0 votes

---
Tags: level-design, jmonkeyengine
---


# Question
Title: The Pixel Shader unit expects a Sampler configured for default filtering to be set at Slot 0 [...]
I don't understand this error. The full output being :

> The Pixel Shader unit expects a Sampler configured for default filtering to be set at Slot 0, but the sampler bound at this slot is configured for comparison filtering.

Here is how I create the sampler state.

```
// Skybox sampler description
D3D11_SAMPLER_DESC skyboxSamplerDesc;
ZeroMemory(&skyboxSamplerDesc, sizeof(D3D11_SAMPLER_DESC));
skyboxSamplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
skyboxSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
skyboxSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
skyboxSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
skyboxSamplerDesc.MipLODBias = 0.0f;
skyboxSamplerDesc.MaxAnisotropy = 16;
skyboxSamplerDesc.ComparisonFunc = D3D11_COMPARISON_EQUAL;
skyboxSamplerDesc.MinLOD = 0;
skyboxSamplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

// Create the skybox texture sampler state
hr = g_d3dDevice->CreateSamplerState(&skyboxSamplerDesc, &g_SkyboxSamplerState);
if (FAILED(hr)) return false;

```

The bindings.

```
ID3D11SamplerState* samplerStates[2];
samplerStates[0] = g_SkyboxSamplerState;
samplerStates[1] = g_PixelDepthSamplerState;
g_d3dDeviceContext->PSSetSamplers(0, 2, samplerStates);

```

HLSL side.

```
SamplerState sbSamplerState : register (s0) {
    Filter = MIN_MAG_LINEAR_MIP_POINT;
    AddressU = CLAMP;
    AddressV = CLAMP;
    AddressW = CLAMP;
    ComparisonFunc = EQUAL;
};

```

# Answer
If your C++ code should specify the actual filtering state, your HLSL shader should not specify it, since everything written there will overwrite it (which is a feature of the effect-framework, not HLSL itself). This might be a bit weird, but works normally just fine. However, you are using a comparison filter on the C++ side (in your case `D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT`) and not on the HLSL side. Since everything should work without the effect-framework (the part that specifies the state within the shader), you are not allowed to set the comparision filter in the C++ code, since the HLSL code expects a default (non-comparision) sampler state type. So you need SamplerComparisonState instead:

```
SamplerComparisonState sbSamplerState : register (s0);

```

If you want, you can still keep the filtering state in the shader, but in any case the sampler state type (comparison or not) needs to be the same, both in the HLSL code and in the C++ code.
> 4 votes

---
Tags: directx11, hlsl, sampler-state
---


# Question
Title: Problem to change window view dragging the mouse
I'm having a bad time trying to change the window view by dragging the mouse. I can precisely do that with the method:

```
void PlayScreen::MenuView(sf::RenderWindow& window)
{
    while (sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
        old_mouse_position = new_mouse_position;
        new_mouse_position = sf::Mouse::getPosition(window);

        game_view.move(new_mouse_position.x - old_mouse_position.x, new_mouse_position.y - old_mouse_position.y);
    }
}

```

The problem is that the view is updated, (when I release the mouse, it's drawn in the correct position) but it's not drawn as I move the mouse. My gameLoop only draw after all the updates are made, and I was trying to keep the logic that way. Everytihng works fine if I draw inside MenuView while.

my Gameloop is quite simple:

```
while (main_window.isOpen())
{
    while (main_window.pollEvent(event))
    {
        GameOptions(event);
        DrawGame();
    }
}

```

Inside the GameOptions(event) there is a:

```
if (event.type == sf::Event::MouseButtonPressed)
{
    new_mouse_position = sf::Mouse::getPosition(window);
    if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
        MenuView(window);
    }
    break;
}

```

I've tried without the while inside the MenuView, but it just don't work.

# Answer
> 1 votes
* The event MouseButtonPressed is sent only once (that's how SFML works), so when you check this statement : `if (event.type == sf::Event::MouseButtonPressed)` it is only true when you click, it won't be true again unless you click again

Instead of doing this `if (event.type == sf::Event::MouseButtonPressed)`

You could do this `if (sf::Mouse::isButtonPressed(sf::Mouse::Left))`

or set a bool to true like this:

in GameOption(event)

```
if (event.type == sf::Event::MouseButtonPressed)
    buttonPressed = true;
else if (event.type == sf::Event::MouseButtonReleased)
    buttonPressed = false;
if (buttonPressed == true)
{
    MenuView(window);
}

```
* The while in MenuView will stop your game from rendering for all the time your Left mouse button is pressed, so get rid of this while. MenuView should only change the view position once.

Hope it solves your problem, if not I'll update my answer (I can't comment yet)

---
Tags: sfml, view
---


# Question
Title: Solitaire Game: Transferring Cards Design in C++
So, I'm working on a Solitaire game. I already created a the classes: Card, Pile, Stock. Each work as expected on it's own. My question is: What possible design for managing moving card(s) between the 7 piles, the stock (the waste) and the foundations? I want a possible design that is suitable for managing these game objects so they can work together smoothly. Any help is greatly appreciated.

# Answer
This is how I solved the problem. Actually, I was inspired by the Observer pattern. I created a class `TransferringSystem`. It contains references to each pile, foundation, and the stock. As for the behavior, it contains three function overloads of `update` function, one for `Pile`, one for `Stock` and one for `Foundation`. Each of the three classes will register itself to the system. When an entity is released, it will tell the system that it was released by passing `this` to it. The system will be responsible for checking if a selected entity intersects with other entities and handle it appropriately.
> 0 votes

# Answer
The most straight forward and simplest way is a pretty good design: have a data type that is a list of cards (could be a vector, linked list, or other things) and move cards between card groups as gameplay dictates. Unless you have a reason to go in a different direction, simple is good and will make for less bugs. Even if you need super high performance for your card game (you shouldn't) a linked list will be plenty fast (:
> 0 votes

---
Tags: c++, architecture
---


# Question
Title: Create a normal map using a script? Unity
I don't have a software that can create normal maps from an image so I usually make a grayscale image and then let unity make the normal map from that image. But I can't save the image to use for later, Instead I have to convert it to a normal map every time I use it. So how would I make a normal map from a greyscale using a script? i prefer c# but js works fine.

# Answer
Hey this function can return a normal map , form an image. It stores the exported image in the Editor Assets folder. You can also specify the strength to increase the bumpiness of the map :)

```
private Texture2D NormalMap(Texture2D source,float strength)
{
        strength=Mathf.Clamp(strength,0.0F,1.0F);

        Texture2D normalTexture;
        float xLeft;
        float xRight;
        float yUp;
        float yDown;
        float yDelta;
        float xDelta;

        normalTexture = new Texture2D (source.width, source.height, TextureFormat.ARGB32, true);

        for (int y=0; y<normalTexture.height; y++)
        {
            for (int x=0; x<normalTexture.width; x++)
            {
                xLeft = source.GetPixel(x-1,y).grayscale*strength;
                xRight = source.GetPixel(x+1,y).grayscale*strength;
                yUp = source.GetPixel(x,y-1).grayscale*strength;
                yDown = source.GetPixel(x,y+1).grayscale*strength;
                xDelta = ((xLeft-xRight)+1)*0.5f;
                yDelta = ((yUp-yDown)+1)*0.5f;
                normalTexture.SetPixel(x,y,new Color(xDelta,yDelta,1.0f,yDelta));
            }
        }
        normalTexture.Apply();

        //Code for exporting the image to assets folder
        System.IO.File.WriteAllBytes( "Assets/NormalMap.png", normalTexture.EncodeToPNG());

        return normalTexture;
}

```

If you don't see the exported image immediately, then don't panic. Just minimize the editor and open it again and the image will be there.

If you face any error such as "the image is not readable" , then make sure you change the import settings of the image

* Choose texture type as "Advanced"
* Check "Read / Write Enable option"
* Apply the changes
> 2 votes

---
Tags: unity, normal-mapping
---


# Question
Title: Why is libGDX's HexagonalTiledMapRenderer adding extra space?
Why are there large spaces between the hexes when rendered by HexagonalTiledMapRenderer? The tiles ARE black bordered, but that doesn't account for all the extra space. I was also able to get them much closer together by modifying the .tmx file that Tiled produced.

Picture showing the tiles fitting tightly together. The left and bottom borders are filled out with orange tiles.

You can see the map properties as tile width 156, tile height 96, side length 0, staggered axis x, stagggered index odd, and tile render order right down:

Picture showing the tiles as rendered in game by HexagonalTiledMapRenderer:

Picture showing what the in game rendering looks like if I edit the tag's tilewidth attribute to be 100 instead of 166:

I imported the below image into Tiles using tile width 156, height 96, margin 0, spacing 0, and transparent color white. I got it from one of the libGDX tests:

test3.tmx as generated by Tiled:

```
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" orientation="hexagonal" renderorder="right-down" width="25" height="25" tilewidth="166" tileheight="96" hexsidelength="0" staggeraxis="x" staggerindex="odd" nextobjectid="1">
 <tileset firstgid="1" name="hexes" tilewidth="60" tileheight="52" tilecount="16">
  <image source="hexes.png" trans="ffffff" width="256" height="256"/>
 </tileset>
 <tileset firstgid="17" name="hexes" tilewidth="82" tileheight="52" tilecount="12">
  <image source="hexes.png" trans="ffffff" width="256" height="256"/>
 </tileset>
 <tileset firstgid="29" name="1" tilewidth="112" tileheight="97" tilecount="4">
  <image source="hexes.png" trans="ffffff" width="256" height="256"/>
 </tileset>
 <layer name="Tile Layer 1" width="25" height="25">
  <data encoding="base64" compression="zlib">
   eJztk0sKwDAIRL2Iev9btguFwSbNT7ooDgzSSObZhBCVSvnSYhTjBwy5zeYvGPrinnqztRir+aN/V+uL2ddGM89kRwYZQ2Ed6052j+HOyI4MPCvncfCukIHfHHon7whzst9Ga24JPdQKW+h5t76fG/0TK9RM4/l4vQDIeBDE
  </data>
 </layer>
</map>

```

Finally, here's the source code of the class doing the rendering:

```
package com.mpinnegar.zoguequest.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.maps.MapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.HexagonalTiledMapRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.mpinnegar.zoguequest.ZogueQuest;

public class OverWorld extends AbstractScreen {
    private final int overWorldGameWidth = 100;
    private final int overWorldGameHeight = 100;
    private Vector3 userClickCoordinates = new Vector3();
    private final OrthographicCamera camera = new OrthographicCamera(overWorldGameWidth, overWorldGameHeight);
    private Vector2 currentPosition = new Vector2();
    private Vector2 destinationPosition = new Vector2(100, 100);
    private MapRenderer mapRenderer = new HexagonalTiledMapRenderer(new TmxMapLoader().load("test3.tmx"), .2f);

    public OverWorld(ZogueQuest zogueQuest, AssetManager assetManager) {
        super(zogueQuest, assetManager);
    }

    @Override
    public void render(float delta) {
        Color markerColor = Color.WHITE;
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        if (!currentPosition.epsilonEquals(destinationPosition, .5f)) {
            Vector2 directionToDestination = destinationPosition.cpy().sub(currentPosition).nor();
            currentPosition.add(directionToDestination.scl(50 * delta));
            currentPosition.y = MathUtils.clamp(currentPosition.y, 0, overWorldGameHeight);
            currentPosition.x = MathUtils.clamp(currentPosition.x, 0, overWorldGameWidth);
        } else {
            markerColor = Color.BLUE;
        }

        camera.update();

        mapRenderer.setView(camera);
        mapRenderer.render();

        ShapeRenderer shapeRenderer = new ShapeRenderer();
        shapeRenderer.setProjectionMatrix(camera.combined);
        shapeRenderer.begin(ShapeType.Filled);
        shapeRenderer.setColor(markerColor);
        shapeRenderer.circle(currentPosition.x, currentPosition.y, 2);
        shapeRenderer.end();

        shapeRenderer.begin(ShapeType.Line);
        shapeRenderer.setColor(Color.GREEN);
        shapeRenderer.rect(0, 0, overWorldGameWidth, overWorldGameHeight);
        shapeRenderer.end();
    }

    @Override
    public void show() {
        super.show();
        Gdx.input.setInputProcessor(new InputProcessor() {
            @Override
            public boolean keyDown(int keycode) {
                return false;
            }

            @Override
            public boolean keyUp(int keycode) {
                return false;
            }

            @Override
            public boolean keyTyped(char character) {
                return false;
            }

            @Override
            public boolean touchDown(int screenX, int screenY, int pointer, int button) {
                userClickCoordinates.set(screenX, screenY, 0);
                userClickCoordinates = camera.unproject(userClickCoordinates);
                destinationPosition.set(userClickCoordinates.x, userClickCoordinates.y);
                return true;
            }

            @Override
            public boolean touchUp(int screenX, int screenY, int pointer, int button) {
                return false;
            }

            @Override
            public boolean touchDragged(int screenX, int screenY, int pointer) {
                return false;
            }

            @Override
            public boolean mouseMoved(int screenX, int screenY) {
                return false;
            }

            @Override
            public boolean scrolled(int amount) {
                return false;
            }
        });
    }

    @Override
    public void resize(int width, int height) {
        super.resize(width, height);
        camera.viewportWidth = overWorldGameWidth * aspectRatio(width, height);
        camera.viewportHeight = overWorldGameHeight;
        camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
    }
}

```

# Answer
Try turning on the grid in Tiled (Ctrl+G) and adjusting your "Tile Side Length" in the Map Properties so that the grid matches correctly with your tiles. It may fix the libgdx rendering issue, and would improve the mouse picking in Tiled a little.

I know setting up a hexagonal map (and even an isometric map) is somewhat confusing at the moment. It's definitely something I would like to improve (and of course also something to document in the manual).
> 3 votes

---
Tags: libgdx, tiled, hexagonal-grid
---


title: SSAO, depth buffer linearization (?)

text:
# Question
Title: SSAO, depth buffer linearization (?)
I'm trying to implement SSAO in my application but it doesn't look as it should. I think that the problem is with depth buffer linearization but I tried almost all methods which I found on the Web and each gave me different and wrong results.

---

**Depth buffer**

My application implements deferred rendering. My framebuffer which represents G-Buffer contains GL\_DEPTH\_STENCIL\_ATTACHMENT with texture attached to it.

It's base and internal format is GL\_DEPTH\_STENCIL. Used data type is GL\_UNSIGNED\_INT\_24\_8.

Parameters which I set to this texture are:

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);

```

Here is the content of this buffer drawed on screen:

---

**SSAO**

Here is my SSAO shader:

```
#version 330

uniform sampler2D nrm;
uniform sampler2D depth;
uniform sampler2D noise;

uniform mat4 ProjectionMatrix; // current projection matrix, for linearized depth

//  ssao uniforms:
const int MAX_KERNEL_SIZE = 64;
uniform int kernelSize = 16; // 20
uniform float power = 2.0;
uniform vec3 kernel[MAX_KERNEL_SIZE];  // wasnt here

uniform vec2 texelSize;
out vec4 FragColor;

vec3 decode_normal(vec2 enc){
    vec2 fenc = enc*4-2;
    float f = dot(fenc,fenc);
    float g = sqrt(1-f/4);
    vec3 n;
    n.xy = fenc*g;
    n.z = 1-f/2;
    return n;
}

vec2 CalcTexCoord(){
    return gl_FragCoord.xy*texelSize;
}

vec3 posFromDepth(in vec2 Tex, in float d){ // get eye coordinate from depth
    vec3 pos = vec3(Tex, d);

    // transform by the projection inverse
    vec4 clip = inverse(ProjectionMatrix)*vec4(pos*2-1,1);

    // divide by w to get the position.
    return clip.xyz/clip.w;
}

float ssao(){
    vec2 Tex = CalcTexCoord();
    float radius = 3.0;

    //  get noise texture coords:
    vec2 noiseTexCoords = vec2(textureSize(depth, 0)) / vec2(textureSize(noise, 0));
    noiseTexCoords *= Tex;

    float originDepth = texture(depth, Tex).z;
    vec3 originPos = posFromDepth(Tex, originDepth);

    float occlusion = 0.0;

    float sampleDepth = 0.0;
    for (int i = 0 ; i < kernelSize ; i++) {
        //  get sample position:
        vec3 samplePos = originPos + kernel[i];

        vec4 offset = ProjectionMatrix * vec4(samplePos, 1.0);
        offset.xy /= offset.w;
        offset.xy = offset.xy * 0.5 + vec2(0.5);

        sampleDepth = texture(depth, offset.xy).z;
        sampleDepth = posFromDepth(offset.xy, sampleDepth).z;

        float rangeCheck = smoothstep(0.0, 1.0, radius / abs(originPos.z - sampleDepth));
        occlusion += step(sampleDepth,samplePos.z)*rangeCheck;
    }

    occlusion = (occlusion/float(kernelSize));

    return pow(occlusion, power);
}

void main() {
    FragColor = vec4(ssao());
}

```

As you can see I reconstruct position from depth. In other shaders this method works ok but here result looks like this:

---

**Other methods which I tried**

I tried also other methods which was presented in many tutorials but it gaves me even worse effects (for example everything was black). Here are some of methods which I used:

```
float CalcViewZ(vec2 Coords)
{
    float Depth = texture(depth, Coords).x;
    return ProjectionMatrix[3][2] / (2 * Depth -1 - ProjectionMatrix[2][2]);
}

float ViewZ = CalcViewZ(Tex);

float ViewX = viewRay.x * ViewZ;
float ViewY = viewRay.y * ViewZ;

...

vec3 originPos = vec3(ViewX, ViewY, ViewZ);

sampleDepth = CalcViewZ(offset.xy);

```

and

```
float linearizeDepth(in float z, in mat4 projMatrix){
    float n = 0.1;
    float f = 90.0;

    //return f * n / (z * (f - n) - f);
    //return (2.0 * n) / (f + n - z * (f - n));
    //return n * (z + 1.0) / (f + n - z * (f - n));
    return (2* n * f) / (f + n - z * (f - n));
}

float linearizeDepth(in float depth, in mat4 projMatrix) {
    return projMatrix[3][2] / (depth - projMatrix[2][2]);
}

...

float originDepth = texture(depth, Tex).z;
originDepth = linearizeDepth(originDepth, ProjectionMatrix);
vec3 originPos = viewRay * originDepth;

float sampleDepth = texture(depth, offset.xy).z;
sampleDepth = linearizeDepth(sampleDepth, ProjectionMatrix);

```

where viewRay is created in vertex shader:

```
viewRay = vec2(
    Vertex.x * uTanHalfFov * uAspectRatio,
    Vertex.y * uTanHalfFov
);

```

I have currently no ideas what is wrong with this. It's a bit urgent to me and I'll appreciate any help.

## Edit

I used linearization given by @Andon M. Coleman but sadly it doesn't help. Here are results:

```
float linearizeDepth(in float depth) {
    float n = 0.1;
    float f = 90.0f;
    return n / (f - depth * (f - n)) * f;
}

float originDepth = texture(depth, Tex).z;
originDepth = linearizeDepth(originDepth);
vec3 originPos = viewRay * originDepth;

sampleDepth = texture(depth, offset.xy).z;
sampleDepth = linearizeDepth(sampleDepth);

```

Here is how I'm creating Projection matrix (maybe it will help):

```
_projection3D.x.x=  (2 * from) / (right - left);
_projection3D.z.x= (right + left) / (right - left);
_projection3D.y.y=  (2 * from) / (top - bottom);
_projection3D.z.y= (top + bottom) / (top - bottom);
_projection3D.z.z=-(to + from) / (to - from);
_projection3D.w.z=-(2 * to * from) / (to - from);
_projection3D.z.w= -1;

```

# Answer
## Solution

I used good algorithm for depth linearization but I didn't convert depth to NDC first:

```
const float near = 0.1; // projection matrix's near plane
const float far = 90.0; // projection matrix's far plane
float LinearizeDepth(float depth)
{
    float z = depth * 2.0 - 1.0; // back to NDC
    return (2.0 * near * far) / (far + near - z * (far - near));
}

```

I also had another problem. Generated AO texture has strange visible strips. The solution to this problem was to set `GL_TEXTURE_MIN_FILTER` and `GL_TEXTURE_MAG_FILTER` to `GL_LINEAR` instead of `GL_NEAREST`.

Here is final effect with blur:

Because currently I store AO only in red channel I removed other channels from image. The one thing which I think should be better is too blurry background but I'm not sure how to fix it now (blur dependent on depth?).

I'd like also to put here link to fantastic page about OpenGL which helped mi a lot with my SSAO problems: Learn OpenGL -\> SSAO
> 5 votes

---
Tags: depth-buffer, deferred-rendering, depth, ssao
---


# Question
Title: Bounding volume hierarchy - linked nodes (linear model)
**The scenario** A chain of points: *(Pi)i=0,N* where Pi is linked to its direct neighbours (Pi-1 and Pi+1).

**The goal**: perform efficient collision detection between any two, non-adjacent links: (PiPi+1) vs. (PjPj+1).

**The question**: it's highly recommended in all works treating this subject of collision detection to use a broad phase and to implement it via a bounding volume hierarchy. For a chain made out of Pi nodes, it can look like this:

I imagine the big blue sphere to contain all links, the green half of them, the reds a quarter and so on (the picture is not accurate, but it's there to help understand the question). What I do not understand is:

*How can such a hierarchy speed up computations between segments collision pairs if one has to update it for a deformable linear object such as a chain/wire/etc. each frame? More clearly, what is the actual principle of collision detection broad phases in this particular case/ how can it work when the actual computation of bounding spheres is in itself a time consuming task and has to be done (since the geometry changes) in each frame update?* I think I am missing a key point - if we look at the picture where the chain is in a spiral pose, we see that most spheres are already contained within half of others or do intersect them.. it's odd if this is the way it should work.

# Answer
Essentially what you're describing with your spiral example is a pathological case, where all of the interesting points are co-incident. You could just as readily construct a hypothetical case where every single collision pair is identical.

The point of broad-phase culling and use of hierarchical volume trees is not to be a perfect solution for every case, but to improve efficiency in the general case. Given a relatively even distribution of collision objects through the space, hierarchical bounding systems like oct-trees or kd-trees are great at very quickly drilling down to a much smaller subset of objects to check. For a typical game where objects are distributed around a relatively large landscape rather than being localised to one tiny area, spatial partitioning is very cheap and generally very effective.

**But**, when choosing an algorithm for broad phase culling, you are always balancing efficiency of computation against expected results. Even if your spatial determination (the cost of figuring out where in the spatial hierarchy to put an object) only costs a tenth of the cost of a proper object-object check (the narrow phase), then to be more efficient, spatial partitioning needs to cut down the number of comparisons needed in the narrow phase by more than a factor of ten. If it doesn't, then you're better off not broad-phase culling at all.

If you know in advance your problem domain is such that the pathological cases are common (e.g. you're simulating a lot of coiled chains), then you should either a) tag those cases such that they skip the broad phase altogether and go straight to narrow phase without incurring the partitioning cost, or b) **find a broad-phase culling algorithm that better fits your domain**.

No algorithm will be perfect in all situations, you are looking for the best average efficiency gain for your particular situation. I can't think of a better solution off-hand for chain collision detection, but I should imagine that you can still use BVH-style culling, you just have to be smarter about how you separate out objects into cullable groups.
> 2 votes

# Answer
In the case you have posted, you would still get benefit from an Axis aligned bounding box based BVH - the first division could split the left/right segments (or top/bottom segments) with very little overlap, and subsequent sub-volumes would divide reasonably well too.

Unfortunately, using a circle as your bounding primitive for lines clustered in a circular shape ensures that you will always have a large amount of overlap, and an inefficient tree.
> 1 votes

---
Tags: collision-detection, physics-engine
---


title: Reading map.txt from assets android

text:
# Question
Title: Reading map.txt from assets android
I'm a beginner android developer currently working on my second app which is a platformer game. I'm trying to read the level map (which I've stored in the assets folder) but I keep getting a FileNotFoundException. This is the code to access it in the game play class:

```
@Override
public void init() {

    try {
        loadMap("file:///android_asset/map.txt");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private void loadMap(String filename) throws IOException {

    ArrayList lines = new ArrayList();
    int width = 0;
    int height = 0;

    BufferedReader reader = new BufferedReader(new FileReader(filename));
    while (true) {
        String line = reader.readLine();
        // no more lines to read
        if (line == null) {
            reader.close();
            break;
        }

        if (!line.startsWith("!")) {
            lines.add(line);
            width = Math.max(width, line.length());

        }
    }
    height = lines.size();

    // Rest of the code
}

```

I have read about using `InputStream` but my game play class extends `State` rather than `Activity` so I'm unable to use it. Can anyone help me out on how I can access the file or how I can work around this problem, it'll be much appreciated.

# Answer
> 0 votes
According to the answers to this question, referencing the assets folder using the *file:///android\_assets/* URI is only for WebViews. You need to use *assets://* instead.

You should also be using the AssetManager to load your files.

EDIT: Poking around a bit further, you can bypass all of this by using the getAssets() method of your Context. Store a reference to it somewhere and make it available to your game class.

---
Tags: android, tilemap
---


title: Choppy movement

text:
# Question
Title: Choppy movement
So, I'm trying to write some code in C# XNA to make an enemy move in a random direction for 0.5 seconds, then switch direction and once again move for 0.5 seconds. However the problem I've discovered is that the way I've done it, the movement becomes choppy, as in the instead of smoothly transitioning from Y1 to Y2 the enemy just "jumps" over there. The code for the movement is:

```
public static void enemy_movement()
    {
        int direction;
        for (int i = 0; i < enemy1_pos.Count; i++)
        {
            direction = rand.Next(4); //The enemy's movement direction
            Vector2 v = enemy1_pos[i];

                if (direction == 0) //Down
                {
                    v.Y += enemy1_speed;
                }
                else if (direction == 1) //Up
                {
                    v.Y -= enemy1_speed;
                }
                else if (direction == 2) //Right
                {
                    v.X += enemy1_speed;
                }
                else //Left
                {
                    v.X -= enemy1_speed;
                }
                enemy1_pos[i] = v;
            }
}

```

and this is the code calling on the function

```
protected override void Update(GameTime gameTime) {
        enemy1_time += (float)gameTime.ElapsedGameTime.Milliseconds;
        if (enemy1_time > 500)
        {
            enemy1_time -= 500;
            Action.enemy_movement();
        }
}

```

How can I make this work?

# Answer
> 1 votes
Rather than move your enemy every 500ms you should define how far an enemy should move in 1 second. For example, say an enemy can move 3 distance units every second. If you know the time between the last frame in milliseconds you can simply do this:

(pseudo code)

```
enemy_units_per_second = 3.0;
delta_time_ms = get_elapsed_time_ms();
enemy_movement_distance = enemy_units_per_second * (delta_time_ms / 1000.0);

```

This will allow your enemy to move in smooth increments every frame. The enemy will also move the same distance at the same speed, regardless of frame-rate.

# Answer
> 0 votes
As Shiro mentioned in the comments, you only move the enemy every half second. Instead you've got to set the direction every half second rather than moving it in a random direction, and make sure it always moves in the direction. And please use a switch rather than such a chain of if else's :)

---
Tags: xna, movement, timer
---


title: UDP packet reliability and re-sending

text:
# Question
Title: UDP packet reliability and re-sending
Like most people on this exchange concerned with UDP client server connections, I've gone through the Gaffer on Games article about implementing reliability. I understand how the ordering and acks and what not works (I think).

My issue is, some packets need to be re-sent until they are received, such as a packet stating that an entity has been created in the world. Others, such as updating the location of an entity don't need to be re-sent if a newer packet containing location data has already been sent.

What if, say, an entity is created and destroyed within a second. Say the create packet is lost but the destroy packet is received. The client has been told to destroy a non existent entity. If it just ignores this, when the create packet is re-sent, the entity will never be destroyed causing inconsistency.

All of this is per-client, so the actual game code should know nothing about it, only the networking code.

So how should this be handled? Do I flag certain packet types as `resend`. Do I send send a field in all dependent packets saying they depend on packet number `x`? Neither seem very elegant.

# Answer
> 2 votes
If the client receives a destroy packet without receiving the create packet, then it should know that it is out of sequence. The client won't have a record of the entity. Queue it until the create packet is received.

As you said, some packet types are sequence dependent and others are not. The client should know the protocol.

Another option is to send the create and destroy as a single event in the same packet if the original create packet hasn't been ack'd yet. This would depend on the protocol you define. You might have an extra bit in your create packet that indicates if the entity has also been destroyed, if there is no other information associated with the destroy event. You might also allow sending multiple events per packet for certain event types like create/destroy or even for all event types though if the data is variable length, then you will need a way to delimit the events in your packets.

If the server sends a new (as in different sequence ID) create/destroy packet but meanwhile the client does receive and ack the original create packet, it should know from the entity ID that it's a duplicate, regardless of the sequence ID being different. So it would just ignore the new create event and apply the destroy only.

# Answer
> 0 votes
You should consider using a mix of TCP and UDP flows and add a layer of abstraction over a raw UDP packet like a "message." Then, similar to the Steam API if you're familiar with it, you can expose functions like `sendReliable(message, destinationClient)` and `sendUnreliable(message, destinationClient)`. Reliable messages can be passed through the TCP stream, and yes you should in fact use TCP streams if the data being sent needs to be reliable or maintain order. Turns out implementing a reliable message protocol in UDP will basically be implementing a worse version of TCP.

You then can decide which data is sent in which way. You're right to send stuff like position updates over UDP, only the latest update is useful and if one is lost there's no reason to resend it. Anything that requires **order** and/or **reliability** definitely should probably be sent over TCP.

# Answer
> 0 votes
I don't recommend using TCP for reliable transport in games - the latency is too high, and the overhead of the transport will chew up your bandwidth. Instead you need to implement a reliable messaging system on top of UDP that uses ACKs to handle the sending and resending of messages. Consider the following situation - two machines are sending state information back and forth.

Machine A on Seq#100 creates object. In the packet it sends out, labelled #100, it includes the message.

Machine B receives the packet, and respond with the ACK of seq# 100. It creates the object.

Machine A receives the ACK of 100.

Later, Machine A destroys the object on seq# 200 and the same thing happens. A packet goes out with seq#200, Machine B acks it, and Machine A receives the ack.

This is great but how does it help us? Well if Machine B never receives seq#100, it can't ACK it, so machine A continues to send all the messages from previous sequence numbers until the ack is received - so seq# 101 has the create in it, seq#102 has the create in it, etc, until the ACK is received. In fact, because of latency, seq#101 is likely created and sent *before* the ack for 100 could ever be received, which helps decrease latency.

Should the ACK from Machine B to machine A be lost, then Machine A keeps sending the message until an ACK is received - it can't assume it has been received so it has no other choice but to do so.

Now if there is such dramatic packet loss that nothing is ack'ed since #100 when the object is destroyed, then the outgoing packet will contain both the create AND the destroy data, which is perfect. The messages should be put into the packet in sequence number order, so they maintain their timeline.

The key here is to put your messages into a queue, sorted by time, and to send the messages out until they are acknowledged. By having them in a queue, you add new messages to the back, and prune old messages from the front. Adding them is easy because they are always sorted in the queue. Further, the ACK sent from machine B to machine A should be bundled with whatever data that machine B needs to send back - there is no point to make a distinct packet - that's a waste of bandwidth.

Note that this is only for reliable messages. Unreliable messages work into this system just fine but are only sent on the seq# they are generated- they are not held onto and resent for multiple frames.

What I like about this system is that your create/destroy messages are kept in sync with the packet data for position, health, etc. which would be included in the same packet.

In a peer to peer game each peer would send the same data, so the packet layout might look like this:

Sequence # Acked Sequence # Number of messages in the packet each message additional payload data such as delta compressed snapshot data

Packet size grows as latency increases, but there are some ways to help mitigate that, such as slowing down the frequency you send packets at. I think Gaffer talks about that strategy.

I hope some of this makes sense.

---
Tags: networking, client-server, udp
---


# Question
Title: LibGDX MainMenu with ScrollPane - Select Level and press Play
In my level Menu, I am using tables that have images and text to identify each game level. Those tables are in a table that is inside a ScrollPane so the player can browse the levels available.

Here is how i've written the code:

```
//top of my show() method

    stage = new Stage();

    Gdx.input.setInputProcessor((com.badlogic.gdx.InputProcessor) stage);

    atlas = new TextureAtlas("levelsmenu/levelmenu.pack");

    skin = new Skin(Gdx.files.internal("levelsmenu/liststyle.json"), atlas);

//example of the tables with image and text identifying each level

    tableLevel1 = new Table();
    tableLevel1.add(new Image(skin, "rhlevelone"));

    tableLevel1.add(new Label("THE HOOD", skin));

//table with the levels available

    Table levelList = new Table(skin);
    levelList.add(tableLevel1);
    levelList.row();
    levelList.add(tableLevel2);
    levelList.row();
    // etc.

// ScrollPane

    scrollPane = new ScrollPane(levelList, skin);

//
table3.add(scrollPane).padLeft(220).expandY();

//
stage.addActor(table3);

```

On the stage I have a button to go back to the Main Menu and a button to play the level selected.

I would like to request help to figure out how to set the right listeners so a level can be selected in the ScrollPane and then played cliking the Play Button.

Should I use FocusListener or ClickListener?

Here is an illustration of what I want do do:

Thanks in advance for any help that may come!!!

Rich Days

# Answer
> 3 votes
This is the logic:

* Create `ImageButtons` or `TextButtons` first
* Add these to a `Table`
* Create a `ScrollPane` with the `Table`
* Set `ScrollPane` position and size. You can disable scrolling in a direction using `scrollPane.setScrollingDisabled()`
* Add `ScrollPane` to the `Stage`

# Answer
> -1 votes
Try using ChangeListener, i've never used a ScrollPane but I did some UI's using ChangeListener!

---
Tags: libgdx, menu, gui
---


# Question
Title: What is the recommended way to store compressed textures in files?
Uncompressed textures can be stored in lossy formats such as jpeg and it saves a lot of hard drive space. However for obvious reasons you cannot do the same on compressed textures.

So what is the recommended way to store compressed textures? Are there any lossy image compression that works even for any kind of compressed textures? If not, what kinds of lossless compression are usually used?

# Answer
> 0 votes
For the various lossy block compressed formats like DXT1 (aka BC1) you can apply standard lossless compression on top. The compression ratio will depend on the content of the textures, but I've seen it approximately halve the file size on a collection of various textures.

If you're really short on storage space you could store jpeg files on disc, and then convert to DXT1 at load time. However, that will probably slow down loading thanks to all the extra CPU work, and reduce texture quality.

---
Tags: textures, assets, storage, compression
---


title: Check if body is on the ground

text:
# Question
Title: Check if body is on the ground
In my game I have an quite irregular terrain at the bottom and a round ball which can be controlled by the keyboard. Is there any way to check, if the ball is currently on the terrain? This is very important to know because the ball should only be able to be controlled when it is on the ground.

I tried to use the `OnCollision` event of the ball body, but it only gets fired on the first occurrence.... For my problem a continuous type of collision-detection is needed.

# Answer
> 2 votes
try OnSeparation.

Pseudo c# code:

```
private void OnSeparation(....
{
 landed=false;
}
private void OnCollision(....
{
 landed=true;
}

```

# Answer
> 0 votes
You could make a trigger at the bottom of the ball and then check if the floor is in this trigger.

# Answer
> 0 votes
If there's gravity applied to your object you could check if the Y velocity==0 after you've done your collisions. It's maybe a bit fake it if you can't make it but in most situations it should work

# Answer
> 0 votes
I'm unfamiliar with Farseer, however in my own physics engine I handle this by getting an array of collisions which occurred in a given time-step and using the result of the Dot Product of the collision normal with the positive Y axis to see if any collision surface is within a certain angle of being parallel to the floor.

Raycasting is probably a better bet (especially if you are expecting many simultaneous collisions- the overhead from a check like this might be too much). Just putting an alternative out there- if this is possible with Farseer.

---
Tags: c#, collision-detection, farseer-physics-engine
---


# Question
Title: How do I make UIText scale properly in a VerticalLayoutGroup in Unity?
I have a Panel with an AspectRatioFitter on it.

In there, I have a vertical layout group, with three buttons, Standard Mode, Speed Mode, Chaos Mode.

I have the Layout Group's anchors set to keep its size relative to the parent Panel.

The problem is that the text doesn't resize when I change the screen resolution. You can see it's cut off to say "Standard M" in the bottom image.

But if I say "Best Fit", the texts aren't the same size, because the boxes are big enough to allow the shorter text to be bigger. The only way I've been able to fix this is to adjust the sizes and anchors of the text boxes by hand. Is there an automatic way to do this?

# Answer
Ok, I think I have it. Set the Canvas to use "Expand". No messing around with text box sizes or anchors, it just seems to work.

To be absolutely clear, I am still using the Aspect Ratio Fitter to force my Panel to maintain its aspect ratio, and it's set to Fit In Parent, which is the Canvas, and that is always the size of the screen.

Results:
> 2 votes

# Answer
You are trying to fit the same layout for horizontal and the vertical orientation. I am afraid it won't be easy to make it happen by tweaking the layout properties. It needs to be done manually through code.

1. Scale the button as a percentage of Vertical side (ButtonHeight=
Screen\_vertical\*0.2)
2. Scale button width according to the newly calculated height and button's aspect ratio
3. Position it in the middle (Screen\_Horizontal/2)
4. Anchor side buttons at (ScreenWidth +- offset)

You need to check if the layout works for the following aspect ratios (widest to narrowest), they will cover both android and iOS devices:-

* 5:4
* 4:3
* 3:2
* 16:10
* 16:9
> 0 votes

---
Tags: unity
---


# Question
Title: How do I avoid lag when dynamically loading a map chunk?
I have a procedural 2d game which extends in all directions, on the surface similar to Terraria. When a player moves their camera close to the edge of the currently loaded terrain, I trigger an expand event, which loads new chunks of terrain. Each chunk is an N×N section of tiles. When I do this I get a stutter of about 1 second due to the cost of procedurally generating the new tile set.

How can I avoid that delay?

---

Currently, all new chunks are loaded in the same iteration of the update loop (bad I know). My current idea is to create a queue to store the chunks and only render 1 chunk per game update.

# Answer
Start generation early; if a player gets within 3 screen widths of the edge of the generated map start generating more chunks on that edge 1 chunk at a time.

Focus generation on the area the player is likely to go. That means follow the walkable terrain and defer sky and underground for later (when they return to the location or linger for a while).

Multi-thread the generation. You can do that easily by doing the expensive creation in the other thread and then just paste the data into the level data in the update loop.
> 5 votes

---
Tags: tiles, procedural-generation, optimization, terrain-rendering
---


title: Crash when setting a new screen

text:
# Question
Title: Crash when setting a new screen
In my almost finished game I want to set a new screen on game over. I got my game over method:

```
    private void gameOver(Label score) {
    for (Body body : worldBodies) {
        world.destroyBody(body);
        dispose();
        ((Game) Gdx.app.getApplicationListener()).setScreen(new GameOver());
    }
}

```

Whenever the method gets called the screen freezes for a second and the game crashes with this statement:

```
09-02 22:04:34.036      391-425/com.joelbrun.jetskirider.android A/libc﹕ Fatal signal 11 (SIGSEGV), code 1, fault addr 0x8 in tid 425 (GLThread 29501)

```

# Answer
> 3 votes
Move this after the for loop:

```
dispose();
((Game) Gdx.app.getApplicationListener()).setScreen(new GameOver());

```

You create/set a new GameOver Screen each iteration, that causes probably the freeze and problems.

---
Tags: java, android, libgdx
---


# Question
Title: How do I efficiently fill the background with a tiling image?
I'm learning Unity by developing a 2D game. It's similar to *RimWorld* and *Prison Architect*. I have a 32×32-pixel grass tile image that I want to fill the background with.

Here's a screenshot from *Prison Architect* to demonstrate what I want:

I created a 2D sprite and set the grass image as sprite and created a prefab with this gameobject. I used this to fill background with prefab:

```
 // This script attached to main camera
for (int q = -1*(Camera.main.pixelHeight/2); q<Camera.main.pixelHeight; q++) {
    for (int i = -1*(Camera.main.pixelWidth/2); i<Camera.main.pixelWidth; i++) {
        Instantiate (grass, new Vector3 ((float)i, (float)q, 0f), Quaternion.identity);
    }
}

```

It's really slow because it's creating 619200 instances of the prefab for 860×720 screen resolution.

How can I better do this?

---

**UPDATE 1**

After Joe's answer.

1. Imported grass image to Unity
2. Created new material
3. Created a quad and set grass material
4. Result (ignore the purple thing):

# Answer
In unity you can create one material that utilizes the texture you want to tile and one "Surface Geometry" either quad or plane. Apply your new material to your new geometry and from there in the inspector, choose the Tiling amount both on the X and Y axes based upon the size of your Texture and the size of the Geometry. (eg if your texture is 16x16 and the floor is 160x160, you will want to tile your texture 10x10)

Take a look at the documentation for working with materials here.

Just like you said your performance is taking a huge hit because of the amount of game objects you are creating, when instead you should just make one GameObject and repeat the image rendered on it

EDIT!: That specific diffuse shader is just an example, you can use almost any shader type that accepts a texture. Even the new unity5 "Standard" shader accepts multiple image textures, but the most basic "Albedo" will allow you to tile it Standard Shader Docs

EDIT2: Forgot to mention texture wrap mode needs to be set from `Clamp` to `Repeat`
> 3 votes

# Answer
Instead of a separate object for each tile, your map should be a single object that's a grid of polygons and the UVs for each square are set to different images.
> 3 votes

# Answer
Hey I have answered a similar question before , here is the link -

https://gamedev.stackexchange.com/a/105947/40457

It basically fills out the screen using a tile map , which is nothing but a 2D array. If you find it difficult to implement then try out some plugins on the asset store to get started :)

Ok so the lag is basically due to the instantiating of gameobjects , which can be avoided. Make a parent in the game scene and add all tiles as children, ON awake just call Get Children function to reference those tiles into an array. Now replace the instantiate code with iteration over the tile pool array and use the tile which is idle or disabled.

As per the reference image you have provided , it looks more like unity terrain , may be you want to explore that option also :)
> 0 votes

---
Tags: unity, tiles, optimization
---


# Question
Title: Can I include 64-bit DLLs in a Unity 5 project?
I am building a C# DLL for inclusion in a Unity project. Due to some dependencies, this must be a 64-bit DLL. The last time I checked, DLLs for Unity had to be built with .NET Framework 3.5 (although this isn't explicitly stated in the DLL documentation). Are there any requirements for bitness?

# Answer
If you use the 64-bit version of the Editor then you need a 64-bit plugin and vice versa. If you are using the 64-bit editor but are also targeting 32-bit platforms you will need two versions of the dll.

Here is a related discussion that may be helpful to make it more clear.

Here is another discussion, that explains how to import and configure both plugins side-by-side.
> 1 votes

# Answer
Yes you should be able to. However, it might limit you to a x64 build.
> -1 votes

---
Tags: unity, dll
---


# Question
Title: How do I ensure consistent behaviour when using Unity's Collider2Ds for triggers and collisions?
I am experiencing inconsistent behavior using Unity's 2D Physics engine and their Collider2Ds to detect collisions and triggers on my projectiles. I will classify it into two problems. The first is that occasionally the projectile will pass through walls/objects it should collide with. The second is that occasionally the projectile will pass through enemies that it should hit without triggering. I will try to elaborate in detail below.

A projectile is organized into a container Projectile GO and two children GO: a PhysicsColliders GO and a HitBoxColliders GO.

The PhysicsCollidersGO job is to hold the colliders that define the solid regions of the projectile using Collider2D components. It's GO is on a Projectile layer which is set to collide with other solid layers such as the ones my walls are on. Walls are static colliders.

The HitBoxCollidersGO job is to define the a HitBox area. It's GO is on a HitBox layer and also uses Collider2D components that are set to be triggers. A HitScript on the GO listens for OnEnterTrigger.

Projectiles are set in motion by setting the velocity of the RigidBody once upon firing.

Here is a visual of the structure:

```
 ProjectileGO
  - PhysicsCollidersGO
  - HitBoxCollidersGO

```

Here are descriptions of the GameObjects and their components:

```
 ProjectileGO
   - RigidBody2D Component (collisionDetectionMode is set to Continious)

 PhysicsCollidersGO (Layer is set to Projectile)
   - BoxCollider2D Component

 HitBoxCollidersGO (Layer is set to HitBox)
   - BoxCollider2D Component (IsTrigger is set)
   - HitScript Component

```

Problem 1. Projectiles will sometimes not collide with walls/solid objects/etc...

Problem 2. Projectiles will sometimes not trigger a hit.

What could be causing these inconsistencies? How can ensure that collisions and triggers will consistently behave correctly?

# Answer
I'd like to start with making the assumption that these objects are traveling relatively quickly, I have seen similar behavior and was able to get more reliable physics interactions doing a combination of the following three solutions.

First off - since physics interactions are calculated at fixed intervals, reducing the speed of fast moving objects (not always possible) can greatly reduce these issues.

If thats not an option, (or in conjunction with reducing the speed) you should look to changing the `Collision Detection` Mode on the Rigidbody/2d Component

* We have a few options but by default unity chooses to use a less resource intensive method called `Discrete`. You can chose which Rigidbody objects you would like to increase the collision "sensitivity on" and ramp that mode up to `Continuous` or `Continuous
Dynamic` and read more about them here in the documentation I have set objects with high priority interactions, Players, Enemies,Projectiles to continuous with some success.

If for some reason continuous is not enough you can opt in to a more performance requiring option by scaling down the Unity "Fixed Time Step" for your project... ultimately asking Unity to do more physics computations per second.
> 2 votes

---
Tags: unity, 2d
---


title: Can't submit facebook app for review

text:
# Question
Title: Can't submit facebook app for review
I'm trying to submit my app for review with publish\_action.

I keep getting the following error:

"It looks like you haven't made any API requests to access content with the publish\_actions permission in the last 30 days."

I'm publishing posts to the users' feed with Facebook SDK for Unity.:

```
 FB.Feed(link: LinkToApp);

```

I've filled all the necessary fields.

I posted both from the Graph and from an iOS device and I still get the same error when I try to submit for review.

What is missing?

# Answer
> 0 votes
On your FB.Login make sure you request the action

```
public void FBLogin()
{
    FB.Login("email, publish_actions", AuthCallback);
}

```

# Answer
> 0 votes
Use a test user (which you have given publish\_actions permission in the settings, then the request action for 30 days will disappear.

---
Tags: unity, facebook
---


# Question
Title: How do I interpolate around a rectangle?
I want to make a fancy animation where a point travels around a rectangle. I want to find the point's position at a time `t`.

The rectangle is given by `X`, `Y`, `Width` and `Height`.

Is there an algorithm for this?

I've used `sin`/`cos` for circles. What's the equivalent approach for rectangles?

# Answer
> 14 votes
I'll assume your *t* goes from *0* to *1*. (If not, just multiply to scale it appropriately.)

Figure out what proportion (*0**1*) each side is of the perimeter. (*side length / total perimeter*)

To find how much of every side is “filled in” at time *t*, iterate through sides, subtracting their proportions until *t* is depleted to a negative value. That last edge (which caused *t* to go negative) is filled by a proportion of *(side length + remaining) / side length*. The rest are not filled.

To get the exact vector position at *t*, multiply each side's vector by the proportion of that side that is filled, and add them.

This works for any polygon actually!

# Answer
> 2 votes
The sine and cosine of t are respectively the y and x coordinate of a point on the circle forming an angle t with the x-axis. No need for that in a rectangle! A rectangle is made of four lines. If `t` goes from `0` to `1`, it reach the point `(px,py)` at `t==0` and to `(qx,qy)` at `t==1` with the line given by:

```
(l(x),l(y)) = (t*qx + (1-t)*px, t*qy + (1-t)*py)

```

if instead of `0` and `1`, you time goes from `t0` to `t1`, you can normalize the time first and then apply the above formula.

```
(l(x),l(y)) = (  ((t-t0)/(t1-t0))*qx + ((t1-t)/(t1-t0))*px, ((t-t0)/(t1-t0))*qy + ((t1-t)/(t1-t0))*py  )

```

Now, for you rectangle, divide in four cases with an `if` for each edge that covers one of the span of time and apply a line movement.

Notice that if your rectangle is axis-aligned, you will always have either the x-value or the y value which is constant. For instance, for t between `0` and `a/4` (and supposing (X,Y) is bottom left),

```
(l(x),l(y)) = ((4*t/a)*(X+Width) + (1-4*t/a)*(X), Y+Height)

```

Which is also equals to:

```
(l(x),l(y)) = (X + (1-4*t/a)*(Width), Y+Height)

```

# Answer
> 1 votes
I don't know if there is an actual algorithm for this, but I made one myself (Java):

```
int points = 4; // for a rectangle
double progress = 0.0; // 0.0 -> 1.0 (with 1.0 being 100%)
double pp = points * progress; // This calculation would otherwise be done multiple times

int p1 = Math.floor(pp);
int p2 = Math.ceil(pp);

while (p1 >= points) p1 -= points;
while (p2 >= points) p2 -= points;

double tmp = 2 * Math.PI / points;

int p1x = Math.cos(tmp * p1);
int p1y = Math.sin(tmp * p1);
int p2x = Math.cos(tmp * p2);
int p2y = Math.sin(tmp * p2);

double p = pp - Math.floor(pp);

int x = (1.0 - p) * p1x + p * p2x; // between -1.0 and 1.0
int y = (1.0 - p) * p2x + p * p2y; // between -1.0 and 1.0

if (p == 0.0) { // prevent a weird glitch when p = 0.0 (I think this is a glitch)
    x = p1x;
    y = p1y;
}

```

You should transform the `x` and `y` variables to get your animation as big or small as you want (by multiplying) and where you want (adding to / subtracting from x and y).

I haven't tested this code, but I think it should work. This should also work for any polygon with any number of points (you could also use a bit of the code to generate the polygon).

# Answer
> 1 votes
Given :

```
a=total time

perimeter = WIDTH *2 + HEIGTH * 2;

```

Given time `T1` how to get `P` on perimeter (assuming rect position at 0,0)?

```
T1=T1%a; //use mod to have T1<a

distT1 = (T1*Perimeter)/a; //distance traveled in time T1

```

now some easy primary scool geometry and math (that hope you spare me) to obtain `P.x` and `P.y` from `distT1`

---
Tags: animation, geometry, interpolation
---


# Question
Title: Handling input in ECS for multiple characters
I've been reading into Entity-Component-Systems, and they seem rather handy. However, I don't quite understand how input should be handled and after googling and looking thru GDSE posts, I've become even more confused. I see plenty of explanations, but no examples of how to incorporate things like an `intent system`.

Originally, I planned on polling for keyboard events and passing those events onto a controller. This controller would have a vector of callback functions, which could be rebound to different keys on the fly. But then I realized it doesn't translate well into a game with multiple characters, each with their own set of actions - like a fighting game, or the Megaman X games that allow you to switch between characters.

I thought that if I were to make these callback functions rather generic, so that they just change the state of the character, then have a System that consumes states for different characters to apply different results to the action (IE, the "jump" button would set the currently controlled character's state to `JUMPING`. But maybe Character 1 jumps faster than Character 2, but Character 2 jumps higher). But that doesn't seem like a wise idea, because now I have a system for every state that each character could possibly have. It smells really bad, basically. And to have a character unsubscribe from one "State System" and resubscribe to another just gives me the feeling that I am not doing something right, but I am at a loss.

How should I handle input that can differ slightly from character to character? I feel like I am on the right track with having the states handle input, but I don't think that each state should have it's own system. A state should be generic and operate on many entities, not just a single instance of one!

# Answer
In ECS there's the concept that an entity is just a collection of components that can be added or removed at will. Typically which set of components an entity has at a given time determine its behavior. Some implementations of ECS are able to detect when components are added or removed from an entity and then automatically change the behavior of the entity. This could be by a process of automatically registering or unregistering the entity from the systems that implement the behaviors.

For example, being or not being in the state of JUMPING could be represented by a Jumping component that an entity has or doesn't have. The ECS engine would handle registering or unregistering entities from the Jumping system as they gain or lose their Jumping components. Pressing the jump button on a game controller would result in a Jumping component being added to the character's entity that the game controller is controlling. While the entity has a Jumping component, it would be registered with the Jumping system that handles applying the physics forces needed to move the character every frame. After moving the character, the Jumping system could check to see if the character is now on the ground or hit a wall and remove the Jumping component from the character if it has, since that would mean it should no longer be in the JUMPING state. The ECS engine would then automatically unregister the entity from the Jumping system. The entity would stop being updated by the Jumping system every frame and would stop moving.

Since a Jumping component is just an object itself, it could have properties on it that would be available to the Jumping system to use in movement calculations. This way you could get different jumping styles with just a single kind of Jumping component. Each character is an entity with its own Jumping component. The Jumping system just loops through all the entities registered with it and grabs each entity's Jumping component.
> 1 votes

---
Tags: c++, software-engineering, input, sdl, entity-component-system
---


title: Wander steering behaviour in 3D

text:
# Question
Title: Wander steering behaviour in 3D
I'm trying to implement the *Wander Steering Behaviour* but getting strange result (see .gif). What am i doing wrong? I want to move a sphere in a random direction.

```
using UnityEngine;

public class UnitWander : MonoBehaviour
{
    public const float CircleDistance = 1f;
    public const float CircleRadius = 0.1f;
    public const float AngleChange = 50f;

    public float Mass = 1;
    public float MaxSpeed = 1;
    public float MaxForce = 1;

    private Vector3 velocity = Vector3.forward;
    private float wanderAngle;

    private void Update()
    {
        var steering = GetWanderForce();
        steering = Vector3.ClampMagnitude(steering, MaxForce);
        steering /= Mass;

        velocity = Vector3.ClampMagnitude(velocity + steering, MaxSpeed);
        transform.position += velocity;
        transform.forward = velocity;
    }

    private Vector3 GetWanderForce()
    {
        var circleCenter = velocity.normalized * CircleDistance;

        var displacement = transform.right * Mathf.Cos(wanderAngle * Mathf.Deg2Rad) * CircleRadius;
        displacement += transform.up * Mathf.Sin(wanderAngle * Mathf.Deg2Rad) * CircleRadius;

        wanderAngle += (Random.value * AngleChange) - (AngleChange * 0.5f);

        var wanderForce = circleCenter + displacement;
        return wanderForce;
    }
}

```

# Answer
I solved the problem. Now script work fine. Just drop this script on game object and enjoy.

```
using UnityEngine;

public class UnitWander : MonoBehaviour
{
    public float CircleRadius = 1;
    public float TurnChance = 0.05f;
    public float MaxRadius = 5;

    public float Mass = 15;
    public float MaxSpeed = 3;
    public float MaxForce = 15;

    private Vector3 velocity;
    private Vector3 wanderForce;
    private Vector3 target;

    private void Start()
    {
        velocity = Random.onUnitSphere;
        wanderForce = GetRandomWanderForce();
    }

    private void Update()
    {
        var desiredVelocity = GetWanderForce();
        desiredVelocity = desiredVelocity.normalized * MaxSpeed;

        var steeringForce = desiredVelocity - velocity;
        steeringForce = Vector3.ClampMagnitude(steeringForce, MaxForce);
        steeringForce /= Mass;

        velocity = Vector3.ClampMagnitude(velocity + steeringForce, MaxSpeed);
        transform.position += velocity * Time.deltaTime;
        transform.forward = velocity.normalized;

        Debug.DrawRay(transform.position, velocity.normalized * 2, Color.green);
        Debug.DrawRay(transform.position, desiredVelocity.normalized * 2, Color.magenta);
    }

    private Vector3 GetWanderForce()
    {
        if (transform.position.magnitude > MaxRadius)
        {
            var directionToCenter = (target - transform.position).normalized;
            wanderForce = velocity.normalized + directionToCenter;
        }
        else if (Random.value < TurnChance)
        {
            wanderForce = GetRandomWanderForce();
        }

        return wanderForce;
    }

    private Vector3 GetRandomWanderForce()
    {
        var circleCenter = velocity.normalized;
        var randomPoint = Random.insideUnitCircle;

        var displacement = new Vector3(randomPoint.x, randomPoint.y) * CircleRadius;
        displacement = Quaternion.LookRotation(velocity) * displacement;

        var wanderForce = circleCenter + displacement;
        return wanderForce;
    }
}

```
> 3 votes

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


# Question
Title: Right-To-Left Text Direction in Cocos2dx
I want to use **Persian**/**Arabic** text beside **English** in whether `Label` or `ui::Text`.

**Persian** is a *Right-to-Left* and **English** is a *Left-to-Right* language and so I have problem to combine them in one string.

**Scnario:**

I want to show this text: 1.`"من1"` then 2.`"emadpres2"` and finally 3.`"3هستم"`.

If I write this text in a *Left-to-Right* editor it show as : ( Wrong Direction: **=====\>** )

> 1من emadpres2 هستم3

But actually it should be shown as : ( Correct Direction: **\<=====** )

> هستم3 emadpres2 من1

This is my code :

```
auto rtl = Label::createWithSystemFont("سلام emadpres چطوری", B_NAZANIN, 25, Size(480, 100));
// The string here is also in wrong direction because the Visual Studio editor is Left-to-Right.
rtl->setColor(Color3B(0, 0, 0));
rtl->setPosition(...);
rtl->setHorizontalAlignment(TextHAlignment::RIGHT);
this->addChild(rtl, Z_NORMAL);

```

and this is the screenshot of this code:

As you see, I tried to use `TextHAlignment` but It doesn't help. I need something to change **Direction** not **Alignment** .

How should I make it *Right-to-Left* ?

PS: Cocos2dx v3.3

# Answer
It's not the label that understand the text direction, but the OS. as you guessed Android check the first letter to guess how it should format the text, whether it's RTL or LTR.

`Label::createWithSystemFont` basically asks the OS to render the text for you. It's completely out of cocos2dx's control how the text is rendered, And thus it's completely OS dependent. If you want to write a code, which works on every platform, you should handle things yourself. Meaning you should separate the string over it's spaces (and direction independent characters e.g. punctuation marks) and place them carefully, one by one when they should be shown.
> 2 votes

# Answer
Although problem still exist in **windows**, But in **Android** everything magically is shown correctly independent of using *English / Persian* in any order.

I test it with `Label::createWithSystemFont` !

PS: I **guess** `Label` understanding the **direction**(LtR or RtL) by checking first letter maybe. I will test it and edit this answer soon.
> 0 votes

---
Tags: cocos2d, cocos2d-x
---


# Question
Title: Unity - custom Export and Import FBX Data
I am trying to write custom data inside a FBX file from 3dsmax at export time. This might be possible even if I don't know right now how to do that.
But my question would be how can I read those custom FBX data inside Unity on import.

Thanks a lot.

# Answer
> 0 votes
Here is a great answer from **theodox** on **Stackoverflow**.

> The easy way to do this is to add a custom attribute to an object in the Maya/Max scene and then use the Unity AssetPostprocessor to find the attribute and parse it's data.
>
> AssetPostprocessor has an OnPostprocessGameObjectWithUserProperties callback which will be fired for every transform in your fbx file which has a custom attribute applied. You'll want to find your attribute in the postprocessor and do something:

```
public void OnPostprocessGameObjectWithUserProperties(GameObject incomingGameObject, string[] incomingPropetyNames, object[] incomingValues)
{
    var thisModelImporter = this.assetImporter as ModelImporter;
    var meta_key = "your_attribute_name";
    if (incomingPropetyNames.Contains(meta_key))
    {
        string raw_data = (string)incomingValues[Array.IndexOf(incomingPropetyNames, meta_key)];
        // use the data here....
    }
}

```

> It's annoying that there's no standard way to create file-level metadata, I usually just attach my 'top level' data to something like the root of the model in the FBX file. You can pass complex data by storing things as a JSON blob and passing the JSON as a string attribute; that's usually easier to maintain than a web of multiple attribute names and types.
>
> Be warned that FBX tends to mangle long attibute names - I'm not sure where the cutoff is but extremely long attribute names sometime get truncated to a meaningless string like \`FBXASC\_012345" if they exceed the magic character count.
>
> The only thing you cant do easily this way is vertex or face level data; while you could pack that sort of thing into custom attributes, there's not a rock-solid guarantee that the indices you see in Max/Maya will be the same as the ones in the FBX. For that type of data vertex colors or extra UV channels are good places to store extra information, though it's up to you to come up with a way of deciding what a given color or UV means.

# Answer
> 1 votes
You would need to write an asset post processor to tell Unity what you want to do with that data.

Here is a link to the documentation :-

AssetPostprocessor

A script on how this can be implemented :)

https://gist.github.com/darktable/2425709

---
Tags: unity, c#, 3dsmax, fbx
---


# Question
Title: Google Leaderboards, Reducing the Score of a Player
I am making a strategy game similar to chess for Android.

I'll be using the Google Leaderboards for rankings.

I want to implement a sort of ranking system, that the player can actually lose score, similar to the one in www.chess.com.

But, from the docs of `submitScore()`:

**"The score is ignored if it is worse than a previously submitted score for the same player."**

I don't understand how can I implement such a system with Google Leaderboards.. sorry if I'm missing something obvious here.

# Answer
Google Leaderboards saves the highest score, it can't simply reduce the score.

Your best bet is to create your own leaderboard system, which would allow you to remove/add score when needed.
> 2 votes

---
Tags: android, leaderboards, google-play
---


title: How to make a stab function?

text:
# Question
Title: How to make a stab function?
I've looked around everywhere, and I can't find an example script for a stab. What I have so far is a top down 2D scene, with a player at the bottom (static). I would like to have the sword/tongue to translate/moveTo upwards to a maxTranslation, then back to the player. While the the "sword" is still in motion, I would like to lock the Input key, so that the player cannot hit the button again while the sword is already out.

So far, this is what I have tried:

```
#pragma strict

var cancelMove : boolean;
var speed : int;
var maxTranslation : double;

function Start () {
    transform.position.z = -0.5;
    speed = 20; // Input speed here
    maxTranslation = 11.8; // Input max translation here
}

function Update () {
    if (Input.GetKeyDown ("space")) {
        moveTo(maxTranslation, speed);
    }

    if (Input.GetKeyUp ("space") && !cancelMove) {
        cancelMove = true;
        moveTo(-11, speed);
    }
}

function moveTo (posY : float, speed : float)
{
    if (posY != -11) {
        while (transform.position.y != posY && Input.GetKey ("space") && !cancelMove)
        {
            transform.position = Vector2.MoveTowards (transform.position, new Vector2(transform.position.x, posY), speed * Time.deltaTime);
            yield;
        }
    }
    else {
        while (transform.position.y != -11) {
            transform.position = Vector2.MoveTowards (transform.position, new Vector2(transform.position.x, posY), speed * Time.deltaTime);
            yield;
        }
        cancelMove = false;
    }
}

```

And:

```
#pragma strict

function Start () {
    transform.position.z = -0.5;
}

function Update () {
    if(Input.GetKeyDown ("space"))
    {
        moveTo(transform.position.y + 10, 50); // Feed the moveTo() function the X/Y positions you want to move it to, and the Speed you want to move at
    }
    transform.position.z = -0.5;
}

function moveTo(posY : float, speed : float)
{
    while (transform.position.y != posY)
    {
        transform.position = Vector2.MoveTowards (transform.position, new Vector2(transform.position.x, posY), speed * Time.deltaTime);
        yield;
    }
}

```

So in the end, how would I implement:

1. A "whip-like" function, where the tongue/sword translates upwards, stays for an interval of about 0.5 seconds, and returns to its original position.
2. The player hitting "space" while the tongue is already out will not do anything.

# Answer
It would be better to animate sword rather than make it move through code.
> -2 votes

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