title: Handling large 2D MMORPG map

text:
# Question
Title: Handling large 2D MMORPG map
I have 1000\*1000 (1,000,000 tiles) fixed size map composed of 3 layers (3,000,000 tiles) every tile has 4 values X,Y,Z and ID (12,000,000 values). When a client connects and requests map data, server has to send 10x10(100 tiles) tiles in a packet and every time the player moves server sends map buffer which is a row of tiles data (X,Y,Z and ID) in a packet too. All these values needed to be loaded on server startup and that's without mentions other variables. Am i on the right path? Is there is any better method?

Additional info: I'm using C# server, map is made by Tiled exported to XML file with CSV format. Client is supposed to be on GameMaker Studio (not yet made)

# Answer
> 2 votes
It is usually not required for each tile to know its own x, y and z coordinates. These are usually inferred from their position in the data-structure which stores the tiles. But there are a few situations where it actually *can* be useful, so I am giving you the benefit of a doubt.

When your map is static (does not change during the game, or at least doesn't change much), then you might want to consider to add a complete copy of your map as an asset to your game client. That way the server doesn't need to send any map data to the clients (except maybe through the pre-game auto updater).

If your game has a dynamic map (it is altered during gameplay), then you might want to send it to the player in form of chunks (rectangular cells of map data). When you send the client a chunk, you don't need to send the x, y and z coordinate of every single tile. You just need to tell the coordinates where the chunk starts, its width and height (number of layers will likely be constant) and then a long list of id's. You might be able to save some more bandwidth by running the id collection through a stock compression algorithm like Deflate or LZW. Check which algorithm gives the best results for your particular mapping style.

Also make sure you don't send any map data the client already knows. When the client walks back and forth between two points, and the terrain doesn't change, you don't need to tell it how it looks over and over again. You could solve this by either having the server remember which client already got which version of which chunk. Or you could turn it around and use a request-model where the client asks the server when it wants a chunk by telling the server the chunk-coordinates and the latest version it got. The server then either replies with a new version of that chunk or with a "chunk didn't change" message.

---
Tags: c#, 2d, tilemap, client-server, mmo
---


# Question
Title: MonoGame EffectPass.Apply() doesn't work
Currently I'm doing the following:

```
spriteBatch.Begin(effect: effect);

// Draw stuff normally

effect.Parameters["flag"].SetValue(true);
effect.CurrentTechnique.Passes[0].Apply();

// Draw stuff with flag

effect.Parameters["flag"].SetValue(false);
effect.CurrentTechnique.Passes[0].Apply();

// Draw stuff normally

```

But this doesn't work. The flag stays false even after I apply the changes.

# Answer
> 0 votes
i believe it's because of how SpriteBatch works. the effect is being run when all the sprites are submitted to the gpu. You have to either call spriteBatch.End() or set SpriteSortMode to Immediate or Texture

# Answer
> 0 votes
You shouldn't need to pass the effect to spritebatch begin. You are handling it all yourself.

EDIT: Because you call effect.CurrentTechnique.Passes\[0\].Apply(); You don't need to pass the effect to the Begin function

---
Tags: monogame, hlsl
---


# Question
Title: How can I find each time the right number of objects?
I have in this case 10 objects. Each object have this script attached:

```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ShowMeshBounds : MonoBehaviour
{
    public GameObject prefabEffect;
    public Color color = Color.green;

    private Vector3 v3FrontTopLeft;
    private Vector3 v3FrontTopRight;
    private Vector3 v3FrontBottomLeft;
    private Vector3 v3FrontBottomRight;
    private Vector3 v3BackTopLeft;
    private Vector3 v3BackTopRight;
    private Vector3 v3BackBottomLeft;
    private Vector3 v3BackBottomRight;

    private float counter = 0;
    public bool animateLines;
    public float speed = 1f;

    private List<GameObject> allLines = new List<GameObject>();
    private List<GameObject> instancesToMove = new List<GameObject>();
    private Vector3 endPos;

    private void Start()
    {
        CalcPositons();
        DrawBox();
        allLines = GameObject.FindGameObjectsWithTag("FrameLine").ToList();

        DuplicatePrefabEffects(allLines.Count);
        instancesToMove = GameObject.FindGameObjectsWithTag("Duplicated Prefab").ToList();

        StartCoroutine(moveStuff());
    }

    private void DuplicatePrefabEffects(int duplicationNumber)
    {
        for (int i = 0; i < duplicationNumber; i++)
        {
            var go = Instantiate(prefabEffect);
            go.tag = "Duplicated Prefab";
            go.name = "Duplicated Prefab";
        }
    }

    void CalcPositons()
    {
        Bounds bounds = GetComponent<MeshFilter>().sharedMesh.bounds;

        Vector3 v3Center = bounds.center;
        Vector3 v3Extents = bounds.extents;

        v3FrontTopLeft = new Vector3(v3Center.x - v3Extents.x, v3Center.y + v3Extents.y, v3Center.z - v3Extents.z);  // Front top left corner
        v3FrontTopRight = new Vector3(v3Center.x + v3Extents.x, v3Center.y + v3Extents.y, v3Center.z - v3Extents.z);  // Front top right corner
        v3FrontBottomLeft = new Vector3(v3Center.x - v3Extents.x, v3Center.y - v3Extents.y, v3Center.z - v3Extents.z);  // Front bottom left corner
        v3FrontBottomRight = new Vector3(v3Center.x + v3Extents.x, v3Center.y - v3Extents.y, v3Center.z - v3Extents.z);  // Front bottom right corner
        v3BackTopLeft = new Vector3(v3Center.x - v3Extents.x, v3Center.y + v3Extents.y, v3Center.z + v3Extents.z);  // Back top left corner
        v3BackTopRight = new Vector3(v3Center.x + v3Extents.x, v3Center.y + v3Extents.y, v3Center.z + v3Extents.z);  // Back top right corner
        v3BackBottomLeft = new Vector3(v3Center.x - v3Extents.x, v3Center.y - v3Extents.y, v3Center.z + v3Extents.z);  // Back bottom left corner
        v3BackBottomRight = new Vector3(v3Center.x + v3Extents.x, v3Center.y - v3Extents.y, v3Center.z + v3Extents.z);  // Back bottom right corner

        v3FrontTopLeft = transform.TransformPoint(v3FrontTopLeft);
        v3FrontTopRight = transform.TransformPoint(v3FrontTopRight);
        v3FrontBottomLeft = transform.TransformPoint(v3FrontBottomLeft);
        v3FrontBottomRight = transform.TransformPoint(v3FrontBottomRight);
        v3BackTopLeft = transform.TransformPoint(v3BackTopLeft);
        v3BackTopRight = transform.TransformPoint(v3BackTopRight);
        v3BackBottomLeft = transform.TransformPoint(v3BackBottomLeft);
        v3BackBottomRight = transform.TransformPoint(v3BackBottomRight);
    }

    void DrawBox()
    {
        SpawnLineGenerator(v3FrontTopLeft, v3FrontTopRight, color);
        SpawnLineGenerator(v3FrontTopRight, v3FrontBottomRight, color);
        SpawnLineGenerator(v3FrontBottomRight, v3FrontBottomLeft, color);
        SpawnLineGenerator(v3FrontBottomLeft, v3FrontTopLeft, color);

        SpawnLineGenerator(v3BackTopLeft, v3BackTopRight, color);
        SpawnLineGenerator(v3BackTopRight, v3BackBottomRight, color);
        SpawnLineGenerator(v3BackBottomRight, v3BackBottomLeft, color);
        SpawnLineGenerator(v3BackBottomLeft, v3BackTopLeft, color);

        SpawnLineGenerator(v3FrontTopLeft, v3BackTopLeft, color);
        SpawnLineGenerator(v3FrontTopRight, v3BackTopRight, color);
        SpawnLineGenerator(v3FrontBottomRight, v3BackBottomRight, color);
        SpawnLineGenerator(v3FrontBottomLeft, v3BackBottomLeft, color);
    }

    void SpawnLineGenerator(Vector3 start, Vector3 end, Color color)
    {
        GameObject myLine = new GameObject();

        myLine.tag = "FrameLine";
        myLine.name = "FrameLine";

        myLine.AddComponent<LineRenderer>();
        myLine.AddComponent<EndHolder>();
        myLine.GetComponent<EndHolder>().EndVector = end;
        LineRenderer lr = myLine.GetComponent<LineRenderer>();
        lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
        lr.startColor = color;
        lr.useWorldSpace = false;
        lr.endColor = color;
        lr.startWidth = 0.1f;//0.03f;
        lr.endWidth = 0.1f;//0.03f;
        lr.SetPosition(0, start);
        lr.SetPosition(1, start);
    }

    IEnumerator moveStuff()
    {
        for (int i = 0; i < allLines.Count; i++)
        {
            counter = 0;

            while (Vector3.Distance(instancesToMove[i].transform.position, endPos) > 0.1f)
            {
                counter++;
                endPos = allLines[i].GetComponent<EndHolder>().EndVector;
                Vector3 startPos = allLines[i].GetComponent<LineRenderer>().GetPosition(0);
                Vector3 tempPos = Vector3.Lerp(startPos, endPos, counter / 500f * speed);

                instancesToMove[i].transform.position =
                    Vector3.MoveTowards(startPos, endPos, counter / 25f * speed);

                allLines[i].GetComponent<LineRenderer>().SetPosition(1, instancesToMove[i].transform.position);//tempPos);

                //move towards destination
                yield return null;
            }
        }
    }
}

```

The problem is that each gameobject find objects name "Frame Line" And then in the Start this line:

```
allLines = GameObject.FindGameObjectsWithTag("FrameLine").ToList();

```

Will find each time more and more gamoebjects and will duplicate on this line:

```
DuplicatePrefabEffects(allLines.Count);

```

Too many objects. First it find 12 objects then 24 36 48 and so on. But it should or what I want it to find each 12 gameobjects in the end it should have 120 frame line.

# Answer
This is why it behaves that way:

* `Start()` is called on the first of your 10 game object.
* `DrawBox()` is called, which in turns calls 12 time `SpawnLineGenerator()`
* Every time `SpawnLineGenerator()` is called, you create a new game object with the line `GameObject myLine = new GameObject();`: these new game objects are all instantiated in the root of your scene
* `allLines = GameObject.FindGameObjectsWithTag("FrameLine").ToList();` is called: for the first time it will find the first 12 game object

But, when the second `Start()` is called, the code will add another 12 new game objects in the root, so now you have 24 game objects with the tag `FrameLine`, and they will be added to the `allLines` list. The 10th time `Start()` is called, the code will add all the 120 game objects to `FrameLine`.

To avoid this, and to assign exactly 12 game objects to each of these 10 objects, you only need to children these 12 game objects to each of the 10 game objects with the script, with this code:

```
private void Start()
{
    CalcPositons();
    DrawBox();
    //With this foreach you check all children, and add only the ones with the appropriate tag
    foreach (Transform item in transform) {
        if (item.gameObject.tag == "FrameLine") {
            allLines.Add(item.gameObject);
        }
    }

    //Do rest of your stuff
}

void SpawnLineGenerator(Vector3 start, Vector3 end, Color color)
{
    GameObject myLine = new GameObject();
    //Make myLine a child of this game object
    myLine.transform.parent = transform;

    //Do all your other stuff
}

```
> 2 votes

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


# Question
Title: How to draw geometric shapes to a texture?
How can I create a texture containing a geometric figure using SDL2?

I saw there is a way to convert **Surface** to **Texture**, and I also saw that there is a way to draw directly to the screen using `DrawRect()` / `FillRect()` functions... I'm not sure if the geometry has something similar. Ultimately I want to have a texture to render.

The way I'm making my engine draw is to read game objects' texture and copy it to the render using `render.Copy(texture, rect1, rect2)`.

This makes me wonder if there's a way for my game object to hold a texture containing a rect, circle, or triangle texture. I couldn't find in the SDL wiki or tutorials online.

# Answer
> 2 votes
I wouldn't suggest rendering shapes to textures, you'll probably get better performance & cleaner code if you just support rendering shapes in your renderer wrapper class.

However, here's how you would render shapes to textures:

You're probably looking for render textures. Use `SDL_CreateTexture` to create render texture (pass in `SDL_TEXTUREACCESS_TARGET` to get a target texture). Pass in the size of the shape you want to render.

Then use `SDL_SetRenderTarget` to bind the render target. After that you can just call `SDL_RenderDrawRect` to draw a rectangle to the render texture you have bound.

If you decide not to go with this approach, you could for an example have your objects return an enum, that tells the rendering function what kind of render call should be used to render the object.

---
Tags: rendering, sdl, geometry, sdl2, rendertexture
---


# Question
Title: Apply a grain effect to all the elements of a level
I'm currently experimenting a little bit on level design. Let's say that I've a room composed of walls and a floor tiles. I'd like to apply to all these elements a sort of "grain" effect, similar to concrete. I wonder which is the better way to go... the only think I can immagine is working with texture directly, so for each element create the texture that already contains the "grain" effect.

I've also tried to apply a generic screen shader but the result is not good because the grain is fixed to the screen, I wanted it to be fixed to walls/floor. Obviously creating all the textures is a long process and I have to keep UV absolutelly proportional for each element.

I'm ok with that solution actually but I wonder if there is anyother way to apply this effect all in once in a simpler and "safer" way, soemthing like a decal that maybe adds also some imperfections.

# Answer
If you are talking about just adding noise there are simple options and a combination of the two.

Either case are simply achieved by **multiplying** the output color with a grey scale value.

How to get this greyscale value?

A: Noise functions

B: Texture sampling

How you sample from either is up to you. You can project from screen space, world space, object position what have you. If you just want it static simply use the uv mapping of your object.

Here is an example : AWSD to move, mouse to look around. Check the simple.frag.glsl tab/file.

You can also combine option A and B and do all sorts of trickery to your liking but the most basic look is done by simply sampling and multiplying. subtracting, adding, didiving whatever suites you.

Snippet for Noise function

```
#version 450

// Uv coordinates
in vec2 vUV;

// In your case the brick texture
uniform sampler2D myTextureSampler;

// our final color data
out vec4 fragColor;

// Noise resolution
float noiseScale = 1000.0;

//-----------------------------
// Noise function
float rand(vec2 n) {
    return fract(sin(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);
}

float noise(vec2 p){
    vec2 ip = floor(p);
    vec2 u = fract(p);
    u = u*u*(3.0-2.0*u);

    float res = mix(
        mix(rand(ip),rand(ip+vec2(1.0,0.0)),u.x),
        mix(rand(ip+vec2(0.0,1.0)),rand(ip+vec2(1.0,1.0)),u.x),u.y);
    return res*res;
}
//------------------------------------------

void main() {

     //Get noise value
    float n = noise(vUV*noiseScale);

    // Get brick texture sample -
    //that is if your texture is a brick texture of course
    vec4 color = texture(myTextureSampler, vUV);

    // Multiply the RGB color of your main texture with the noise
    // Add 0.5 so we at least retain more bright colors
    color.rgb *=n+0.5;

    // Tell OpenGL color is our final result
    fragColor = color;
}

```

Snippet for Texture sampling

```
#version 450

// Uv coordinates
in vec2 vUV;

// In your case the brick texture
uniform sampler2D myTextureSampler;
uniform sampler2D myNoiseSampler;

// our final color data
out vec4 fragColor;

void main() {

    // Get brick texture sample -
    //that is if your texture is a brick texture of course
    // Then get noise sample, just taking green, red and blue would work too.
    vec4 color = texture(myTextureSampler, vUV);
    float n = texture(myNoiseSampler, vUV).g;

    // Multiply the RGB color of your main texture with the noise
    // Add 0.5 so we at least retain more bright colors
    color.rgb *=n+0.5;

    // Tell OpenGL color is our final result
    fragColor = color;
}

```
> 1 votes

---
Tags: shaders, textures, level-design
---


# Question
Title: There is no ".text" member after I type "GUIText"
I want to write a text in game scene... but when I type...

```
void Update() {
     GUIText.t|

```

Then the code completion hints do not offer to complete this "t..." to `GUIText.Text`.

Why is that? And how can I assign text to display in Unity 5.6.4 (64 bit)?

# Answer
> 1 votes
Because you are trying to reference a static member that doesn't exist.

We do not access like this:

```
GUIText.text = "whatever"; //trying to reference a static member that doesn't exist

```

but rather like this:

```
    GUIText guiText = new GUIText(); //have now created an "object" A.K.A. "instance"
//...or otherwise you can drag an "object reference" in via Unity's inspector.
    guiText.text = "whatever"; //now have the "object reference" on which "text" exists

```

Also remember that programming languages are nearly always *case-sensitive*, so you must be careful for example to use `GUIText` and not `GUItext` or `GuiText`. The names must be precise.

---
Tags: unity, c#, gui, monodevelop, code-hinting
---


# Question
Title: Unity:How to realize a modal message box?
I'm developing a simple "modal" MessageBox.

This is the code inside Message Box panel:

```
public void Show(string _title , string _message, bool _showYesButton, bool _showNoButton, bool _showCancelButton) {
    this.gameObject.SetActive (true);
    Title.text = _title;
    Message.text = _message;
    btnYes.SetActive (_showYesButton);
    btnNo.SetActive (_showNoButton);
    btnCancel.SetActive (_showCancelButton);

}

```

And here how I call it outside:

```
MyMessageBoxScript _script = MyMsgBoxGameObject.GetComponent<MyMessageBoxScript >();
_script.Show("Hey..","Are you sure you want to overwrite this save ?",true,true,false);

```

Ok.. the problem is that I can't do a "modal" window, like in .NET version, returning what user pressed.

Something like:

```
buttonPressed = _script.Show("Hey.:", "Are you sure...");

```

So, searching with Google someone use this Way :

```
_script.Show(CallBackFunction; "Hey..","Are you sure you want to overwrite this save ?",true,true,false);

```

and

```
void CallBackFunction () {
...
}

```

**But I can't understand how it works: How to pass CallBackFunction as parameter and how to execute (after clicking: yes,no or cancel) ?**

Thanks

# Answer
Add a parameter to `public void Show` of type `Action`. Action is a delegate-type representing a method with no arguments and a return type of `void`.

You can then add that delegate to the `onClick` event handler of the OK button.

```
public void Show(Action callback, string _title , string _message, bool _showYesButton, bool _showNoButton, bool _showCancelButton) {
    this.gameObject.SetActive (true);
    Title.text = _title;
    Message.text = _message;
    btnYes.SetActive (_showYesButton);
    btnYes.onClick.RemoveAllListeners();  // remove previous callback
    btnYes.onClick.AddListener(callback);  // add the new one
    btnNo.SetActive (_showNoButton);
    btnCancel.SetActive (_showCancelButton);
}

```
> 2 votes

---
Tags: unity, gui
---


# Question
Title: How can you pass a large amount of textures or equivalent to the fragment shader in OpenGL?
I am adding shadow mapping to a game engine I am working on.

For this effect, each light source needs it's own associated shadow map cube texture.

I am going to be exaggerated and say there can be up to 1000 lights in the world at a given time (this would most likely lag the entire thing, but that's not the issue).

This means I need up to 1000 depth maps loaded into the shaders at any one time.

According to:

```
GLint temp;
glGetIntegerv(GL_MAX_TEXTURE_UNITS, &temp);
cout << temp << endl;

```

I have up to 4 texture units available. And the way I am currently passing my shadow maps is:

```
void Shadow_Map::load_to_GPU(GLuint program, GLuint index)
{
    glUseProgram(program);
    glActiveTexture(GL_TEXTURE0+index+1);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

    string name = "depth_maps[" + to_string(index) + "]";

    GLint loc = glGetUniformLocation(program, name.c_str());
    if(loc == GL_INVALID_VALUE || loc==GL_INVALID_OPERATION)
    {
        cerr << "Error returned when trying to find depth_map uniform."
             << endl;
        return;
    }

    glUniform1i(loc,1+index);
}

```

So under my current methods I am very far away from the amount of depth map cube textures I need to use. Is there a better way to pass a large amount of cubicTextures, or what other techinique could I use to be able to handle large amounts of point lights?

# Answer
I would use a Cube Map Texture Array for this. You can query the maximum array texture layers with:

```
GLuint max_layers;
glGetIntegerv (GL_MAX_ARRAY_TEXTURE_LAYERS, &max_layers);

```

E.g. my implementation (NVIDIA) returns 2048. Your mileage may vary with others.

I am raising my eyebrow slightly at the need for so many light sources. It seems a little excessive.

As DMGregory mentions, deferred shading is a preferred solution for many light sources, however even there you aren't going to generate a unique shadow map for each. It's not trivial to implement well either.
> 2 votes

---
Tags: opengl, shaders, fragment-shader, shadows, shadow-mapping
---


# Question
Title: Diagonal symmetry across a filtered array?
I wrote this code to randomly generate a square terrain that somewhat resembles an island. First, I randomly populated a square with grass tiles (1s) on a plane of water tiles (0s):

Then, I looped through each tile and changed its tile type according to its neighboring tiles(if a tile is surrounded by 4 or more water tiles, it becomes a water tile, otherwise it becomes a grass tile):

The results don't seem all that pleasing; not only is the terrain filled with holes and lack overall "togetherness", it is also weirdly symmetrical diagonally.

Here's the code:

```
private void SmoothMap (Chunk chunk)
{
    for(int row = 1; row < chunk.rows-1; row++)
    {
        for(int col = 1; col < chunk.cols-1; col++)
        {
            //if current tile is not null
            if(chunk.GetTile(row, col) != null)
            {
                //Check its neighboring tiles
                int neighboringTiles = GetSurroundingTiles(row, col, chunk);
                //System.out.println("Position: " + row + ", " + col);
                //System.out.println("Current tile type: " + chunk.GetTile(row, col).type);
                //System.out.println("Neighboring water tiles: " + neighboringTiles);

                if (neighboringTiles > 4)
                {
                    if (chunk.GetTile(row, col) != null)
                    {
                        chunk.GetTile(row, col).texture = GetRandomWaterTexture();
                        chunk.GetTile(row, col).type = Enums.tileType.Water;
                    }
                }
                else if (neighboringTiles < 4)
                {
                    if (chunk.GetTile(row, col) != null)
                    {
                        chunk.GetTile(row, col).texture = GetRandomGrassTexture();
                        chunk.GetTile(row, col).type = Enums.tileType.Grass;
                    }
                }
            }
        }
    }
}

private int GetSurroundingTiles(int r, int c, Chunk chunk)
{
    int surroundingTiles = 0;

    for(int x = c-1; x <= c+1; x++)
    {
        for(int y = r-1; y <= r+1; y++)
        {
            if (x != c || y != r)
            {
                if(chunk.GetTile(x, y) != null)
                {
                    if (chunk.GetTileCode(x, y).equals("0"))
                    {
                        surroundingTiles++;
                    }
                }
            }
        }
    }
    return surroundingTiles;
}

```

Does anyone know why it is the way it is? Or a better way to approach generating an terrain like this?

Here's the GetTile() code:

```
public String GetTileCode(int r, int c)
{
    Tile tile;
    ArrayList<Tile> chunk_row;
    if(tiles.size() > r && r >= 0){
        chunk_row = tiles.get(r);

        if(chunk_row != null && chunk_row.size() > c && c >= 0){
            tile = chunk_row.get(c);
            return tile.isGrass() ? "1" : "0";
        }
    }
    return "0";
}

```

1 is grass, and 0 is water.

# Answer
> 3 votes
You are writing to the same array you are reading from - that's what causes diagonal symmetry. Problem is you can't sample correctly if you have already begun to change the array you are sampling from! You must have a copy of the tiles array in order to avoid this. Write into a fresh/clear array, then copy contents over from it after you are finished smoothing. Here is code that works:

```
public struct Tile //struct allows copy. We need this for copying to and fro from tiles to tilesSmoothed.
{
    public bool isLand;
    public string somethingElse;
}

public class Main : MonoBehaviour
{
    public const int ROWS = 50;
    public const int COLS = 50;

    Tile[,] tiles = new Tile[COLS, ROWS];
    Tile[,] tilesSmoothed = new Tile[COLS, ROWS];
    GameObject[,] tileGOs = new GameObject[COLS, ROWS];

    void Start ()
    {
        for (int x = 0; x < COLS; x++)
        {
            for (int y = 0; y < ROWS; y++)
            {
                //data model
                tiles[x,y] = new Tile();
                tiles[x,y].isLand = Random.Range(0.0f, 1.0f) >= 0.5f ? true : false;

                //tilesSmoothed[x,y] = new Tile(); //unnecessary - all structs are initialised to zero / false

                //view
                tileGOs[x,y] = GameObject.CreatePrimitive(PrimitiveType.Cube);
                tileGOs[x,y].transform.position = new Vector3(x, y, 0);
                tileGOs[x,y].SetActive(tiles[x,y].isLand);
            }
        }
    }

    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            SmoothMap();
        }
    }

    private void SmoothMap()
    {
        //1st loop populates tilesSmoothed
        for (int x = 1; x < COLS-1; x++)
        {
            for (int y = 1; y < ROWS-1; y++)
            {
                //if current tile is not null
                if (tiles[x,y].isLand)
                {
                    //Check its neighboring tiles
                    int neighbourCount = CountNeighbourTiles(x, y);
                    tilesSmoothed[x,y].isLand = neighbourCount > 4;
                }
            }
        }

        //2nd loop copies those results from tilesSmoothed into tiles
        for (int x = 0; x < COLS; x++)
        {
            for (int y = 0; y < ROWS; y++)
            {
                //model
                tiles[x,y].isLand = tilesSmoothed[x,y].isLand; //COPY!
                //remember to also clear tilesSmoothed[x,y] here if you like, but for now this is not req'd.

                //view
                tileGOs[x,y].SetActive(tiles[x,y].isLand);
            }
        }
    }

    private int CountNeighbourTiles(int x, int y)
    {
        int count = 0;

        for (int nx = x-1; nx < x+1+1; nx++)
        {
            for (int ny = y-1; ny < y+1+1; ny++)
            {
                //if (x != c || y != r) //this is not required and is costly - see return line below
                //{
                if (tiles[nx,ny].isLand)
                {
                    count++;
                }
                //}
            }
        }
        return count - 1; //you can assume -1 since the current tile must be valid and was definitely counted
    }
}

```

As for your approach to smoothing...

`SmoothMap` should probably handle cases where e.g. we are surrounded by 3 tiles (checking horizontally and vertically, the count goes up to 4; checking diagonally, the number can go up to 8). You can either count the total surrounding valid tiles and act accordingly, or act on them according to structure, such as look at who is adjacent to who, e.g. 2 in the top right and 3 in the bottom left - neither group touching the other. None of this is essential to solving your main problem which is symmetry, but it will help with smoothing if implemented well. I've changed your `GetSurroundingTiles` to be subtly more efficient.

What you're doing here is a 3x3 box filter which is a sound and common approach. For a smoother map, you must increase the resolution of the grid, i.e. increase the values of `ROWS` & `COLS`.

**As a lesson to take from this, remember always to reduce your code down to the most basic thing that works, in order to solve mind-numbing problems.**

---
Tags: java, libgdx, procedural-generation, grid, filtering
---


title: Change color of selected polygons

text:
# Question
Title: Change color of selected polygons
I have a "low poly" surface, where the color palette for polygons is low (e.g. 20 distinct colors). Is there a way to change the color (with a smooth transition) for all polygons painted with a certain color?

Maybe an analogy would be to smoothly make all polygons of a certain color transparent..

*Background:*

I have managed to get a 2D variant working: load a bitmap on a canvas and use a shader to change the color.

# Answer
I'd be tempted to do this like so:

1. With each vertex, store a single numeric texture coordinate which will serve as your index into your colour palette (ie. "this vertex should be painted in colour 0, that one should be painted in colour 17")
2. In your vertex shader, use this index to look up the colour from either a palette texture (where each pixel is 1 palette entry) or an array of colour uniforms. Pass this colour to the fragment shader to draw to the screen.
3. To gradually change the colour in one or more palette entries, you can...

* **with a palette texture:** write multiple rows into your palette, where row 1 is the first version of the palette, row 2 is the second version, etc...

    Use a uniform to select which palette to read from. Use Material.SetFloat() to gradually vary that uniform between two adjacent rows, using texture filtering to blend between any colour palette entries that are different on the two rows.
    * **with an array of colour uniforms:** use Material.SetColorArray() to update your array each frame as you vary the colours.
> 1 votes

---
Tags: unity, 3d
---


# Question
Title: Is there a way to make it easy to add new content to my game without much effort ?
Good evening !

Im currently developing an little "mmorpg" on my own. I started some months ago and i noticed that its pretty hard to add new content or features to it due to the complexity of the code, structre and the framework. Let me give your an little example...

In my game, players can build stuff. So theres a base class called "BaseEntity". It will be used for all entity related stuff, buildings, resources, duengongs and so on. Theres also a "BuildingEntity" which extends "BaseEntity" and a "TowerEntity" which extends "BuildingsEntity". So all in all this makes it very easy to add new Buildings to my game without writing the same base class ever and every again.

But there problems too. In many places i need to check if the "GameObject" holds an certain Class as a Component. For example, when my player clicks on the tower, i need to check if theres a building script assigned to it. And when i create new "branches" i need to add those to my existing codes every and ever again. This makes it very complicated at some point.

Are there any structures or tricks to make adding new content to a game much more easier ?

# Answer
> 4 votes
Unity already has a concept of "BaseEntity" - it's called a `GameObject`.

A "BuildingEntity" can be a `GameObject` with a `Building` component attached.

Rather than deriving "TowerEntity" from "BuildingEntity," see if it can be reduced to just the features it adds beyond the normal `Building`. For instance, if it's a watchtower with an attack like in an RTS game, maybe it's just a `GameObject` with a `Building`, `Health`, `Faction`, and `TurretAttack` component on it. You can re-use those `Health`, `Faction`, and `TurretAttack` components on a creature instead of a building to make an enemy that holds its ground and uses ranged attacks on nearby foes.

Maybe you have shop buildings too. Instead of a ShopEntity subclass of BuildingEntity, you could just have a `GameObject` with a `Building` and `Shop` scripts attached. Meanwhile, a roaming merchant character can also use the same `Shop` script.

This idea of breaking down your behaviours into modular chunks of functionality you can freely mix and match is called Composition Over Inheritance, and it's a style that component-based systems like Unity encourage. It helps us avoid encoding "is-a" relationships rigidly in code, and frees content creators to create new types of content by combining & reconfiguring existing behaviour chunks.

Once you have a good set of building blocks, new content can be defined in data: "This brand new enemy type? It's all the same building blocks as that old enemy, but with less health, higher speed, and the `ExplodeOnDeath` behaviour we used for the exploding barrels, so players are challenged to stop it before it gets too close."

And because each piece of content is self-contained, your old scripts (usually) don't need to get more complicated as you add new behaviours. eg. Each behaviour that does damage doesn't need to know how to damage a `BuildingEntity` and `CreatureEntity` and `PropEntity` and your brand new `SwitchEntity` \- it just needs to know how to damage an object with `Health` and you can ensure all those types have that component attached.

You don't strictly have to work in this composition-focused way, but it's a methodology that was developed specifically to address the concern you raised: adding more content to a game flexibly, minimizing complexity bottlenecks.

---
Tags: unity
---


title: Divert gameobject around mesh surface

text:
# Question
Title: Divert gameobject around mesh surface
I am trying to find a way to divert a vector3 position around the surface of a mesh which doesn't have a collider. I have a function (found online) that calculates the closest position on the surface of the mesh but it only works if the position is outside the mesh.

In the diagram below, the red arrow represents whats currently happening. It works great when it's outside the mesh and will give a position on the surface of the mesh, but once it moves forward and enters the mesh, it just keeps walking straight. The green line shows what i would like to happen.

# Answer
> 1 votes
With a collider attached to the object, we can use a method like this to skim along its surface:

```
void MoveAroundObstacle(
                Vector3 destination,
                float speed,
                Collider obstacle,
                float bufferRadius) {

     // How far can we move this frame?
    float range = speed * Time.deltaTime;

    if(obstacle != null) {
        // Check if we hit the obstacle on this move.
        Vector3 direction = destination - transform.position;
        Ray ray = new Ray(transform.position, direction);
        RaycastHit hit;
        if(obstacle.Raycast(ray, out hit, range + bufferRadius)) {
            direction = direction.normalized;

            // Project the direction we want to go onto the surface.
            Vector3 parallel = direction
                             - Vector3.Dot(hit.normal, direction) * hit.normal;

            // Ensure we have a sensible unit vector parallel to the surface.
            if(Mathf.Approximately(parallel.sqrMagnitude, 0f)) {
                 parallel = Quaternion.LookRotation(hit.normal) * Vector3.right;
            } else {
                 parallel = parallel.normalized;
            }

            // Divvy-up our movement for the frame between movement toward the destination,
            // and movement along the surface in the closest direction available.
            float forwardMovement = hit.distance - bufferRadius;
            float sidewaysMovement = Mathf.Max(range - Mathf.Abs(forwardMovement), 0f);

            // Make the move.
            transform.Translate(
                      forwardMovement * direction
                    + sidewaysMovement * parallel,
                      Space.World);
            return;
        }
    }

    // No obstacle in range. Let's use our full movement to travel toward the destination.
    transform.position = Vector3.MoveTowards(
                              transform.position,
                              destination,
                              range);
}

```

Some things to note:

* a `bufferRadius` greater than zero helps keep our object from penetrating into the obstacle visually, and also helps keep our raycast start point slightly outside the object, so we never miss it by starting our scan from inside its skin already.
* this method uses naive hill-climbing based on the current closest intersection point alone - it doesn't know anything about the global structure of the shape. If the object is mostly convex, this shouldn't pose a problem. But if it has a valley or divot exactly opposite the destination, this following logic can get stuck there.

(From one side of the valley, it looks like descending deeper into the valley brings us closer to the destination, so we descend until we start to climb the far side, at which point it looks like the closest path to the destination is to turn around and go back down into the valley)
* This method fires just one ray, assuming that the overall surface behaviour in this region will be well represented by a single ray hit. ie. It posits that the collider doesn't have extremely small crevices & sharp corners that might give a misleading result. The buffer radius gives us some protection against these issues, but it's not bulletproof.

If you need a more robust result, you can use a SphereCast or other shapecast instead, and fire a secondary cast after computing the move from the first hit to ensure it's not taking us into an adjacent wall.

---
Tags: unity, c#, movement, vector, mesh
---


# Question
Title: How can I sort vertices efficiently in a specific direction (CW/CCW)?
I am trying to triangulate a set of points using a very simple approach where a base vertex is chosen, and then every other vertex is joined to its neighbouring vertex and then back to the base vertex, to create a triangle-fan structure, which creates a solid surface.

The problem with this approach is that in order to triangulate it there is a lot of iterating, and for each triangulation point, it must iterate over the entire list again to find its nearest CW point which is very slow, but works.

```
    for (int i = 1; i < triangulationPoints.Count; i++)
        {
//this method iterates over available which is a copy of triangulationPoints
//and finds the closest vertex with no backtracking
            Vector3 vertex = findClosestVertex(currentVertex, available, ordered);
//...
available.Remove(vertex);
        }

```

Now I'm looking to speed up the algorithm so I get the same effect, but faster.

I implemented a binary insert function that sort each point based on distance from the base vertex as it is inserted into the triangulationPoint list which works nicely and is fast, but produces incorrect results as it doesn't take into account the next CW vertex, but any vertex.

Does anyone have any suggestions as to how I can speed this up, or perhaps another triangulation algorithm that is relatively easy to implement which would achieve fast speeds?

**Edit** I have tried Unity's triangulator and that produces results that are worse than my attempt. I have also tried a third-party triangulator (https://github.com/CiaccoDavide/Unity-UI-Polygon) and this seems to be exactly what I need, however it only draws on the UI and not in world space.

---

An attempt at implementing DMGregory's explanation

```
   Quaternion toPlaneSpace = Quaternion.Inverse(Quaternion.LookRotation(cutter.normal));

    centroidPosition = centroidPosition / sharedIntersectionPoints.Count;

    foreach (Vector3 v in sharedIntersectionPoints)
    {
        Vector3 offset = toPlaneSpace * (v - centroidPosition);

        IntersectionPoint ip = new IntersectionPoint(v, Mathf.Atan2(offset.y, offset.x));

        int index = binaryInsertAngle(new IntersectionPoint(v, Mathf.Atan2(offset.y, offset.x)), 0, points.Count);

        if (index > orderedTriangulationPoints.Count)
        {
            orderedTriangulationPoints.Add(ip.point);
            points.Add(ip);
        }
        else
        {
            orderedTriangulationPoints.Insert(index, ip.point);
            points.Insert(index, ip);
        }
    }

```

Both the new ordered list and the old ordered list are the same size so it should be stepping over the vertices correctly without missing any.

# Answer
1. Iterate over the vertices and store a running average of their positions to compute an estimated `centroid` position.
2. Take your cutting plane and use it to form a quaternion or matrix you can use to transform vectors in the cutting plane back to a standard XY plane. eg:

`Quaternion toPlaneSpace = Quaternion.Inverse(Quaternion.LookRotation(planeNormal));`
3. Iterate over the vertices again and compute the local offset within the plane:

`offset = toPlaneSpace * (vertexPosition - centroid)`
4. Use this `offset`'s `x` and `y` to compute a pseudo-angle.

We could use `pseudoAngle = Mathf.Atan2(y, x)` but this is actually a little heavier-weight than we need. We don't care if it's a true angle, only that it increases monotonically with angle (ie. as we move our `xy` point counter-clockwise about the origin, the value of `pseudoAngle` keeps going up until our wrap-around point - that's enough to let us sort the vertices correctly)

So, if you really want to shave every cycle, you can swap this out for the approximate Atan2 method of your choice.
5. Store your `psuedoAngle` somewhere that you can associate with the vertex, like a parallel array of floats (where the index of the vertex in your collection exactly matches the index of its corresponding `pseudoAngle`
6. Sort your vertex collection by `pseudoAngle`.

This last step dominates the running time at O(n log n), which is still quite reasonable (and beats repeating a search every time we need to pick a new vertex)

Now you can walk the sorted list in order to build your triangles, as long as your polygon is always convex.
> 2 votes

---
Tags: geometry, vertex, sorting, point-cloud, triangulation
---


# Question
Title: Jagged array - check if array index is out of range
Hey I am a bit confused about how to properly check a Jagged array for "index out of range exceptions"

Im quite sure im somehow supposed to use the .Length of the array but it confuses me to read this, because my tiles are of a TileType type (enum):

https://msdn.microsoft.com/en-us/library/system.array.length.aspx

https://stackoverflow.com/questions/37233225/c-sharp-how-can-i-check-if-a-multidimensional-array-has-a-value-and-its-index

https://stackoverflow.com/questions/25562496/how-to-check-if-multidimensional-array-row-contains-non-zero-value

What im doing is creating a grid of tiles and running through them after the fact and setting their values to have a collider (red in this case) if they are in the correct position. In order to do this I have to check the tiles surrounding the one I am currently on. This sometimes, albeit rarely, leads to an index of out range exception because the tile I am on is on the edge of the tile grid and thus it cannot find the tile I am looking for.

Here is a small peice of the code:

```
 void SetTilesValuesForRooms()
{
    // Go through all the rooms...
    for (int i = 0; i < rooms.Length; i++)
    {
        Room currentRoom = rooms[i];

        // ... and for each room go through it's width.
        for (int j = 0; j < currentRoom.roomWidth; j++)
        {
            int xCoord = currentRoom.xPos + j;

            //// For each horizontal tile, go up vertically through the room's height.
            for (int k = 0; k < currentRoom.roomHeight; k++)
            {
                int yCoord = currentRoom.yPos + k;

                // Make the left wall have colliders
                // this line is the culprit
                if (xCoord == currentRoom.xPos && tiles[xCoord - 1][yCoord - 1] == TileType.Wall || tiles[xCoord - 1][yCoord] == TileType.Wall)
                {
                    tiles[xCoord - 1][yCoord - 1] = TileType.Red;

                    if (yCoord == currentRoom.yPos + currentRoom.roomHeight - 1 && tiles[xCoord - 1][yCoord] == TileType.Wall)
                    {
                        tiles[xCoord - 1][yCoord] = TileType.Red;

                        if (tiles[xCoord - 1][yCoord + 1] == TileType.Wall)
                        {
                            tiles[xCoord - 1][yCoord + 1] = TileType.Red;
                        }
                    }
                }

```

Im quite interested to know how I would properly go about checking if the tile I am about to correct is out of range or not.

thank you.

# Answer
Length of Jagged Arrays can be a little weird. Since a jagged array is just an "array of arrays," you need to know if you're asking **"How many arrays do I have?"** vs **"How long is this array?**

If you have a 2D jagged array x\[\]\[\], saying x.Length will give you the number of arrays within x. Calling x\[0\].Length will tell you how long the array at index 0 is. *The contained arrays do not all have to be the same length.*

---

Before we talk about your other question, here are a few quality of life suggestions.

**You're mixing for loops and this gets *VERY* confusing!** Separate your room iteration from your tile iteration. When using generic iterators like i,j,k it's very hard to keep track of which loop vars are which, especially when different vars iterate over different sets. Move the layers to different methods, it makes things easier to read, develop, and bug test.

**For loops don't have to start at 0**: rather than having iterators that are one off variables, turn those into your vars. Rather than having `int xCoord = currentRoom.xPos + j;` write `for(int xCoord = currentRoom.xPos; xCoord < currentRoom.xPos + currentRoom.width; xCoord++)` Saves you a line of code, and allows your code to function as written rather than have a layer of abstraction. This is personal preference, but it keeps the loop code in the loop and the useful code in the body.

**Rather than checking if your answer, write code that can't be wrong**: This isn't always applicable. But try to reduce the amount of possible errors. Best case is 0, but any error you can't create is an edge case you don't have to check.

---

You're implicit question of **how to iterate over tiles in a grid** can be solved in several ways.

You can do a multipass check. This prevents the need for error checking since you can guarantee that you'll never exceed your boundaries, but requires significantly more code. this generally works by writing code blocks for each edge case (and corner case).

It could look like this (if your room is rectangular). If not, just break each edge into it's own method. This (quite literally) removes the edge cases and allows free reign on the inside elements.

```
void checkTopBottom(){

   //check corner values first
   checkCorners(Top);
   checkCorners(Bottom);

   //checks top and bottom edges
   for(int i = 1; i < width-1; i++){
       checkTop(i);
       checkBottom(i);
   }
}

void checkLeftRight() // same as TopBottom but using different direction

void checkGeneral() // standard double for checking everything else

```

---

The easiest, and most compact / maintainable way is to compartmentalize your problem. Check a specific tile's neighbor in its own method. In that method bound your iterators to the array's min/max values. This requires error checking since border tiles will always have at least one wrong tile (equal to the current tile). However 1 error is easier to check than 3.

Here's a rough approach of how I would do it.

```
foreach(var currentRoom in rooms){
   checkRoomTiles(currentRoom);
}

void checkRoomTiles(Room current){
    for(int x = current.xpos; x < current.xpos + current.width;x++){
        for(int y = current.ypos; y < current.ypos + current.height;y++){
            checkSpecificTile(x,y, current);
        }
    }
}

void checkSpecificTile(int x, int y){
   Tile current = tiles[x][y];
   for(int xMod = x-1; xMod <= x+1; xMod++){
      for(int yMod = x-1; yMod <= x+1; yMod++){

         //bounds checking. Ensures node is always within range
         tX = max(tX,0);

         // x length is the length of the array of arrays
         tx = min(tX, tiles.Length-1);

         tY = max(tY,0);

         // y length is the length of the current array
         tY = min(tY, tiles[x].Length-1);

         //checks if the error correction made us reference current
         (if tiles[tX][tY] == current) continue;

         handleTile(tX,tY);
      }
   }
}

```

Don't expect the code to work as written, there's probably errors somewhere. But this should give a general idea.
> 2 votes

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


# Question
Title: Character Movement - Canvas Character - Javascript
How do I change the arrowkey movement so that is based off of the click of the buttons instead?

Cheers

```
<script type="text/javascript">
    var ctx = null;
    var gameMap = [
        0, 0, 0, 0, 0,
        0, 1, 1, 1, 0,
        0, 1, 0, 0, 0,
        0, 1, 1, 1, 0,
        0, 0, 0, 0, 0
    ];
    var tileW = 40, tileH = 40;
    var mapW = 5, mapH = 5;
    var currentSecond = 0, frameCount = 0, framesLastSecond = 0, lastFrameTime = 0;

 new tile
    var keysDown = {
        37: false,
        38: false,
        39: false,
        40: false
    };

    var player = new Character();

    function Character() {
        this.tileFrom = [1, 1];
        this.tileTo = [1, 1];
        this.timeMoved = 0;
        this.dimensions = [30, 30];
        this.position = [45, 45];
        this.delayMove = 700;
    }
    Character.prototype.placeAt = function (x, y) {
        this.tileFrom = [x, y];
        this.tileTo = [x, y];
        this.position = [((tileW * x) + ((tileW - this.dimensions[0]) / 2)),
        ((tileH * y) + ((tileH - this.dimensions[1]) / 2))];
    };
    Character.prototype.processMovement = function (t) {
        if (this.tileFrom[0] == this.tileTo[0] && this.tileFrom[1] == this.tileTo[1]) { return false; }

        if ((t - this.timeMoved) >= this.delayMove) {
            this.placeAt(this.tileTo[0], this.tileTo[1]);
        }
        else {
            this.position[0] = (this.tileFrom[0] * tileW) + ((tileW - this.dimensions[0]) / 2);
            this.position[1] = (this.tileFrom[1] * tileH) + ((tileH - this.dimensions[1]) / 2);

            if (this.tileTo[0] != this.tileFrom[0]) {
                var diff = (tileW / this.delayMove) * (t - this.timeMoved);
                this.position[0] += (this.tileTo[0] < this.tileFrom[0] ? 0 - diff : diff);
            }
            if (this.tileTo[1] != this.tileFrom[1]) {
                var diff = (tileH / this.delayMove) * (t - this.timeMoved);
                this.position[1] += (this.tileTo[1] < this.tileFrom[1] ? 0 - diff : diff);
            }

            this.position[0] = Math.round(this.position[0]);
            this.position[1] = Math.round(this.position[1]);
        }

        return true;
    }

    function toIndex(x, y) {
        return ((y * mapW) + x);
    }

    window.onload = function () {
        ctx = document.getElementById('game').getContext("2d");
        requestAnimationFrame(drawGame);
        ctx.font = "bold 10pt sans-serif";

        window.addEventListener("keydown", function (e) {
            if (e.keyCode >= 37 && e.keyCode <= 40) { keysDown[e.keyCode] = true; }
        });
        window.addEventListener("keyup", function (e) {
            if (e.keyCode >= 37 && e.keyCode <= 40) { keysDown[e.keyCode] = false; }
        });
    };

    function drawGame() {
        if (ctx == null) { return; }

        var currentFrameTime = Date.now();
        var timeElapsed = currentFrameTime - lastFrameTime;

        var sec = Math.floor(Date.now() / 1000);
        if (sec != currentSecond) {
            currentSecond = sec;
            framesLastSecond = frameCount;
            frameCount = 1;
        }
        else { frameCount++; }

        if (!player.processMovement(currentFrameTime)) {
            if (keysDown[38] && player.tileFrom[1] > 0 && gameMap[toIndex(player.tileFrom[0], player.tileFrom[1] - 1)] == 1) { player.tileTo[1] -= 1; }
            else if (keysDown[40] && player.tileFrom[1] < (mapH - 1) && gameMap[toIndex(player.tileFrom[0], player.tileFrom[1] + 1)] == 1) { player.tileTo[1] += 1; }
            else if (keysDown[37] && player.tileFrom[0] > 0 && gameMap[toIndex(player.tileFrom[0] - 1, player.tileFrom[1])] == 1) { player.tileTo[0] -= 1; }
            else if (keysDown[39] && player.tileFrom[0] < (mapW - 1) && gameMap[toIndex(player.tileFrom[0] + 1, player.tileFrom[1])] == 1) { player.tileTo[0] += 1; }

            if (player.tileFrom[0] != player.tileTo[0] || player.tileFrom[1] != player.tileTo[1]) { player.timeMoved = currentFrameTime; }
        }

        for (var y = 0; y < mapH; ++y) {
            for (var x = 0; x < mapW; ++x) {
                switch (gameMap[((y * mapW) + x)]) {
                    case 0:
                        ctx.fillStyle = "#685b48";
                        break;
                    default:
                        ctx.fillStyle = "#5aa457";
                }

                ctx.fillRect(x * tileW, y * tileH, tileW, tileH);
            }
        }

        ctx.fillStyle = "#0000ff";
        ctx.fillRect(player.position[0], player.position[1],
            player.dimensions[0], player.dimensions[1]);

        ctx.fillStyle = "#ff0000";
        ctx.fillText("FPS: " + framesLastSecond, 10, 20);

        lastFrameTime = currentFrameTime;
        requestAnimationFrame(drawGame);
    }
</script>

```

```
<canvas id="game" width="400" height="400"></canvas>
<table>
    <tr>
        <td></td>
        <td>
            <button id="NORTH" onclick="NORTH()">NORTH</button>
        </td>
        <td></td>
    </tr>

    <tr>
        <td>
            <button id="WEST" onclick="WEST()">WEST</button>
        </td>
        <td></td>
        <td>
            <button id="EAST" onclick="EAST()">EAST</button>
        </td>
    </tr>

    <tr>
        <td></td>
        <td>
            <button id="SOUTH" onclick="SOUTH()">SOUTH</button>
        </td>
        <td></td>
    </tr>
</table>

```

# Answer
> 1 votes
This should be doable by attaching click events to the buttons and saving which one was clicked, then resetting it.

First remove the `onclick=` occurences from your html. They currently don't work because there is no global NORTH/EAST/SOUTH/WEST functions defined.

Next, define an object in which you can store the direction that the user clicked.

```
var movementState = {
      east: false,
      north: false,
      south: false,
      west: false
    };

```

After that, in the window.onload callback, instead of binding to `keydown` and `keyup` you want to bind an event to the buttons:

```
document.getElementById('NORTH').addEventListener('click', function(e) {
    movementState.north = true;
});

document.getElementById('EAST').addEventListener('click', function(e) {
    movementState.east = true;
});

document.getElementById('SOUTH').addEventListener('click', function(e) {
    movementState.south = true;
});

document.getElementById('WEST').addEventListener('click', function(e) {
    movementState.west = true;
});

```

Lastly, you'll want to alter the `drawGame` function. Specifically the part where `keysDown` is used to determine where the player should move.

```
    if (!player.processMovement(currentFrameTime)) {
    if (movementState.north && player.tileFrom[1] > 0 && gameMap[toIndex(player.tileFrom[0], player.tileFrom[1] - 1)] == 1) { player.tileTo[1] -= 1; movementState.north = false; }
    else if (movementState.south && player.tileFrom[1] < (mapH - 1) && gameMap[toIndex(player.tileFrom[0], player.tileFrom[1] + 1)] == 1) { player.tileTo[1] += 1; movementState.south = false; }
    else if (movementState.west && player.tileFrom[0] > 0 && gameMap[toIndex(player.tileFrom[0] - 1, player.tileFrom[1])] == 1) { player.tileTo[0] -= 1; movementState.west = false;}
    else if (movementState.east && player.tileFrom[0] < (mapW - 1) && gameMap[toIndex(player.tileFrom[0] + 1, player.tileFrom[1])] == 1) { player.tileTo[0] += 1; movementState.east = false; }

    if (player.tileFrom[0] != player.tileTo[0] || player.tileFrom[1] != player.tileTo[1]) { player.timeMoved = currentFrameTime; }
}

```

Now you can clean up all occurrences of `keysDown`. An implementation can be found at https://jsfiddle.net/9bdgxfdo/9/

---
Tags: javascript, movement, character
---


title: How to access files in Chrome

text:
# Question
Title: How to access files in Chrome
So, I am making a game-like html file that needs to load a few assets. I have a loading animation which uses the timing of the loading files to create a progress bar. This all goes fine. The files all load, and the app launches. However, none of the files can access each other as they are all in different `script` tags. And I cannot merge them because the JS is never actually put into the html. So what I need to do is to access the local file system (it uses the `file://` prototype) and read the file, then stick the text into a script tag. However, all of the examples I have found on the web throw this error:

> Xhtmlrequests can only access (list of protocols not including `file`)

What I need is a JS way to access the files with no input from the user (other than opening the application). How can this be done?

# Answer
> 1 votes
First, to explain the problem you ran into trying to access file://:

The user's file system is not directly accessible from any normal browser environment for security reasons. If you would be able to pull any file from a user's computer into javascript everyone's data would've already been made public :)

Now, first ask yourself the question: Is it absolutely necessary to show a progress bar? How big a file are we talking about here? As long as everything loads within a second or two users are usually fine with waiting.

As long as you indicate that the page is loading somehow the user will generally not mind waiting. Just think about how many games you know of that actually show a progress bar instead of a generic "loading" message.

Either way, you probably want to run your game from a webserver, put the scripts in dedicated .js files (if you didn't already do so) and load everything you need with ajax (XMLHttpRequest) calls.

The biggest source of waiting is normally your media files, scripts are likely to only be a small percentage of your overall package, in size.

For a rough progress estimate you could probably divide the amount of files to load by the ones already loaded.

I would recommend reading through at least the first two steps of https://phaser.io/tutorials/getting-started for the webserver part. Even if it isn't directly related to your problem it should still give you a clear idea of how to go about configuring a webserver and solving your problem.

# Answer
> 0 votes
I found a way to do this. It's not very honest, but whatever. So, when the page loads, the mechanism to load the files loads them, then unloads them while still updating the progress bar. Then, when it's done, it loads a highly packed file that contains all of the scripts that are needed. This is not a good thing if someone finds out about this as they would be ticked that their computer is loading the resources twice.

---
Tags: javascript, html5, filesystem
---


# Question
Title: Ideas for fair travelling system for text based RPGs
I'm working on a text RPG (in principle similar to cantr.net) that allows players to role-play their characters in a player-driven world. Players form cities, societies and so on. Pretty much nothing is predetermined for them including currency, etc.

The thing I'm struggling with is how to strike a balance between "pro" players that are logged in nearly 24/7 and more casual players that would like to log in once a day/two days. Most of the systems already take that into account and I'm fairly happy with them, but I'm struggling with creating traveling system that would be fair both ways.

Currently for crafting and other things I'm using "energy" points that are capped at X number and regenerate Y number per hour (basically it regenerates every three real-life days so allows for some catch-up if you miss a day or two). Could it be applied somehow to traveling? What are your ideas?

The world is a flat surface with x/y coordinates the "locations" are just specific points on a map that users can go to and while in the same "location" they can interact with each other. Kinda like Fallout 1 map. I was thinking of allowing movement of X units per 1 energy + some bonuses if vehicles/horse is used.

Let's assume this situation: a thief steals something in a town and starts to run. The game shouldn't require the guards (which are player characters) to be online 24/7 to be able to catch up. They need to have some form of slack or catch-up mechanic to be able to compete, but the thief shouldn't be severely punished by that either. I don't want to force guards to be online too much but at the same time I'm trying not to create a situation where guard characters can just talk freely and "don't give a shit" for a day and then go and chase because they know they will catch him easily.

What are your thoughts on this?

EDIT: As requested I'm going to include a bit of more context here. The game itself has no goals, quests or really any "purpose". All that I need to provide is a world and mechanics that allow player characters to craft, fight and live in a sandbox world and do whatever they wish. Players are "role-playing" in the Dungeon & Dragons sense - they actually have to play and talk from the perspective of their character.

But since I can't expect players to be logged in 24/7 I need to create a fair (or close) system with respect for players' time.

The biggest problem I have is with travel. Not travel per se but chasing mostly. How not to require constant logging in and checking if something happened, allow to catch up to someone who logged in earlier/in different timezone but give the chance to escape as well.

I was thinking about energy points (so players would have to strategize and leave some "just in case") and using something like Tracking skill which would influence how well one character can find another character in travel.

# Answer
I am afraid Phillip in the comments is right, but I have some thoughts I am going to share...

Is the game expecting the player to always chase the thief? If yes, I would slow down the 'escape' speed and speed up the 'chase' speed. It is harder to run when you are carrying a bunch of other people's stuff, right? This could potentially make a fun mini-game of choosing the right target.

Is the game wanting the person to simply get revenge? If yes, I would introduce a bounty system. The player wouldn't need to be the one to chase at that point. The thief would simply be a wanted person until someone gets the player's stuff back. If the thief keeps stealing, eventually the reward for taking him down would be quite enticing. You would want to make sure that the player who was stolen from was notified when the thief was caught.

If the option to chase the thief is basically a side quest, perhaps you can send sightings of the thief to the victim? Then, the player could decide now or later if the chase is worth it. Perhaps even much later in the game! For example, they decide to not worry about the theft, but a month later they get an update that the thief was spotted not so far away. Well, if the 'chase' is a short one... that might change things!

The concept sounds fun. If you update your post to flesh out the mechanics, I am sure others will give more insight!
> 1 votes

---
Tags: game-design
---


# Question
Title: How to stop the RotateAround function to rotate after Keypress in Unity
I have a camera follow script and I am rotating the camera with Q and E key to right and left. The `Camera` is a child of a `camHolder` object. I came up with this code, which rotates around the player to the right and left, but it's shaking as it tries to keep rotating around the player.

I didn't come up with a solution to stop the `RotateAround` function, instead I tried setting `rotateSpeed` to `0` after I let go of the key, but that didn't work either.

---

```
public Transform player;
public float smoothSpeed = 0.125f;
public float rotateSpeed;
private Vector3 velocity = Vector3.zero;

[SerializeField]
private Vector3 offset;

[Space]
public Transform camHolder;

void LateUpdate ()
{
    CameraFollowPlayer();
}

void Update()
{
    RotateCamera();
}

void CameraFollowPlayer()
{
    camHolder.position = Vector3.SmoothDamp(transform.position, player.position + offset,
                                             ref velocity, smoothSpeed * Time.deltaTime);
    transform.LookAt(player.position);
}

void RotateCamera()
{
    if(Input.GetKey (KeyCode.E))
    {
        rotateSpeed += 20f;
        if(rotateSpeed >= 20f)
        {
            rotateSpeed = 20f;
        transform.RotateAround(player.position, transform.up, rotateSpeed * Time.deltaTime);
        }
    }
    else
    {
        rotateSpeed = 0f;
    }

    if(Input.GetKey (KeyCode.Q))
    {
        rotateSpeed += 20f;
        if(rotateSpeed >= 20f)
        {
            rotateSpeed = 20f;
            transform.RotateAround(player.position, transform.up, -rotateSpeed * Time.deltaTime);
        }
    }
    else
    {
        rotateSpeed = 0f;
    }
}

```

# Answer
> 1 votes
You should not be rotating the same transform in both `Update()` and `LateUpdate()`, as they *will* conflict and you *will* see shaking / juddering, since you're telling it be one angle and then immediately you're telling it to be something else. You should probably(?) be managing the `camHolder` in one function, and the `camera` (which is `this.transform`) in the other function.

(I'm not really sure why you use `Update()` and `LateUpdate()` anyway, I would just use one.)

I'd start with this:

```
if (rotateSpeed == 0.0f)
   transform.LookAt(player.position);

```

This works fine for me:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform player;
    public float smoothSpeed = 0.125f;
    public float rotateSpeed;
    private Vector3 velocity = Vector3.zero;

    [SerializeField]
    private Vector3 offset;

    [Space]
    public Transform camHolder;

    void Update()
    {
        RotateCamera();

        CameraFollowPlayer();
    }

    void CameraFollowPlayer()
    {
        camHolder.position = Vector3.SmoothDamp(transform.position, player.position + offset,
                                                 ref velocity, smoothSpeed * Time.deltaTime);
        //transform.LookAt(player.position);
    }

    void RotateCamera()
    {
        if(Input.GetKey (KeyCode.E))
        {
            rotateSpeed += 20f;
            if(rotateSpeed >= 20f)
            {
                rotateSpeed = 20f;
            transform.RotateAround(player.position, transform.up, rotateSpeed * Time.deltaTime);
            }
        }
        else
        {
            rotateSpeed = 0f;
        }

        if(Input.GetKey (KeyCode.Q))
        {
            rotateSpeed += 20f;
            if(rotateSpeed >= 20f)
            {
                rotateSpeed = 20f;
                transform.RotateAround(player.position, transform.up, -rotateSpeed * Time.deltaTime);
            }
        }
        else
        {
            rotateSpeed = 0f;
        }
    }
}

```

---
Tags: unity, c#, camera, rotation
---


# Question
Title: How to handle Entity Initialisation and Destruction
I've been using the ECS pattern for a while now and, as the complexity of the game increased, I started having issues with the timing of the entity initialisation and destruction code.

I'll use the Physics as the example, but the same principles apply to most other aspects as well.

First a few definitions:

* PhysicsModule - the low level physics system (usually an external library like box2d) - has no idea about ECS
* PhysicsSystem - an ECS system - works as an iterface between the low-level module and the rest of the ECS
* EntityWorld - the object responsible for creating and destroying entities and associating them to Systems

For example, a typical scenario goes like this:

* 1) An Entity gets created from external data (Transform, ShapeData, CollidableData)
* 2) The data has to be registered with the PhysicsModule (using ShapeData and CollidableData)
* 3) Every frame, the PhysicsSystem asks the PhysicsModule for the position of the related object and updates the Transform. Repeat for a while.
* 4) The Entity gets destroyed in another System far a way
* 5) The PhysicsModule needs to be told to remove the associated physics object

The problematic steps are 2) and 5). I can think of two ways of handling this.

---

## Have the PhysicsSystem handle the lifecycle.

Pros:

* the logic is encapsulated in one System

Cons:

* the PhysicsSystem needs to know about the init data (ShapeData, CollidableData) which is useless after the initial registration with the PhysicsModule
* the EntityWorld has to keep track which entities were freshly added or removed from a system to notify it about them
* the destruction of the entity has to be delayed in order for its components to still be accessible in the same frame
* this approach often causes long chains of events (spanning a couple of frames) which are difficult to follow

In order to make this work, the main loop always ends up being a complete mess to make sure particular inits, updates and destroys are done in the correct order.

---

## Have one place for all the init and destruction code.

Pros:

* the init data is not used beyond the initial registration
* the init / destroy code is in one place
* all the cleanup can be done in one frame in the correct order

Cons:

* this essentially becomes the God Object and knows about everything in the game
* the whole thing probably becomes very cluttered with all the possible permutations
* the destruction of the entity has to be delayed in order for its components to still be accessible in the same frame

---

At the moment my game evolved into the first solution and I'm having quite a few issues so I'm thinking about trying another approach. The second one I mentioned seems a bit better, but it does involve a God Object and from my experience that is a bad way of doing things.

Also, I took a look at various ECS implementations and noticed that some of them have methods to notify systems that entities were added/removed to them and some of them don't - so there's obviously various approaches to this.

My question is - **Is there another way of handling Entity Initialisation and Destruction without resorting to either the God Object or the God Loop?**

# Answer
> 2 votes
This is one of the common problems with ECS architecture: Intersystem communication.

There is no silver bullet solution, and research is ongoing, but common solutions are:

1. Observer patterns. Any change to the entity triggers updates to the observer, which could be the systems in question, or a system relevant abstraction of the entity. Upon destruction, the observer is notified, and consequently removes the entity from it's list of stuff to process and observe.
2. Callbacks. Think of this like an "on destruct" asynchronous behaviour. Requires the entity to have knowledge of the world/engine into which it has been injected. Upon destruction, it calls the callback function, passing itself and the world/engine, and calls something like `engine->removeEntity(this);`
3. Direct Command Object. Any time an entity is to be destroyed, it is not done so directly. Instead, a command is filtered up to the top engine level, which processes the command and calls a remove function on all systems, to remove the entity.

Finally, another option, is to have a single factory with a static collection of entities and components, managing their lifetimes. Systems, then, do not actually store pointers to entities, but an ID, which is used to query the factory. If the ID query returns false, then the system simply removes that entry from it's collection of IDs, and processes the next in line. This completely eliminates the possibility of dangling pointers, but at the cost of being potentially non-cache friendly.

Personally, I use instantiation of direct command classes, as this is something very easily tied into a scripting language, but this has it's own drawbacks.

The best advice I can give, is to experiment with the different approaches above, or combinations of them, and pay mind to considerations such as usability, ability to be scripted, performance, and cache friendliness.

Each approach has drawbacks and benefits, and its highly educational to discover these by yourself, if you aren't on a timescale.

# Answer
> 0 votes
Check this answer from myself in another post where I explain a **messaging system for an ECS** and provide a link to code implementing it.

On the other hand, I don't know what you mean by `God object` exactly, but a **`Factory`** pattern is perfectly fine. Besides centralizing this initialization/destruction of entities, you can avoid the object creation in cases where you create/destroy frequently. I'll explain:

You can create a **pool of entities** and have X instances of each type of entity already created. They are objects that the factory holds internally and nobody else has to know about them **until** they require a new object of that type to the factory. Then, you only need to initialise the entity with the right parameters, but you avoid the memory allocation (expensive) and object construction itself. That's factory's responsibility and users of the factory have no idea nor worries about whether its entity was newly created or reused.

Hope it helps.

---
Tags: architecture, entity-system, entity-component
---


# Question
Title: How do I get the distance between 2 points on an isometric grid?
How do I get the distance between 2 points on an isometric grid? I'm creating a facebook isometric game (in as3), and when I move around a particular type of building, I need to know if it comes within range of another type of structure, for example a tree. I tried taking the grid x,y points for both items, and calculating the x,y from that but it doesn't seem to work.

# Answer
There are a lot of ways to compute distances, every dot product can be used: a looot of ways.

In your case you surely want to compute the distance between the center of the tiles. I take for granted that you know how to compute the center of a tile.

Once you know the position, you can use the Euclidean distance in the canvas' coordinate space (i.e. √\[(x'-x")²+(y'-y")²\]) or the same in tile's coordinate system.

Another option is the Manhattan or taxicab distance: d = |x'-x"|+|y'+y"|; even in this case you can use tile's coordinate or canvas' coordinate.

The last option (after L2 and L1 norm) the L"infinite" norm where d is the max between |x'-x"| and |y'-y"|.

**Lets see the differences:**

The best way to evaluate this norms is to see the shape of a disc.

Given a center, a disc is every point that falls within a fixed distance (however computed).

***Euclidean Norm:***

The disc is a standard circle in the canvas space and an ellipse in tile space

*Euclidean Canvas*

*Euclidean Tile*

While the first one is easier to compute in general (you don't have to go back and forth tile and canvas coords), the second gives a better fill.

The **"Euclidean Tile"** is the norm that is generally considered **the most correct one**.

---

***Taxicab Norm:***

The disc becomes a diamond in canvas coordinate and a sort of rectangle in the tile coordinate (showing how applying the same coordinate changes two times rawly gives the initial result)

*Taxicab Canvas*

*Taxicab Tile*

We can see even this time how the canvas coordinate gives the worst results: this is the price for an easier way to compute distances.

The "Taxicab Tile" gives a reasonable results, quite similar to the "Euclidean Tile", but simply summing the tile coordinate. This is a very popular norm for this kind of problems

---

***L0 Norm:***

Using the max if axial distances, the disc becomes a rectangle and the equivalent diamond in canvas and tile space respectively

*L0 Canvas*

*L0 Tile*

Ok, let's face it: the L0 canvas is horrible.

On the other hand the "L0 Tile" make it sense: it is quite clean and *very* easy to compute. Can be taken into account when playing with slow device and we need to use every clock cycle.

---

**Conclusions**

The norms computed on canvas coordinates give the worst of the results: the two coordinate systems does not match very well so the price to have a easier norm is simply too high.

The Euclidean norm is the better choice but the slower one; The Taxycab norm offer a very good trade off.

The "L0" is the fastest and easier but the price is to have a distance that is a little unrealistic.
> 11 votes

# Answer
I assume you have points `(x1, y1)` and `(x2, y2)`.

The pythagorean distance between them is `sqrt((x1-x2)^2 + (y1-y2)^2)`. Leave out the sqrt if you just need a relative distance.

If you want to find a distance in grid tile units, then simply divide:

`actual_distance/grid_size`.
> 4 votes

# Answer
If you don't need exact distance, but only to check whether your object (x1,y1) is within given range from some point (x2,y2), you don't need sqrt at all. It would be enough to check the following:

(x1-x2)^2 + (y1-y2)^2 \<= range * range

This goes directly from Euclidean distance formula and is very cheap to calculate
> 0 votes

---
Tags: actionscript-3, tiles, isometric
---


# Question
Title: Problem with folder structure and building project in UE4
I created a new C++ project on Unreal Engine 4. After that I close visual studio and ue4 editor. I manually added public and private folders in the source folder. Then I made folders for the player, items, AI and gamemodes.

The problem appears when I create a new class, the files appear in the respective folders but not in the editor. To fix this I open the visual studio project and I press the build solution. I restart the editor and the classes appear in the folder structure.

The real problem starts here. When i double click any class. A new visual studio appears, ue4 shows the progress bar on the bottom right corner with the text "Loading visual studio". After a couple of seconds a new visual studio pops up. A new screen appears saying that the project is opened on another visual studio and now will migrate all info to a temp folder.

Now I can't code because any attempt at using a C++ class by dragging it into the editor viewport instantly crashes UE4.

What am I doing wrong? What is the correct workflow for creating folder structures in UE4? There is no documentation on how to do this properly.

# Answer
> 2 votes
Always create the folders in the Unreal editor by right clicking in the directory tree and selecting New Folder or clicking the green "Add New" bar at the top.

Unreal itself creates the public and private folders, when creating a new asset / actor / function etc. you choose the public or private options.

When you are creating them, click the relevant box but note that only one of the C++ files goes into the folder you clicked. I forget which one but either the header or cpp file **always** goes into the private folder.

The only thing I can suggest is right clicking on any of your folders and choosing the "Fix Up Redirectors In Folder" which should bring up the option to do this for **all** folders which hopefully, will fix your problems.

One other issue is that Visual Studio may need the full location of the files it's using, either by putting them in the #include section (ie "public/items/items.h" or putting them in the included directories from the editor Project settings.

---
Tags: c++, unreal-4, visual-studio
---


title: Integrating Unity physics with Entitas

text:
# Question
Title: Integrating Unity physics with Entitas
I've used Entitas a bit and it appeared to me as a great way of creating clean, modular code. I've seen few examples of games created with this framework, and most of them were puzzles, TD's, simple RPG's, etc. Those made me come to think, that ECS like that is not suitable for games making big use of Unity built-in physics engine. Rigidbody in this case is part of View layer, but it would affect for example "position" component, so we can't say they are really separated. Unity Physics also works at it's own pace, so there is not really a chance for independent Component-System based simulation.

Are there any generally accepted solutions, or if I don't wan't to write my own physics engine, I should give up Entitas?

# Answer
I literally just started looking at Entitas last night so there may be better solutions, but you could do something like the following:

**Create a component to store the collisions**

```
[UniquePrefix("has")]
public class Collisions : IComponent
{
    public List<GameObject> list;
    public bool isInitialized;
}

```

**Create a MonoBehaviour that forwards the relevant physics events to the entity**

```
public class CollisionReporter : MonoBehaviour
{
    public GameEntity Entity;

    private void OnCollisionEnter(Collision other)
    {
        Entity.collisions.list.Add(other.gameObject);
    }
}

```

**Create a system that links collisions entities to gameobjects with the MonoBehaviour above and responds to the collisions**

```
public class CollisionSystem : ReactiveSystem<GameEntity>
{

    private readonly IContext<GameEntity> _context;

    public CollisionSystem(IContext<GameEntity> context) : base(context)
    {
        _context = context;
    }

    protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context)
    {
        return context.CreateCollector(GameMatcher.Collisions);
    }

    protected override bool Filter(GameEntity entity)
    {
        return entity.hasCollisions;
    }

    protected override void Execute(List<GameEntity> entities)
    {
        foreach (var e in entities)
        {
            if (!e.collisions.isInitialized)
            {
                var go = new GameObject();
                go.Link(e, _context);
                // Add and configure RigidBody, Collider, etc.
                var collisionReporter = go.AddComponent<CollisionReporter>();
                collisionReporter.Entity = e;
                e.collisions.isInitialized = true;
            }

            foreach (var other in e.collisions.list)
            {
                // Do whatever collision response you need...
            }

            e.collisions.list.Clear();
        }
    }

}

```
> 3 votes

---
Tags: unity, entity-system, physics-engine
---


# Question
Title: What framerate should I aim for on a mobile phone?
The higher the framerate, the better the game looks, but the faster it drains the battery.

What's a happy medium?

(I'm making a relatively simple 2D game with sprites moving constantly. I want the movement to appear smooth but I know how irritating it is when a simple game sucks your battery dry.)

# Answer
> 7 votes
Your framerate should be as low as looks good, but I think you're in a tough situation if all of your sprites are moving constantly. You should try your absolute hardest to keep a **consistent** framerate; a low, consistent framerate is better than a high but randomly stuttering framerate. Then turn it down until it doesn't look good.

Consider matching the framerate of movies on the big screen: they are only **24 FPS**. But again, they are precisely consistent, which is why people are okay with just 24 FPS.

Alternatively, if your sprites have an animation sequence and that has a FPS value, try matching that or a multiple of it. For example if they animate at 5 frames per second, then maybe try 25 or 30 frames per second so that the sprite animations can be precisely timed and make the game appear more smooth and consistent than it really is.

I think the best option in this case is to try out some framerates and find a good default, and then put a setting in your options menu for the user to be able to turn it up or down according to the user's desired battery life.

# Answer
> 3 votes
It might seem obvious, but aim for whatever the refresh rate of the screen you're using, or a multiple of that, i.e. if the device does 24fps you could do 12fps. But as Ricket says, the ideal thing is to be consistent.

# Answer
> 3 votes
So first off, a disclaimer: I'm a Director at GameBench, and we make tools for measuring mobile app/game performance (frame rate and other metrics) for a lot of major companies (Rovio, Samsung, Seriously, NaturalMotion etc.) I also have a degree in Game Design.

With regards to target frame rates, there's a few answers here that touch a little on some important points (consistency/stability), but here's what I've learned after nearly 5 years of working in mobile game performance:

Lower frame rate definitely saves battery. This is evident through our own testing (which you can confirm at https://data.gamebench.net) and also as we've seen a lot of device manufacturers actually limit the display refresh rate to as low as 52hz as opposed to the standard 60hz commonly used.

On mobile devices in general, you have the option of selecting from the following target frame rates (this is because they are divisors of the max frame rate - 60 FPS):

* 15 FPS
* 30 FPS
* 45 FPS
* 60 FPS
* **90 FPS**
* **120 FPS**

**Note: 90 and 120 FPS are only available on a few (as of writing this, two) devices.**

However, the right target frame rate can only be decided once you have an understanding of the gameplay style and user interaction mechanics you're going to implement.

For a puzzle game where user response times (reactions) or physically realistic animations aren't important, then aim for 15 FPS, the lowest available target. For a fast-paced shooter where users will need quick reaction times, then definitely aim for 60 FPS.

You can completely ignore any advice stating targets like 24 or 25 FPS, and always ensure that when you target a particular frame rate, you stay as close as possible to it during gameplay, or else it will impact the user experience.

All the best, and feel free to reach out if you've got any other mobile performance questions :)

# Answer
> 2 votes
When developing for mobile devices I always aim for 30.

---
Tags: frame-rate, mobile
---


# Question
Title: Objects desync position when speed is not multiple of 10
While finishing up game loop and rendering integration, i made some blocks move back and forth in the x axis to test things out. Their initial positions are as follows:

The first block starts at 0,0(Top-left) and subsequent ones add 40 to both x and y.

Move code

```
s16 speed = 10;

if(block->sprite->position.x >= viewportWidth - block->sprite->width)
{
    block->sprite->position.x = viewportWidth - block->sprite->width;
    block->dir = -1;
}
else if(block->sprite->position.x <= 0)
{
    block->sprite->position.x = 0;
    block->dir = 1;
}

block->sprite->position.x += speed * block->dir;

```

However, if i change the speed to a number not multiple of 10(or using deltaTime to influence the speed), the blocks will de-sync when changin directions, as shown bellow:

Result of using roundf(1000 * deltaTime) as speed

Result of using 13 speed and removing the clamping of position

I thought it was related to me using ints instead of floats for positions, tried to change but no luck. Looking at the game loop update, no block is being left out of any update phase either.

What bit of math an i missing? What causes this?

Thanks.

# Answer
> 0 votes
Your value of movespeed=10 is a special case where each block collides with the wall at the same distance into the wall.

In order to keep your spacing the same, the boxes must each travel a distance of movespeed every frame.

Think of a 1D problem with a single point on a line that goes from 0 to 100. Using your algorithm lets start at P1 = 97 and go through the steps.

P1 = 97 + 10 = 107

Next frame

P1 = 100 - 10 = 90

Since the point was brought back to 100, then you subtract 10, the point traveled 17 in one frame, which makes it desync from other boxes that align more accurately with the wall.

In order to fix the problem, you need to make sure the point always travels the same distance i.e.

If P1 = 97 and you add 10, then P1 = 100 + (100-(97+10)) = 93

Meaning that P1 traveled a distance of 3 towards the wall and then 7 away from the wall for a total of 10.

A way to implements this would be to change the previous lines to the following...

```
block->sprite->position.x = 2*(viewportWidth - block->sprite->width) - (block->sprite->position.x+movespeed);

```

and

```
block->sprite->position.x = -(block->sprite->position.x-movespeed);

```

and include the normal movement code in an else bracket

```
else
{
    block->sprite->position.x += speed * block->dir;
}

```

---
Tags: c++, movement
---


title: Different gameplay throughout game?

text:
# Question
Title: Different gameplay throughout game?
I want to create a top-down rpg kind of game. It doesn't have the turn-based battles, for the most part, as it's more of a puzzle type game with an overarching mystery to solve, with not much action. However, I've been playing with the idea of adding different kinds of gameplay from other genres that mixes well with this top-down perspective, such as Zelda-style melee combat, fast "kill 'em all" shoot 'em up action like Hotline Miami, and stealth like the Metal Gear series.

Lets say I have ten chapters of around two hour length each. The distribution of each gameplay element would, for example, go something like this:

* Chapter 1: regular top-down
* Chapter 2: regular top-down (small stealth segments)
* Chapter 3: Zelda
* Chapter 4: regular top-down (small rpg turn based fight)
* Chapter 5: Metal Gear
* Chapter 6: Hotline Miami (small stealth segments)
* Chapter 7: regular top-down
* Chapter 8: Zelda
* Chapter 9: Hotline Miami
* Chapter 10: mix of Zelda, Hotline Miami, Metal Gear and turn based rpg fight

These gameplay styles fit with the narrative, which would've previously only been cutscenes. The Zelda parts for example are flashbacks to medieval times, where it shows how the evil bad guy was born and how the first few attempts at destroying him went for an order of knights (spoilers: not too well, but they did manage to slay many of the bad guy's monster army and weaken him a bit).

Now, regardless of whether or not you think I could pull something like this off (I have my doubts as well, but that's not the point of the question), could this be a bad idea? Variety is the spice of life after all, but I feel that maybe the player could be overwhelmed or annoyed having to learn different mechanics from different genres. Could it be disruptive to the gaming experience if you suddenly play a different kind of game? Or does it not matter as long as it's integrated well with the rest of the gameplay and story?

# Answer
> 3 votes
The interplay between the game designer and the player is very important. By introducing a piece of gameplay to the player, you're making a promise to the player. In particular, that by investing time in mastering this gameplay, their time will be rewarded. They will be better able to play through the later stages of the game.

By radically shifting gameplay styles for relatively long periods of time, you are reneging on that promise. Whatever time investment they had in your Chapters 1 & 2 is lost for the entire next chapter.

This is different from the case of a game like Mario Party, where there is an up-front expectation that the game is composed of mini-games. This is also different from things like stealth sections of games or mini-games within a game. Those are used simply to break up the monotony; 90+% of your gameplay is still in the style you were using before.

In your case, you have given the player consistent gameplay for a reasonably long period of time, and then you take that away from them. Without up-front notice, I would consider that perfidy.

What you need to do is choose a general gameplay style that can fit into all of your time periods. Different periods would have different weapons, which influences your play styles. But the core root gameplay should still be the same.

For example, consider a top-down perspective, where you move the character with the arrow keys and attack by clicking with the mouse in a particular direction.

Such a system is amenable to multiple styles of combat. Melee-style sections means getting close to targets. Shooter-style sections can involve cover, since you have some control over your locations. You can even do stealth-shooter sections.

But they're all using the same perspective and same core gameplay. Lessons learned in one style map to others. Melee teaches you to avoid getting surrounded, which is also an important skill in shooter sections. Stealth sections teach you how to use terrain, which can be important for shooter sections where you may need cover. And so forth.

While the dynamics of any particular chapter can and should have their own unique flavor, the totality of your game still needs to have reasonably consistent gameplay.

---
Tags: game-design
---