title: Why is my A* algorithm slow?

text:
# Question
Title: Why is my A* algorithm slow?
I made an A\* algorithm, but running it is unbearably slow, even on a 40 x 40 test arena with few obstacles. I've tried changing the unexplored array to exclude nodes in the open list, and although it runs a lot faster, this creates a bug where it doesn't always select the best path.

What am I doing wrong? For what it's worth, I'm running Visual Studio.

---

```
Coordinate* Map::astar(int x1, int y1, int x2, int y2, int size)
{
    Coordinate* return_path;

    if (!passable[x2/24000][y2/24000])
    {
        // return with blank path if target is not passable
        return_path = new Coordinate[1];
        return_path[0].x = -1;
        return_path[0].y = -1;
        return return_path;
    }

    std::vector<Node> open_list;
    std::vector<Node> closed_list;
    Node current_node;
    Coordinate destination;
    Coordinate directions[8];
    directions[0].x = -1;
    directions[0].y = -1;
    directions[1].x = -1;
    directions[1].y = 1;
    directions[2].x = 1;
    directions[2].y = -1;
    directions[3].x = 1;
    directions[3].y = 1; // diagonal directions
    directions[4].x = -1;
    directions[4].y = 0;
    directions[5].x = 0;
    directions[5].y = -1;
    directions[6].x = 0;
    directions[6].y = 1;
    directions[7].x = 1;
    directions[7].y = 0; // straight directions

    // set up unexplored array to quickly sift through explored nodes
    bool** unexplored;
    unexplored = new bool*[xmax];

    for (int i = 0; i < xmax; i++)
    {
        unexplored[i] = new bool[ymax];

        for (int j = 0; j < ymax; j++)
        {
            unexplored[i][j] = true;
        }
    }

    // set starting node and add it to open list
    current_node.loc.x = x1 / 24000;
    current_node.loc.y = y1 / 24000;
    current_node.exactloc.x = x1;
    current_node.exactloc.y = y1;
    current_node.parent.x = current_node.loc.x;
    current_node.parent.y = current_node.loc.y;
    current_node.cost = 0;
    current_node.steps = 1;
    destination.x = x2 / 24000;
    destination.y = y2 / 24000;
    open_list.push_back(current_node);

    // Main loop
    while (!open_list.empty())
    {
        // select the open node with lowest cost + distance
        int best_node;
        int best_cost = -1;

        for (unsigned int i = 0; i < open_list.size(); i++)
        {
            int dx = abs(destination.x - open_list[i].loc.x);
            int dy = abs(destination.y - open_list[i].loc.y);
            int min = (dx > dy) ? dy : dx;
            int distance = (dx + dy) * 1000 - min * 586;
            int total_cost = open_list[i].cost + distance;

            if (total_cost < best_cost || best_cost < 0)
            {
                best_cost = total_cost;
                best_node = i;
            }
        }

        current_node = open_list[best_node];

        // if we are at the destination, construct a path to it
        if (current_node.loc.x == destination.x && current_node.loc.y == destination.y)
        {
            // Path found: add current node to the closed list
            closed_list.push_back(current_node);
            return_path = new Coordinate[current_node.steps + 2];
            return_path[current_node.steps+1].x = -1;
            return_path[current_node.steps+1].y = -1;
            return_path[current_node.steps].x = x2;
            return_path[current_node.steps].y = y2;

            for (int i = current_node.steps - 1; i >= 0; i--)
            {
                unsigned int j;

                for (j = 0; j < closed_list.size(); j++)
                {
                    if (current_node.exactloc.x == closed_list[j].exactloc.x &&
                        current_node.exactloc.y == closed_list[j].exactloc.y)
                    {
                        break;
                    }
                }

                return_path[i] = current_node.exactloc;
                current_node.exactloc = closed_list[j].parent;
            }

            // clean up unexplored array
            for (int i = 0; i < xmax; i++)
            {
                delete[] unexplored[i];
            }

            delete[] unexplored;
            return return_path;
        }

        // remove current node from open list and add to closed
        open_list.erase(open_list.begin() + best_node);
        closed_list.push_back(current_node);
        unexplored[current_node.loc.x][current_node.loc.y] = false;

        // add neighboring nodes to open list
        for (char i = 0; i < 8; i++)
        {
            Node n;
            n.loc.x = current_node.loc.x + directions[i].x;
            n.loc.y = current_node.loc.y + directions[i].y;

            if (i<=3)
            {
                n.cost = current_node.cost + 1414;
            }
            else
            {
                n.cost = current_node.cost + 1000;
            }

            n.steps = current_node.steps + 1;
            n.exactloc.x = n.loc.x * 24000;
            n.exactloc.y = n.loc.y * 24000;
            n.parent = current_node.exactloc;

            // check if both coordinates are positive and below maximum
            // check if location is a passable node
            // check if location has already been considered
            if (n.loc.x >= 0 && n.loc.y >= 0 && n.loc.x < xmax && n.loc.y < ymax)
            {
                // check if location is a passable node
                if (passable[n.loc.x][n.loc.y] && unexplored[n.loc.x][n.loc.y])
                {
                    // for diagonals, check if the adjacent straight nodes are passable.
                    // if neither is passable, abort movement.
                    if ((i <= 3 && (passable[current_node.loc.x][n.loc.y] ||
                        passable[n.loc.x][current_node.loc.y])) || i > 3)
                    {
                        // add the neighbor to the open list
                        open_list.push_back(n);
                    }
                }
            }
        }
    }

    // no path found
    // clean up unexplored array
    for (int i = 0; i < xmax; i++)
    {
        delete[] unexplored[i];
    }

    delete[] unexplored;

    // return with blank path
    return_path = new Coordinate[1];
    return_path[0].x = -1;
    return_path[0].y = -1;
    return return_path;
}

```

# Answer
Thanks guys. I think I got it. What I did was change the unexplored array into a cost array that stores the cost to travel to that node. If the pathfinder travels over a node that requires more cost that the lowest recorded cost, it is not added to the open list. Now my algorithm returns quick results and doesn't make unwanted detours. There are still lots of things I can do for speed improvements like binary heap, but I already know how to implement that.
> 1 votes

# Answer
One problem may be the way you use the open list, At the start of each loop you do a linear scan over the entire open\_list, use erase to remove the lowest cost node and then add *all* not-closed neighbours to the `open_list` which leads to duplicate nodes in the list. You also don't have a way to avoid exploring a node twice.

If you track how large the open\_list gets during the algorithm you'll see it gets massive. Combine this with the 2 O(n) operations on the list and it'll be no surprise that the runtime gets massive.

During the linear scan over the open\_list you should flush the explored nodes. You can replace erase with a swap with back and pop\_back sequence.

```
for (unsigned int i = 0; i < open_list.size(); i++)
{
    while(i < open_list.size() &&
          explored[open_list[i].loc.x][open_list[i].loc.y]){
         // flush explored nodes
         swap(open_list[i], open_list.back());
         open_list.pop_back();
    }
    if(i >= open_list.size()) break;

    int dx = abs(destination.x - open_list[i].loc.x);
    int dy = abs(destination.y - open_list[i].loc.y);
    int min = (dx > dy) ? dy : dx;
    int distance = (dx + dy) * 1000 - min * 586;
    int total_cost = open_list[i].cost + distance;

    if (total_cost < best_cost || best_cost < 0)
    {
        best_cost = total_cost;
        best_node = i;
    }
}

```

Though it would be better if you updated the elements in the open\_list in place instead of simply adding the neighbours.
> 1 votes

---
Tags: path-finding
---


# Question
Title: rotating an array of images in 90 degree-java
In my java game,I have a stickSprite in vertical position.I want to rotate this stick in 90 degrees.so that it can hit the floor,once I press a key. I used a an array of stick sprites to create a large stick.Why I am doing this because I want to increase the stick length differently at different times.

I am using this method to rotate the stick image:

```
public Image rotateImage(Image src, float angle) {

    int sw = src.getWidth();
    int sh = src.getHeight();
    int[] srcData = new int[sw * sh];

    src.getRGB(srcData, 0, sw, 0, 0, sw, sh);
    int[] dstData = new int[sw * sh];

    double rads = angle * Math.PI / 180.f;
    float sa = (float) Math.sin(rads);
    float ca = (float) Math.cos(rads);
    int isa = (int) (256 * sa);
    int ica = (int) (256 * ca);

    int my = -(sh >> 1);
    for (int i = 0; i < sh; i++) {
        int wpos = i * sw;

        int xacc = my * isa - (sw >> 1) * ica + ((sw >> 1) << 8);
        int yacc = my * ica + (sw >> 1) * isa + ((sh >> 1) << 8);

        for (int j = 0; j < sw; j++) {
            int srcx = (xacc >> 8);
            int srcy = (yacc >> 8);

            if (srcx < 0)
                srcx = 0;
            if (srcy < 0)
                srcy = 0;
            if (srcx > sw - 1)
                srcx = sw - 1;
            if (srcy > sh - 1)
                srcy = sh - 1;

            dstData[wpos++] = srcData[srcx + srcy * sw];

            xacc += ica;
            yacc -= isa;
        }
        my++;
    }

    return Image.createRGBImage(dstData, sw, sh, true);
}

```

and rotating the single stick(that is not an element of the array.Stick array elements are placed above this base stick.)like this.It worked well.

```
private void RotateBaseStick() {

    if (smashBool &&angleValue<90) {
        angleValue = angleValue + stickMovingSpeed;
        rotatedImage = rotateImage(stickImage, angleValue);
        stickSprite.setImage(rotatedImage, rotatedImage.getWidth(),
                rotatedImage.getHeight());

    }
    if (angleValue >= 90) {
        smashBool = false;
    }

    }

```

I am wondering how can I rotate the entire stickArray efficiently to make the feel of a long single stick hitting the ground? Please help me.

# Answer
You should have a method which rotates an image using a **pivot point**.

Then it does not matter how many sticks there are, you always use the same pivot point to make the images rotate. In your case, the pivot point would be the bottom right corner of your right stick. Below enjoy my paint's skills.
> 0 votes

---
Tags: java
---


# Question
Title: How to fix this error at start-up after an update of Unity?
I receive this error after updating Unity to version 5.4.0p1:

```
Failed to query D3D11 context for ID3DUserDefinedAnnotation interface (hr = 0x80004002)

```

After some research, I did not find anything so I post it here. How it's fix?

Here it's my **Editor.Log** file:

```
LICENSE SYSTEM [2016820 9:45:38] Next license update check is after 2025-12-19T00:00:00
Built from '5.4/patch-release' branch; Version is '5.4.0p1 (e61faee5ea97) revision 15081390'; Using compiler version '160040219'
OS: 'Windows 7 Service Pack 1 (6.1.7601) 64bit' Language: 'en' Physical Memory: 3990 MB
BatchMode: 0, IsHumanControllingUs: 1, StartBugReporterOnCrash: 1, Is64bit: 1, IsPro: 1
Initialize mono
Mono path[0] = 'C:/Program Files/Unity/Editor/Data/Managed'
Mono path[1] = 'C:/Program Files/Unity/Editor/Data/Mono/lib/mono/2.0'
Mono path[2] = 'C:/Program Files/Unity/Editor/Data/UnityScript'
Mono config path = 'C:/Program Files/Unity/Editor/Data/Mono/etc'
Using monoOptions --debugger-agent=transport=dt_socket,embedding=1,defer=y,address=0.0.0.0:56416
IsTimeToCheckForNewEditor: Update time 1471669718 current 1471666542
I:/Flappy Bird
Loading GUID <-> Path mappings...0.000173 seconds
Loading Asset Database...0.016619 seconds
Audio: FMOD Profiler initialized on port 54900
AssetDatabase consistency checks...0.030437 seconds
Initialize engine version: 5.4.0p1 (e61faee5ea97)
Refreshing native plugins compatible for Editor in 5.76 ms, found 1 plugins.
GfxDevice: creating device client; threaded=1
Direct3D:
    Version:  Direct3D 11.0 [level 11.0]
    Renderer: Intel(R) HD Graphics (ID=0x152)
    Vendor:   Intel
    VRAM:     880 MB
Failed to query D3D11 context for ID3DUserDefinedAnnotation interface (hr = 0x80004002)
 (Filename: C:/buildslave/unity/build/Runtime/GfxDevice/d3d11/GfxDeviceD3D11.cpp Line: 871)
Begin MonoManager ReloadAssembly
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\UnityEngine.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\UnityEditor.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\Unity.Locator.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\I18N.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\I18N.West.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\Unity.DataContract.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Core.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\Unity.IvyParser.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Xml.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Configuration.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\PackageManager\Unity\PackageManager\5.4.0\Unity.PackageManager.dll (this message is harmless)
Initializing Unity.PackageManager (PackageManager) v5.4.0 for Unity v5.4.0p1
Setting Android v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer
Setting StandaloneWindows v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\PlaybackEngines\windowsstandalonesupport
Setting Advertisements v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Advertisements
  UnityEngine.Advertisements.dll (Extension) GUID: 739bbd9f364b4268874f9fd86ab3beef
  Editor/UnityEditor.Advertisements.dll (Extension) GUID: 97decbdab0634cdd991f8d23ddf0dead
Setting EditorTestsRunner v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner
  Editor/nunit.framework.dll (Extension) GUID: 7cbab2be89b54486bbd23a6fe637d30e
  Editor/UnityEditor.EditorTestsRunner.dll (Extension) GUID: 3c0ad459c1534645b5d603b7cc258f97
Setting GUISystem v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem
  UnityEngine.UI.dll (Extension) GUID: f5f67c52d1564df4a8936ccd202a3bd8
  Editor/UnityEditor.UI.dll (Extension) GUID: 80a3616ca19596e4da0f10f14d241e9f
Setting UNetHLAPI v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking
  UnityEngine.Networking.dll (Extension) GUID: 870353891bb340e2b2a9c8707e7419ba
  Editor/UnityEditor.Networking.dll (Extension) GUID: 5f32cd94baa94578a686d4b9d6b660f7
Setting TreeEditor v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\TreeEditor
  Editor/UnityEditor.TreeEditor.dll (Extension) GUID: adebbd281f1a4ef3a30be7f21937e02f
Setting UnityAnalytics v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\UnityAnalytics
  UnityEngine.Analytics.dll (Extension) GUID: 852E56802EB941638ACBB491814497B0
Setting UnityPurchasing v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\UnityPurchasing
  UnityEngine.Purchasing.dll (Extension) GUID: 8E0CD8ED44D4412CBE0642067ABC9E44
Registering custom dll's ...
Register platform support module: C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/UnityEditor.Android.Extensions.dll
Register platform support module: C:\Program Files\Unity\Editor\Data\PlaybackEngines\windowsstandalonesupport/UnityEditor.WindowsStandalone.Extensions.dll
Registered in 0.073302 seconds.
Non platform assembly: I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp-firstpass.dll (this message is harmless)
Loading I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp-firstpass.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp.dll (this message is harmless)
Loading I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp-Editor.dll (this message is harmless)
Loading I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp-Editor.dll into Unity Child Domain
Platform assembly: C:\Program Files\Unity\Editor\Data\PackageManager\Unity\PackageManager\5.4.0\Unity.PackageManager.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\PackageManager\Unity\PackageManager\5.4.0\Unity.PackageManager.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Advertisements\Editor\UnityEditor.Advertisements.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Advertisements\Editor\UnityEditor.Advertisements.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\nunit.framework.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\nunit.framework.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\UnityEditor.EditorTestsRunner.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\UnityEditor.EditorTestsRunner.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\UnityEngine.UI.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\UnityEngine.UI.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\Editor\UnityEditor.UI.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\Editor\UnityEditor.UI.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\UnityEngine.Networking.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\UnityEngine.Networking.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\Editor\UnityEditor.Networking.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\Editor\UnityEditor.Networking.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\TreeEditor\Editor\UnityEditor.TreeEditor.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\TreeEditor\Editor\UnityEditor.TreeEditor.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\JMO Assets\Editor\JMOAssets.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\JMO Assets\Editor\JMOAssets.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\Plugins\I18N.MidEast.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\Plugins\I18N.MidEast.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\Plugins\I18N.Other.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\Plugins\I18N.Other.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\Plugins\I18N.Rare.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\Plugins\I18N.Rare.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\Plugins\Mono.Data.Sqlite.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\Plugins\Mono.Data.Sqlite.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\Plugins\System.Data.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\Plugins\System.Data.dll into Unity Child Domain
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\UnityEditor.Graphs.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\Managed\UnityEditor.Graphs.dll into Unity Child Domain
Platform assembly: C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\UnityEditor.Android.Extensions.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\UnityEditor.Android.Extensions.dll into Unity Child Domain
Platform assembly: C:\Program Files\Unity\Editor\Data\PlaybackEngines\windowsstandalonesupport\UnityEditor.WindowsStandalone.Extensions.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\PlaybackEngines\windowsstandalonesupport\UnityEditor.WindowsStandalone.Extensions.dll into Unity Child Domain
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\nunit.core.interfaces.dll (this message is harmless)
Refreshing native plugins compatible for Editor in 0.36 ms, found 1 plugins.
Preloading 0 native plugins for Editor in 0.00 ms.
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\Mono.Cecil.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\Unity.SerializationLogic.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\UnityScript.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\ICSharpCode.NRefactory.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Xml.Linq.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\nunit.core.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Transactions.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Mono.Data.Tds.dll (this message is harmless)
Mono: successfully reloaded assembly
- Completed reload, in  0.893 seconds
Registering platform support modules:
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Boo.Lang.Compiler.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Boo.Lang.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Boo.Lang.Parser.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\UnityScript.Lang.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Mono.Security.dll (this message is harmless)
Registered platform support modules in: 0.1201295s.
Native extension for WindowsStandalone target not found
Native extension for Android target not found
Downloading http://update.unity3d.com/5.4/ivy.xml to C:\Users\DARSHA~1\AppData\Local\Temp\unity\85968888-3129-4314-87f1-74e4e633d110\ivy.xml
Reloading assemblies after successful script compilation.
Begin MonoManager ReloadAssembly
Shutting down Remote Indexer
Task failed: Downloader Task
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\UnityEngine.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\UnityEditor.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\Unity.Locator.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\I18N.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\I18N.West.dll (this message is harmless)
Registering custom dll's ...
Register platform support module: C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/UnityEditor.Android.Extensions.dll
Register platform support module: C:\Program Files\Unity\Editor\Data\PlaybackEngines\windowsstandalonesupport/UnityEditor.WindowsStandalone.Extensions.dll
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Core.dll (this message is harmless)
Registered in 0.099164 seconds.
Non platform assembly: I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp-firstpass.dll (this message is harmless)
Loading I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp-firstpass.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp.dll (this message is harmless)
Loading I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp-Editor.dll (this message is harmless)
Loading I:\Flappy Bird\Library\ScriptAssemblies\Assembly-CSharp-Editor.dll into Unity Child Domain
Platform assembly: C:\Program Files\Unity\Editor\Data\PackageManager\Unity\PackageManager\5.4.0\Unity.PackageManager.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\PackageManager\Unity\PackageManager\5.4.0\Unity.PackageManager.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Advertisements\Editor\UnityEditor.Advertisements.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Advertisements\Editor\UnityEditor.Advertisements.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\nunit.framework.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\nunit.framework.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\UnityEditor.EditorTestsRunner.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner\Editor\UnityEditor.EditorTestsRunner.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\UnityEngine.UI.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\UnityEngine.UI.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\Editor\UnityEditor.UI.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem\Editor\UnityEditor.UI.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\UnityEngine.Networking.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\UnityEngine.Networking.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\Editor\UnityEditor.Networking.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking\Editor\UnityEditor.Networking.dll into Unity Child Domain
Non platform assembly: C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\TreeEditor\Editor\UnityEditor.TreeEditor.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\TreeEditor\Editor\UnityEditor.TreeEditor.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\JMO Assets\Editor\JMOAssets.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\JMO Assets\Editor\JMOAssets.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\Plugins\I18N.MidEast.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\Plugins\I18N.MidEast.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\Plugins\I18N.Other.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\Plugins\I18N.Other.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\Plugins\I18N.Rare.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\Plugins\I18N.Rare.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\Plugins\Mono.Data.Sqlite.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\Plugins\Mono.Data.Sqlite.dll into Unity Child Domain
Non platform assembly: I:\Flappy Bird\Assets\Plugins\System.Data.dll (this message is harmless)
Loading I:\Flappy Bird\Assets\Plugins\System.Data.dll into Unity Child Domain
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\UnityEditor.Graphs.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\Managed\UnityEditor.Graphs.dll into Unity Child Domain
Platform assembly: C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\UnityEditor.Android.Extensions.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\UnityEditor.Android.Extensions.dll into Unity Child Domain
Platform assembly: C:\Program Files\Unity\Editor\Data\PlaybackEngines\windowsstandalonesupport\UnityEditor.WindowsStandalone.Extensions.dll (this message is harmless)
Loading C:\Program Files\Unity\Editor\Data\PlaybackEngines\windowsstandalonesupport\UnityEditor.WindowsStandalone.Extensions.dll into Unity Child Domain
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\nunit.core.interfaces.dll (this message is harmless)
Refreshing native plugins compatible for Editor in 0.42 ms, found 1 plugins.
Preloading 0 native plugins for Editor in 0.00 ms.
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\Mono.Cecil.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\Unity.SerializationLogic.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\Unity.DataContract.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\UnityScript.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\ICSharpCode.NRefactory.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Xml.Linq.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\Unity.IvyParser.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Managed\nunit.core.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\System.Transactions.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Mono.Data.Tds.dll (this message is harmless)
Mono: successfully reloaded assembly
- Completed reload, in  0.741 seconds
Initializing Unity.PackageManager (PackageManager) v5.4.0 for Unity v5.4.0p1
Setting Android v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer
Setting StandaloneWindows v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\PlaybackEngines\windowsstandalonesupport
Setting Advertisements v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Advertisements
  UnityEngine.Advertisements.dll (Extension) GUID: 739bbd9f364b4268874f9fd86ab3beef
  Editor/UnityEditor.Advertisements.dll (Extension) GUID: 97decbdab0634cdd991f8d23ddf0dead
Setting EditorTestsRunner v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\EditorTestsRunner
  Editor/nunit.framework.dll (Extension) GUID: 7cbab2be89b54486bbd23a6fe637d30e
  Editor/UnityEditor.EditorTestsRunner.dll (Extension) GUID: 3c0ad459c1534645b5d603b7cc258f97
Setting GUISystem v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\GUISystem
  UnityEngine.UI.dll (Extension) GUID: f5f67c52d1564df4a8936ccd202a3bd8
  Editor/UnityEditor.UI.dll (Extension) GUID: 80a3616ca19596e4da0f10f14d241e9f
Setting UNetHLAPI v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\Networking
  UnityEngine.Networking.dll (Extension) GUID: 870353891bb340e2b2a9c8707e7419ba
  Editor/UnityEditor.Networking.dll (Extension) GUID: 5f32cd94baa94578a686d4b9d6b660f7
Setting TreeEditor v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\TreeEditor
  Editor/UnityEditor.TreeEditor.dll (Extension) GUID: adebbd281f1a4ef3a30be7f21937e02f
Setting UnityAnalytics v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\UnityAnalytics
  UnityEngine.Analytics.dll (Extension) GUID: 852E56802EB941638ACBB491814497B0
Setting UnityPurchasing v5.4.0 for Unity v5.4.0p1 to C:\Program Files\Unity\Editor\Data\UnityExtensions\Unity\UnityPurchasing
  UnityEngine.Purchasing.dll (Extension) GUID: 8E0CD8ED44D4412CBE0642067ABC9E44
Registering platform support modules:
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Boo.Lang.Compiler.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Boo.Lang.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\Boo.Lang.Parser.dll (this message is harmless)
Platform assembly: C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0\UnityScript.Lang.dll (this message is harmless)
Registered platform support modules in: 0.0633843s.
Native extension for WindowsStandalone target not found
Native extension for Android target not found
Validating Project structure ... 0.028280 seconds.
Refresh: detecting if any assets need to be imported or removed ... Refresh: elapses 0.028525 seconds (Nothing changed)
Warming cache for 1967 main assets: 0.015007 seconds elapsed
Initializing Unity extensions:
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityAnalytics/UnityEngine.Analytics.dll'
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll'
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/Networking/Editor/UnityEditor.Networking.dll'
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/TreeEditor/Editor/UnityEditor.TreeEditor.dll'
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/EditorTestsRunner/Editor/UnityEditor.EditorTestsRunner.dll'
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/Networking/UnityEngine.Networking.dll'
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/Advertisements/Editor/UnityEditor.Advertisements.dll'
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/GUISystem/Editor/UnityEditor.UI.dll'
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/UnityPurchasing/UnityEngine.Purchasing.dll'
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/EditorTestsRunner/Editor/nunit.framework.dll'
 'C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/Advertisements/UnityEngine.Advertisements.dll'
Load scene 'Assets/Scenes/Menu.unity' time: 0.014026 ms
Unloading 189 Unused Serialized files (Serialized files now loaded: 0)
System memory in use before: 35.8 MB.
System memory in use after: 35.8 MB.
Unloading 9 unused Assets to reduce memory usage. Loaded Objects now: 1086.
Total: 5.100740 ms (FindLiveObjects: 0.442337 ms CreateObjectMapping: 0.110156 ms MarkObjects: 4.509246 ms  DeleteObjects: 0.036604 ms)
<RI> Initializing input.
XInput1_3.dll not found. Trying XInput9_1_0.dll instead...
<RI> Input initialized.
Issue TrimJob to reduce GI Cache size to maximum 10GB at: 'C:/Users/Darshan Soni/AppData/LocalLow/Unity/Caches/GiCache'
Setting up 1 worker threads for Enlighten.
  Thread -> id: 7c8 -> priority: 1
Launched and connected shader compiler UnityShaderCompiler.exe after 0.62 seconds
TrimDiskCacheJob: Current cache size 69mb
Refresh: detecting if any assets need to be imported or removed ... Refresh: elapses 0.028466 seconds (Nothing changed)

```

# Answer
> 1 votes
This happens on machines that have Windows 7 without any service packs installed. While this error is harmless, you can work around it by updating Windows.

---
Tags: unity
---


# Question
Title: Is there anyway to retrieve the properties of an individual TiledTile?
I managed to get a list of all the tiles in a layer of a tmx map by iterating through the `IReadOnlyList<TiledTile> Tiles` in `TiledTileLayer` and enumerating the values into another list. But I need to be able to iterate through that list and check for a certain property. However, `TiledTile` has no `properties` variable and no `getProperties()` method. How would I do this?

# Answer
> 1 votes
Correct me if I'm wrong but I think the properties you're after exist on the Tileset Tile.

There's been a lot of work going into the Tiled feature of MonoGame.Extended lately. Even since you asked this question a lot of things have changed. If there's something missing, raising a github issue is a good way to get some eyeballs on it.

Sorry if I've missed something. I checked the Tiled editor to see what properties you might be talking about and I'm not sure how you'd go about setting Properties at the tile level.

---
Tags: monogame, monogame-extended
---


# Question
Title: how can you use playerprefs to save an array in javascript on unity
As I stated I can't find a working answer anywhere else. I have a game where you are to draw out your own weapon and I'm storing that information in an array. How?

# Answer
You would first need to serialize your array into a string. One way to do this, is to create a tokenizable string representation of your array data.

For example:

```
string data = "";

for (int n = 0; n < Array.GetLength(0); n++) {
    data += Array[n].ToString();
    if(n != Array.GetLength(0) - 1)
        data += ",";
}

PlayerPrefs.SetString("ArrayData", data);
PlayerPrefs.Save();

```

Then loading this back into the array would look something like this:

```
string data = PlayerPrefs.GetString("ArrayData");
string[] tokens = data.Split(',');

Array = new Array[tokens.GetLength(0)];
for (int n = 0; n < tokens.GetLength(0); n++) {
    Array[n] = tokens[n];    //Cast to var type here
}

```
> 2 votes

---
Tags: unity, javascript
---


title: How can I play a video in a Godot game?

text:
# Question
Title: How can I play a video in a Godot game?
I'd like to know if and how it is possible for me to play a video in my Godot game. Specifically I'd like to know what video file format I need to use and what code I have to write to play that video back fullscreen.

# Answer
Godot has a `VideoPlayer` API that is suitable for this purpose.

Once you create a `VideoPlayer` node, you can use the `set_stream` function to assign the desired video stream. You can load such a stream using the `load` function: `load("some/path/to/your/video.ogv")`.

Note that `VideoPlayer` *only* supports the OGV Theora format.
> 2 votes

---
Tags: video, godot
---


# Question
Title: Determining whether to trigger random events
Say I want to trigger some event with a certain likelihood throughout gameplay. For example, say I want there to be a 5% chance of engine failure in a spaceship simulator that runs for an indeterminate length of time.

When and how do I determine **if** that event will occur? If I determine it **will** occur, how do I determine **when** it will occur?

The problem I see is that if you calculate the chance of a failure every tick, then there's a 5% chance of failure **per tick**, which means over two ticks there's **more** than a 5% chance - something like 8% I believe. Once the game ticks 1,000 or 1,000,000 times, it's almost certain the engine will have failed (~100% chance) when there's only supposed to be "a 5% chance."

Say we somehow knew the game would last for ten minutes - then we could get a random number 1-100 and if it's 5 or less, say the engine will fail within those ten minutes. But then at minute 5, say the player upgrades his or her engine to a 2% failure rate. We could again roll the die and if we get 2 or less, the engine will fail within the next five minutes. But again, we've calculated the chances of failure twice, which means it's more likely to fail than if we calculated those chances only once.

When we look at in-game items, they never say "5% chance of failure **per frame, per minute, per game, etc.**" What does "x% chance" really mean and how do we get a computer to tell us if and when the event will occur?

# Answer
> 1 votes
With in game items, their effects tend to be either permanent, or applied by use. So it would be 5% failure each time you use the object. So a weapon would not have the effect applied until it is used to attack something. Permanent effects rarely have any % failure chances, instead, they do things like +1 to damage, or -20% dodge. Modifying a stat directly with no randomness.

The other option, applied with use, or a condition, is simple. Lets take an example of a sword. It has a 1% chance of breaking. Every time it hits something, then we roll a dice calculating 1-100, then if it is 1, then the sword breaks.

With regards to the length of time, you simply do not check until the time required has passed. So if the engine has a 5% chance of failure if it has been running for X amount of time, then simply do not roll the dice until X amount of time has passed.

Lets say we have a spaceship, and if you run the engines at 90% or more of maximum speed for 5 minutes, there is a 5% chance they will explode. For the first 5 minutes, the program doesn't roll any dice. After 5 minutes has passed, it starts rolling the dice each tick. We simply start counting when they hit 90% of maximum speed, and stop when they go below 90%. Of course, this opens up an exploit that lets them drop below 90% to reset the counter. But we can get around this with some form of cooldown, perhaps pausing the counter while the speed is below 90% during this period.

Then there are ongoing, like you have pointed out. Developers can check every frame, which would rapidly increase the chances, or after so many frames/time.

Honestly, 5% of failure is ambiguous, and varies on how the developer has developed the system. It really is a way of telling the user that there is a chance something bad can happen, and they can tell that a 2% failure engine is better than a 5%. The average user doesn't really need to know that the game only checks this once every minute, or whenever they change speed or direction. And for the special user who has spreadsheets detailing every tiny chance or difference between engines, you can bury it in documentation or let them figure it out on there own.

# Answer
> 0 votes
5% chance of failure is very high. I assume, that in your simulator longer the flight takes, more break-downs should appear. There is bias about chance. Fair toss of the coin has 50% chance of head, or 1:1 head:eagle. If you do 100 tosses, how many heads have you seen? Can be 0 or 100 or something between, rarely 50:50. N. Taleb More scientific reading This is the same problem you are facing.

Most of the game has chance given to some action, like enchantment. Really depends how you want to build you mechanics. What should player feel. It can for example effectively limit the distance the ship can reasonably travel and so on. You can put your variables in Excel and change those to get expected results.

---
Tags: random
---


# Question
Title: Is Ruby's garbage collector still as big of a problem to game developement?
I am beginner wanting to make a game, and chose to learn Ruby ,since it seems easier to read than most languages.

Reading up on Ruby, I find that Ruby could be used to make small-scale games, but it's garbage collector was a serious problem. The post I read had been closed, so the most recent post was from 2013. In contrast, Ruby 2.0 came out in 2013, and apparently the garbage collector got better. I was wondering if the garbage collector is still a major problem.

To be a little more specific, the game I want to make is going to be 2D, using pixel art. It's a small PvP game using LAN. I want to make 7 character classes, but I can start with less. This game is quite small, but there are a lot of things I want to add as I get more experience, such as a story.

Does the garbage collector still make game development a problem, in Ruby?

# Answer
Let's first discuss your concerns of a garbage collector. Truthfully, it really shouldn't matter much, that is, assuming you're being smart about how you write your code. If you're working in a managed environment, you will need to obey several constraints while you code; the rendering loop is a good example. In constant loops you should be generating as little garbage as possible, by that I actually mean zero allocations. You need to be initializing as much data as you can beforehand, caching it, and reusing it. In other routines of your game/engine this can be different, because those routines will be executed infrequently. Also, consider using structs in place of certain plain-data classes, like Points, Vector2, Vector3, and Matrices. Structs are value types, thus are not allocated to the heap, that means no garbage collection.
> 3 votes

---
Tags: ruby
---


# Question
Title: HPA* Pathfinding, building the hierarchical graph is too slow
So I have a graph, roughly grid shaped, that is about 300\*300 nodes large. Even at this size, however, traditional a star takes 20 seconds to run in some cases. So I implemented an HPA\* algorithm to shorten pathfinding time. HPA\* looks somewhat like this, chopping up the graph into small chunks that can be pathed quickely:

The algorithm works by first finding places to put hierarchical nodes along certain sized edges, then, for every node, finding a path between itself and all other nodes that it shares a square with, or cluster. In the image above, this is shows as the red dots as hierarchical nodes, and the red lines as the paths between the hierarchical nodes.

To find the path between all the nodes in a cluster, I used A\*. While the paths are not that big between each node, and thus the A\* does not take too long, I need to find many, many of them. For my project, I have hundreds of hierarchical nodes, and, therefore, thousands of searches needed to build the hierarchical graph.

This is an annoyance for testing my game, rebuilding the graph whenever I change something in the scene, it is a nightmare when I wan to do dynamic map changes, often taking seconds and even minutes to get it done.

I have tried many things to speed up the build process, such as doing a modified flood fill for every cluster to just see if the hierarchical nodes are connected and that making the distance between the euclidean, sacrificing accuracy. But the modified flood fill was about as slow as A\*, and it did not work.

Is there anything to speed up the HPA\* build time for dynamic maps, any special algorithms or speedups or shortcuts I need to know? I would be willing to sacrifice a lot of path accuracy for anything to make it faster. Thank you for all your help.

P.S. The problem is with the fact that it has to do hundreds or even, in some cases, thousands of A\* pathfinds during the build phase.

# Answer
You are generating the graph dynamically right?

Anyway, for each sector you should just do a flood fill for each node to get you the distance between the nodes. This should be enough but you can also get a path using this technique. Also, don't floodfill outside the sector. A couple thousand 4x4 floodfills should not take more then a couple of seconds.

When you dynamically change the map you only need to take account for the sector you changes, you update the cost for the nodes and if a node becomes unreachable you need to sync it with the other sector.

I have a traditional A\* traverse a harsh 1024x1024map in less then a second with about 300k iteration steps. So you might have to consider tweaking your algorithm. What data structures you use? I often use a `boolean[]` as closedlist if you know where to look

```
if (closedList[connection.getToNode().getIndex()]) continue;
// Direct lookup, no iterations at all!

```

And then the openlist, I find a `TreeMap<Fscore, List<Nodes>` very fast but needs some extra attention.

And there might be countless of other bottlenecks in your alghorithm but these two can have the most impact.
> 1 votes

# Answer
It should be possible to only change the subpaths that are affected by the map change.

```
void updateHPA(List<Change> changes){
    Set<Square> changedSqr = new HashSet<>();
    for(Change ch : changes) {
        Square sq = grid.getSquareOf(ch.getLoc());
        if(changedSqr.contains(sq)) continue;
        changedSqr.add(sq);

        // update paths internal to sq
    }
}

```
> 0 votes

---
Tags: algorithm, performance, path-finding
---


title: Need help on double jumping in Unity

text:
# Question
Title: Need help on double jumping in Unity
I have been making a 2D game in Unity, with a group of mine. We have made a character and are able to make him run and jump. Currently, I have been trying to make him double jump so someone can't just spam the jump button and go flying, but nothing has been working.

I've been through about at least 10 different tutorials on it, but nothing has worked. How do I make my character double jump?

```
public float speed;
public float jump;

float moveVelocity;
private Rigidbody2D myRigidBody;
private bool grounded = true;

void Start ()
{
    myRigidBody = GetComponent<Rigidbody2D> ();
}

void Update ()
{
    //constant run
    myRigidBody.velocity = new Vector2(speed, myRigidBody.velocity.y);

    if (Input.GetKeyDown (KeyCode.Space))
    {
        if (grounded)
        {
            myRigidBody.velocity
                = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
        }
    }
}

```

# Answer
Change 'totalJumps' to 'doubleJumped' and replace that condition with:

```
if (Input.GetKeyDown (KeyCode.Space))
{
    if (grounded || !doubleJumped) {
        myRigidBody.velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
        doubleJumped = !grounded;
    }
} else if (grounded) {
    doubleJumped = false;
}

```

That's saying to jump either when grounded or you haven't double jumped yet, and to reset the double jump variable when on the ground.

---

incidentally, I assumed 'grounded' is being detected, although that's not in your code sample. If needed, do a raycast down to detect when standing on the ground, explained more here: http://answers.unity3d.com/questions/196381/how-do-i-check-if-my-rigidbody-player-is-grounded.html
> 1 votes

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


# Question
Title: Why am I getting this linker failure building my Unity project in Xcode?
This image is of my code when I am trying to compile my game in xcode. I have been working on it for weeks and this is stopping me I have been trying to figure it out for days. Any help would be greatly appreciate!

# Answer
I figured it out. Delete any x code instances of this project, and then re-export with unity(making sure your package name/and icon images are in there) after that open in x code and should work right away. I'm not sure why this is, probably happened from multiple instances of the same object with a few different library files with the same name not linking in the right order or something. Thanks for the responses though!
> 0 votes

---
Tags: xcode
---


# Question
Title: Continuously get keyboard input from user and remember last character [Java]
I want to write a Snake game in Java. How can I continuously monitor input and if user pressed `W` set variable `Char lastDirection = 'w'; //hence, Direction.UP`?

I know about the Scanner method: `Scanner scan= new Scanner(System.in);`... But then user would have to hit enter each time he presses the button. Document Listener (Swing) seems better, but then I would have a long string of user input saved somewhere that I don't need. What is the right method for listening to keyboard and remembering the last character?

# Answer
> 3 votes
You need a Listener indeed.

Then you can store the pressed keys in an array, and manage it like this.

```
bool keyPressed[256];
// Do not forget to initialize all to false if java does not do it;

onKeyPressed(event e) {
    keyPressed[e.keyCode] = true;
}

onKeyReleased(event e) {
    keyPressed[e.keyCode] = false;
}

// in game loop you can then check like this
if (keyPressed[keyCode("w")])
    moveUp();

```

Note that all of this is pseudo-code.

**EDIT :**

The previous code is not really adapted for snake as the snake is supposed to keep moving on even if the key has been released.

Using booleans to keep track of the current direction as stated in OP's own answer is indeed the best solution I can think of.

# Answer
> 0 votes
I've find this Snake game implementation: http://zetcode.com/tutorials/javagamestutorial/snake/

It uses extends `KeyAdapter`.

```
private class TAdapter extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
            leftDirection = true;
            upDirection = false;
            downDirection = false;
        }

        if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
            rightDirection = true;
            upDirection = false;
            downDirection = false;
        }

        if ((key == KeyEvent.VK_UP) && (!downDirection)) {
            upDirection = true;
            rightDirection = false;
            leftDirection = false;
        }

        if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
            downDirection = true;
            rightDirection = false;
            leftDirection = false;
        }
    }
}

```

The use of four `boolean` flags seems dated and `enum` seems better for this purpose, but `KeyAdapter` fits the task well.

# Answer
> 0 votes
In Swing, there are many, many different kinds of event listeners. In particular, KeyListener will do the job in this situation. Oracle has a great tutorial about event handling so I won't go into any details here.

Do you really need to remember the last key pressed? It seems to me that it would be more useful to keep track of the current direction the snake is moving and change direction as appropriate. For example, if the snake is moving up and the user presses down, you do not care about the key pressed. You only care if the user presses left or right.

---
Tags: java, keyboard
---


# Question
Title: Off screen image Direct3D processing with SharpDX, pixel shader and C#
I currently have a working app that can process images with a window handle. This of course makes use of the swap chain and so on... I need to process an image with pixel shader off screen without a window handle. I have not been able to successfully port this to an off screen model. Can any please help educate me on the best way to do this? I have the Device, context for both Direct3D and Direct2D available. I'm having issues with using the correct texture to image process...

# Answer
First up create the DirectX device by calling New Direct3D11.Device and then you simply call DeviceContext.Flush in place of present.

Setup the device

```
    Dim FL As FeatureLevel() = New FeatureLevel(0) {}
    FL(0) = FeatureLevel.Level_11_1
    MainDevice = New Direct3D11.Device(Direct3D.DriverType.Hardware, DeviceCreationFlags.None, FL)

```

At the end of the frame

```
MainDevice.ImmediateContext.Flush

```

Texture creation

```
Dim ColorFormat As Format = Format.R8G8B8A8_UNorm
Dim BufferDesc As New Texture2DDescription() With {
 .ArraySize = 1,
 .BindFlags = BindFlags.RenderTarget Or BindFlags.ShaderResource,
 .CpuAccessFlags = CpuAccessFlags.None,
 .Format = ColorFormat,
 .Height = Height,
 .Width = Width,
 .MipLevels = 1,
 .OptionFlags = ResourceOptionFlags.None,
 .SampleDescription = New SampleDescription(1, 0),
 .Usage = ResourceUsage.Default
}

    Dim ColorBuffer As Texture2D = New Texture2D(MainDevice, BufferDesc)
    Dim ClorBufferRT AS RenderTargetView = New RenderTargetView(MainDevice, _buffer)

```
> 0 votes

---
Tags: c#, shaders, sharpdx, pixel
---


title: SharpDX Texture to Image in C#

text:
# Question
Title: SharpDX Texture to Image in C#
I currently have an image processing application that outputs processed images post pixel shaders have been applied. However, using the examples I've found on the internet, the colors are flip to BGRA when RGBA is expected. I currently work around this with by post export processing to get the desired RGBA format. I was hoping someone else has dealt with this and has a solution that does not require post processing to correct the format.

# Answer
> 3 votes
I have two methods for doing this I will post them both.

Code is in VB.net and using sharpDX 3.0.2

Basically you copy your texture data to a staging resource and then write that staging resource to disk using WIC.

If I recall I may have pulled this out of the SharpDX.Toolkit, DrawContext is just a wrapper around Device context so it should just be a name change and it will work.

This will save textures to disk as DDS files, you can change this by changing out the WIC encoder or load the images into Photoshop and do it from there.

```
  ' jpeg Container Format GUID: 19e4a5aa-5662-4fc5-a0c01758028e1057
  ' PNG Container Format GUID: 1b7cfaf4-713f-473c-bbcd6137425faeaf

 Dim blah As Guid = Guid.Parse("9967cb952E854ac88ca283d7ccd425c9") 'this is the WIC DDS Container Format GUID

 Dim bitmapEncoder As DdsEncoder = New DdsEncoder 'This is the WIC DDS encoder, try changing this to png or jpeg.

```

I like the DDS file format so I just stick with that.

How to save a texture to a File

```
   Dim fs As New FileStream(DirectXDevice.ContentPath & "Textures\Layer1.dds", FileMode.OpenOrCreate)
        SaveTexture(_Context, TerrainLayerBuffer, fs)
        fs.Flush()
        fs.Dispose()

```

How to save a texture to a System.Drawing.Image

```
 Dim ms As New MemoryStream()

 SaveTexture(_Context, TerrainLayerBuffer, ms)
 ms.Flush()

 Dim newimage As System.Drawing.Image = System.Drawing.Image.FromStream(ms)
 ms.Dispose()

```

The save texture methods

```
  Public Sub SaveTexture(_device As DrawContext, res As Resource,ByRef stream As Stream)
    Dim factory As New ImagingFactory()
    Dim texture = TryCast(res, Texture2D)
    'Setup Staging resource
    Dim textureCopy = New Texture2D(_device.Device, New Texture2DDescription() With {
    .Width = CType(texture.Description.Width, Integer),
    .Height = CType(texture.Description.Height, Integer),
    .MipLevels = 1,
    .ArraySize = 1,
    .Format = texture.Description.Format,
    .Usage = ResourceUsage.Staging,
    .SampleDescription = New SharpDX.DXGI.SampleDescription(1, 0),
    .BindFlags = BindFlags.None,
    .CpuAccessFlags = CpuAccessFlags.Read,
    .OptionFlags = ResourceOptionFlags.None
})
     Copy Texture Data To Staging Resource
    _device.CopyResource(res, textureCopy)

    'Read Staging resource data to a Datastream to be passed to the WIC codec
    Dim dataStream As DataStream
    Dim dataBox = _device.MapSubresource(textureCopy, 0, 0, MapMode.Read, Direct3D11.MapFlags.None, dataStream)

    Dim dataRectangle = New DataRectangle() With {
    .DataPointer = dataStream.DataPointer,
    .Pitch = dataBox.RowPitch
}

    ' TODO: should use some conversion from textureCopy.Description.Format
    Dim bitmap As BitmapSource = New Bitmap(factory, textureCopy.Description.Width, textureCopy.Description.Height, PixelFormatFromFormat(textureCopy.Description.Format), dataRectangle)

    'Set Up WIC
    Using WICStream As New WICStream(factory, stream)
        Dim blah As Guid = Guid.Parse("9967cb952E854ac88ca283d7ccd425c9") 'DDS Container Format
        Dim bitmapEncoder As BitmapEncoder = New BitmapEncoder(factory, blah, WICStream)
        Dim ccc As BitmapEncoderInfo = bitmapEncoder.EncoderInfo

        If bitmapEncoder IsNot Nothing Then
            Using bitmapFrameEncode = New BitmapFrameEncode(bitmapEncoder)

                bitmapFrameEncode.Initialize()
                bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height)

                bitmapFrameEncode.SetPixelFormat(PixelFormatFromFormat(textureCopy.Description.Format))
                bitmapFrameEncode.WriteSource(bitmap)
                bitmapFrameEncode.Commit()
                bitmapEncoder.Commit()
            End Using
            bitmapEncoder.Dispose()
        End If
    End Using

    _device.UnmapSubresource(textureCopy, 0)

    "Clean UP
    textureCopy.Dispose()
    bitmap.Dispose()
    factory.Dispose()

End Sub

  Public Sub SaveTexture(_device As DrawContext, res As Resource, _filename As String)
    Dim factory As New ImagingFactory()
    Dim texture = TryCast(res, Texture2D)
    Dim textureCopy = New Texture2D(_device.Device, New Texture2DDescription() With {
    .Width = CType(texture.Description.Width, Integer),
    .Height = CType(texture.Description.Height, Integer),
    .MipLevels = 1,
    .ArraySize = 1,
    .Format = texture.Description.Format,
    .Usage = ResourceUsage.Staging,
    .SampleDescription = New SharpDX.DXGI.SampleDescription(1, 0),
    .BindFlags = BindFlags.None,
    .CpuAccessFlags = CpuAccessFlags.Read,
    .OptionFlags = ResourceOptionFlags.None
})
    _device.CopyResource(res, textureCopy)

    Dim dataStream As DataStream
    Dim dataBox = _device.MapSubresource(textureCopy, 0, 0, MapMode.Read, Direct3D11.MapFlags.None, dataStream)

    Dim dataRectangle = New DataRectangle() With {
    .DataPointer = dataStream.DataPointer,
    .Pitch = dataBox.RowPitch
}

    ' TODO: should use some conversion from textureCopy.Description.Format
    Dim bitmap = New Bitmap(factory, textureCopy.Description.Width, textureCopy.Description.Height, PixelFormatFromFormat(textureCopy.Description.Format), dataRectangle)

    Using WICStream = New WICStream(factory, _filename, IO.NativeFileAccess.ReadWrite)
        Dim bitmapEncoder As DdsEncoder = New DdsEncoder(WICStream.NativePointer)

        If bitmapEncoder IsNot Nothing Then
            Using bitmapFrameEncode = New BitmapFrameEncode(bitmapEncoder)
                bitmapFrameEncode.Initialize()
                bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height)

                bitmapFrameEncode.SetPixelFormat(PixelFormatFromFormat(textureCopy.Description.Format))
                bitmapFrameEncode.WriteSource(bitmap)
                bitmapFrameEncode.Commit()
                bitmapEncoder.CreateNewFrame(bitmapFrameEncode, 0, 0, 0)
            End Using
            bitmapEncoder.Dispose()
        End If

    End Using

    _device.UnmapSubresource(textureCopy, 0)
    textureCopy.Dispose()
    bitmap.Dispose()
    factory.Dispose()
    factory = Nothing
    bitmap = Nothing
    textureCopy = Nothing
End Sub

  Public Function PixelFormatFromFormat(format As SharpDX.DXGI.Format) As Guid
    Select Case format
        Case SharpDX.DXGI.Format.R32G32B32A32_Typeless, SharpDX.DXGI.Format.R32G32B32A32_Float
            Return SharpDX.WIC.PixelFormat.Format128bppRGBAFloat
        Case SharpDX.DXGI.Format.R32G32B32A32_UInt, SharpDX.DXGI.Format.R32G32B32A32_SInt
            Return SharpDX.WIC.PixelFormat.Format128bppRGBAFixedPoint
        Case SharpDX.DXGI.Format.R32G32B32_Typeless, SharpDX.DXGI.Format.R32G32B32_Float
            Return SharpDX.WIC.PixelFormat.Format96bppRGBFloat
        Case SharpDX.DXGI.Format.R32G32B32_UInt, SharpDX.DXGI.Format.R32G32B32_SInt
            Return SharpDX.WIC.PixelFormat.Format96bppRGBFixedPoint
        Case SharpDX.DXGI.Format.R16G16B16A16_Typeless, SharpDX.DXGI.Format.R16G16B16A16_Float, SharpDX.DXGI.Format.R16G16B16A16_UNorm, SharpDX.DXGI.Format.R16G16B16A16_UInt, SharpDX.DXGI.Format.R16G16B16A16_SNorm, SharpDX.DXGI.Format.R16G16B16A16_SInt
            Return SharpDX.WIC.PixelFormat.Format64bppRGBA
        Case SharpDX.DXGI.Format.R32G32_Typeless, SharpDX.DXGI.Format.R32G32_Float, SharpDX.DXGI.Format.R32G32_UInt, SharpDX.DXGI.Format.R32G32_SInt, SharpDX.DXGI.Format.R32G8X24_Typeless, SharpDX.DXGI.Format.D32_Float_S8X24_UInt,
            SharpDX.DXGI.Format.R32_Float_X8X24_Typeless, SharpDX.DXGI.Format.X32_Typeless_G8X24_UInt
            Return Guid.Empty
        Case SharpDX.DXGI.Format.R10G10B10A2_Typeless, SharpDX.DXGI.Format.R10G10B10A2_UNorm, SharpDX.DXGI.Format.R10G10B10A2_UInt
            Return SharpDX.WIC.PixelFormat.Format32bppRGBA1010102
        Case SharpDX.DXGI.Format.R11G11B10_Float
            Return Guid.Empty
        Case SharpDX.DXGI.Format.R8G8B8A8_Typeless, SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb, SharpDX.DXGI.Format.R8G8B8A8_UInt, SharpDX.DXGI.Format.R8G8B8A8_SNorm, SharpDX.DXGI.Format.R8G8B8A8_SInt
            Return SharpDX.WIC.PixelFormat.Format32bppRGBA
        Case SharpDX.DXGI.Format.R16G16_Typeless, SharpDX.DXGI.Format.R16G16_Float, SharpDX.DXGI.Format.R16G16_UNorm, SharpDX.DXGI.Format.R16G16_UInt, SharpDX.DXGI.Format.R16G16_SNorm, SharpDX.DXGI.Format.R16G16_SInt
            Return Guid.Empty
        Case SharpDX.DXGI.Format.R32_Typeless, SharpDX.DXGI.Format.D32_Float, SharpDX.DXGI.Format.R32_Float, SharpDX.DXGI.Format.R32_UInt, SharpDX.DXGI.Format.R32_SInt
            Return Guid.Empty
        Case SharpDX.DXGI.Format.R24G8_Typeless, SharpDX.DXGI.Format.D24_UNorm_S8_UInt, SharpDX.DXGI.Format.R24_UNorm_X8_Typeless
            Return SharpDX.WIC.PixelFormat.Format32bppGrayFloat
        Case SharpDX.DXGI.Format.X24_Typeless_G8_UInt, SharpDX.DXGI.Format.R9G9B9E5_Sharedexp, SharpDX.DXGI.Format.R8G8_B8G8_UNorm, SharpDX.DXGI.Format.G8R8_G8B8_UNorm
            Return Guid.Empty
        Case SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.DXGI.Format.B8G8R8X8_UNorm
            Return SharpDX.WIC.PixelFormat.Format32bppBGRA
        Case SharpDX.DXGI.Format.R10G10B10_Xr_Bias_A2_UNorm
            Return SharpDX.WIC.PixelFormat.Format32bppBGR101010
        Case SharpDX.DXGI.Format.B8G8R8A8_Typeless, SharpDX.DXGI.Format.B8G8R8A8_UNorm_SRgb, SharpDX.DXGI.Format.B8G8R8X8_Typeless, SharpDX.DXGI.Format.B8G8R8X8_UNorm_SRgb
            Return SharpDX.WIC.PixelFormat.Format32bppBGRA
        Case SharpDX.DXGI.Format.R8G8_Typeless, SharpDX.DXGI.Format.R8G8_UNorm, SharpDX.DXGI.Format.R8G8_UInt, SharpDX.DXGI.Format.R8G8_SNorm, SharpDX.DXGI.Format.R8G8_SInt
            Return Guid.Empty
        Case SharpDX.DXGI.Format.R16_Typeless, SharpDX.DXGI.Format.R16_Float, SharpDX.DXGI.Format.D16_UNorm, SharpDX.DXGI.Format.R16_UNorm, SharpDX.DXGI.Format.R16_SNorm
            Return SharpDX.WIC.PixelFormat.Format16bppGrayHalf
        Case SharpDX.DXGI.Format.R16_UInt, SharpDX.DXGI.Format.R16_SInt
            Return SharpDX.WIC.PixelFormat.Format16bppGrayFixedPoint
        Case SharpDX.DXGI.Format.B5G6R5_UNorm
            Return SharpDX.WIC.PixelFormat.Format16bppBGR565
        Case SharpDX.DXGI.Format.B5G5R5A1_UNorm
            Return SharpDX.WIC.PixelFormat.Format16bppBGRA5551
        Case SharpDX.DXGI.Format.B4G4R4A4_UNorm
            Return Guid.Empty

        Case SharpDX.DXGI.Format.R8_Typeless, SharpDX.DXGI.Format.R8_UNorm, SharpDX.DXGI.Format.R8_UInt, SharpDX.DXGI.Format.R8_SNorm, SharpDX.DXGI.Format.R8_SInt
            Return SharpDX.WIC.PixelFormat.Format8bppGray
        Case SharpDX.DXGI.Format.A8_UNorm
            Return SharpDX.WIC.PixelFormat.Format8bppAlpha
        Case SharpDX.DXGI.Format.R1_UNorm
            Return SharpDX.WIC.PixelFormat.Format1bppIndexed
        Case Else

            Return Guid.Empty
    End Select
End Function

```

WIC Codec Info Page

---
Tags: c#, shaders, sharpdx, pixel, image-processing
---


# Question
Title: Possible legal pitfalls in font licensing for mobile games?
As I start to look into finding a the right font for a new mobile game I'm developing, I'm noticing that license agreements for fonts are pretty varied. Looking on advice for what pitfalls to avoid in choosing a distinctive font for a mobile game that will initially be free, but which we eventually plan to monetize.

My main concern is with a license that may not cover our intended uses, and lead to penalties.

We're willing to spend a little money in order to COA ("cover our butts")

# Answer
Font licensing is a big deal. As I stated previously, this is something that is covered in a general IT class, in my country. While it has been some time since I took a "general" IT class, the general idea is to make sure you *do* have permission to use the font.

It is important to note that I am not a lawyer, and not even a lawyer can really tell you if you *will* be sued. While this depends on location, you can really be sued for *anything*, provided the claimant is confident enough in their case to warrant the required expenditure. For this reason, it may not necessarily be a good idea to go off the consensus of the team. As Alexandre states, you may ultimately want to contact a copyright lawyer, for peace of mind.

---

> I'm noticing that license agreements for fonts are pretty varied

It depends where you look. A quick google search lead me to an article at Design Shack, which gives a very good overview of font licenses, and the need to acquire them.

> My main concern is with a license that may not cover our intended uses, and lead to penalties.

In general, you are looking for a *commercial* license. From what you tell us, your game is not currently in the commercial stage, but you think that you *might* make it commercial at some point. Consider the implications of making your game commercial, where you *do not* have commercial license to use the font.

If you do not "upgrade" your license, in this scenario, you lead yourself to further legal drama. You are using a font *outside* of its license agreement. If you intend to "upgrade" your license, you are going to have to chase up the original creator/publisher, and arrange a new license. What if you can not get in contact with the original creator/publisher, or they simply refuse, which they are completely within their right to do? You would have to start over, and find a completely new font.

---

***Where should I look for these fonts?***

* **fonts.com** explicitly lists "Licenses for Mobile Apps", which covers software you may install on an Android, iOS or Windows phone. There *is* a terms of use, but you do not need to be a lawyer to understand it, as it is written in no uncertain terms. This site also appears to offer a *subscription fee*, which may be a viable option; the fonts, themselves, are rather expensive. I doubt they would fall within your budget of "a little money", especially when the terms of service state that you must purchase a license multiple times, for inclusion in multiple pieces of software. You would have to buy another license if you intended to include the font in a future game.
* **1001 Free Fonts** offers a vast collection of fonts advertised as "free". I would not *assume* commercial license, but many do also offer the option to explicitly *purchase* a commercial license.
* **Google Fonts** *may* be an option; rather than directly selling you fonts, Google offers an API service that provides access to a broad range of open source fonts. Google explicitly states permit-able use for commercial use and applications, but I can not work out if it would be feasible to integrate this into your game.
* **MyFonts** is another site that explicitly states license to use the fonts in mobile applications. Across ten seperate fonts, every one of them offered a "pay once per unique application" license, and the fonts were far better priced than on fonts.com.
* Another user on a closed question suggests checking out **The League of Moveable Type**, a site that focuses on free, open-source fonts.
* **CheapProFonts** seems to be another suitable option. We have already had a user ask about using fonts from these guys \- and a company representative actually answered, directly, to confirm that the one license was adequate for use in his game.

---

***Are there any other options?***

As already stated, you have the option of simply contacting the creator and asking for permission. You would be surprised how many authors would post a font as "free", and not even consider the legal implications that their font may not actually be "free". This process should take you about five minutes, and if you do not end up using the font, there is no real penalty. Just make sure that if you *do* use the font, you respect any requests such as acknowledgement.

There is another suitable option; one that will not cost you any money, or risk any foreseeable legal drama: ***Make it yourself***.

Fonts *can* be rather complex, if you consider all of the styles and variations. If you can get away with defining your exact requirements, you may consider simply creating your own font. This is an option I have seen developers take, in the past. I have even seen developers use "creative license" to effectively hand draw the font they wished to use, based off copyrighted work that was outside of their budget. The new version could be considered their own work, and was therefore *legally*1 acceptable.

1 Note that *legal* is not the same as *ethical*; ultimately, you make that additional call on whether you consider this to be appropriate behavior. I would speculate that such action is only *pseudo-legal*, in that it would be next to impossible to actually proove, in court.
> 3 votes

---
Tags: licensing
---


title: Android build has white image over game

text:
# Question
Title: Android build has white image over game
In unity when I am playing my game it displays fine, but when I build and run it to my nexus 5 there is this white something I don't even know over my game. Any suggestions for fixes?

# Answer
> 1 votes
I Don't know why, but I just put the z value to 1 for quad and it made it work I just thought half the screen was in front and half was behind so if i made it 1 it would level it out. Thats probably not the reasoning but give it a try if you have half the screen as your quad.

---
Tags: unity, 2d, image, bug
---


# Question
Title: How do I scale a Spine animation at runtime?
The spine docummentation shows how to scale the skeleton when loading. Is it a must to reload the skeleton to scale the animation while playing it?

# Answer
This is done by manipulating the bone directly, as in this documentation: http://esotericsoftware.com/spine-using-runtimes#Manipulating-bones

The key here is that you have to perform the operation after calling AnimationState\_update/apply but *before* calling Skeleton\_updateWorldTransform:

```
Skeleton_update(spine->_Skeleton, dt);
AnimationState_update(spine->_AnimationState, dt);
AnimationState_apply(spine->_AnimationState, spine->_Skeleton);

// Now that the animation has applied any changes, provide our own manipulations:
spine->_Skeleton->x = transform->position.x;
spine->_Skeleton->y = transform->position.y;
spine->_Skeleton->root->scaleX = 0.5f;
spine->_Skeleton->root->scaleY = 0.5f;

spine->_Skeleton->root->rotation = 45.0f;

Skeleton_updateWorldTransform(spine->_Skeleton);

```
> 1 votes

---
Tags: sfml, spine
---


# Question
Title: What's the difference between setTransformMatrix and setProjectionMatrix in LibGDX?
There are two method of `SpriteBatch` in LibGDX: `setTransformMatrxi` and `setProjectionMatrix`.

I know one can use `batch.setProjectionMatrix(camera.combined)` to define how/where an object should be rendered on the screen. But then what does `setTransformMatrix` do?

I googled "difference between transform matrix and projection matrix" but no luck.

# Answer
> 1 votes
Transformation matrix:

This matrix defines **where** to render your geometry.

Projection matrix:

Don't use this matrix to move stuff around, it's not meant to. This matrix defines **how** to render your geometry. For example, this can make the game render in a perspective projection (things farther away are smaller) or in an ortographic projection (everything is the same size). This is where `camera.combined` should go.

They aren't interchangeable, because they get multiplied in the shaders, and matrix multiplication is not cummulative.

---
Tags: libgdx, mathematics, matrix
---


title: Hold button down by mouse?

text:
# Question
Title: Hold button down by mouse?
When I hold down a button by mouse for 5 seconds, print a message. How to do this ? I wrote this script but is not working. I don't know if there other methods.

```
Public float clock;
Public Button out;

public void quit_out_mouse() {
    clock = Time.time;
    if(Time.time - clock > 3.0f )       {
        Debug.Log (" gone !! ");
    }

   }

```

# Answer
I don't think the code of @virtouso would work : It's not frame independent and if you hold the button down for 2 seconds, release it, the timer will not reset

```
public float duration = 6 ;
private float timer = 0;
private bool waitingButtonUp = false ;

private void Update()
{
    // Use waiting button up if you don't want the function to be called every 6 seconds
    // but you want the user to release the mouse button before being able to call
    // the function after pressing the button again
    if( Input.GetMouseButton(0) && !waitingButtonUp )
    {
        timer += Time.deltaTime ;
    }
    else // Do not forget to reset timer when the button is not pressed anymore
    {
        timer = 0 ;
        waitingButtonUp = false;
    }

    if( timer > duration )
    {
        DoSomething();
        waitingButtonUp = true ;
        timer = 0 ;
    }
}

private void DoSomething()
{

}

```
> 2 votes

---
Tags: unity, gui
---


title: A* algorithm works silly with heap

text:
# Question
Title: A* algorithm works silly with heap
I'm trying to use A\* and visualised it, but when i add a heap optimization it start looking in incredeble ways sometimes normal(better then next to be sure), somtimes he looks on few columns.

Normal working without heap

Code:

Pathfinding.h

```
#pragma once
#include "Node.h"
#include<iostream>
#include "Heap.h"

class Pathfinding
{
public:
    std::vector<Node*> openSet;
    std::vector<Node*> closedSet;
    std::vector<Node*> path;
    std::vector<std::vector<Node*>> grid;
    Node* startNode;
    Node* targetNode;
    bool intialized = false;
    int cols;
    int rows;
    bool find = false;
    Pathfinding(int _cols, int _rows, std::vector<std::vector<Node*>> _grid);
    ~Pathfinding();

    void FindPath(Node* start, Node* target);
    void SetStartAndGoal(Node* start, Node* goal);
    int GetDistance(Node* nodeA, Node* nodeB);
};

```

Pathfinding.cpp

```
#include "Pathfinding.h"

Pathfinding::Pathfinding(int _cols, int _rows, std::vector<std::vector<Node*>> _grid)
{
cols = _cols;
rows = _rows;
grid = _grid;
}

Pathfinding::~Pathfinding()
{
delete startNode;
delete targetNode;
openSet.clear();
closedSet.clear();
path.clear();
}

void Pathfinding::FindPath(Node* start, Node* target)
{
if (!intialized)
{

    openSet.clear();
    closedSet.clear();
    path.clear();

    std::make_heap(openSet.begin(), openSet.end());

    SetStartAndGoal(start, target);

    intialized = true;
}
if (intialized)
{
    if (!find)
    {
        if (openSet.size() > 0)
        {
            Node* current = openSet.front();

            std::pop_heap(openSet.begin(), openSet.end());
            openSet.pop_back();

            if (current == targetNode)
            {
                Node* temp = current;
                path.push_back(temp);
                while (temp->parent)
                {
                    path.push_back(temp->parent);
                    temp = temp->parent;
                }
                std::cout << "DONE!";
                find = true;
            }

            closedSet.push_back(current);

            for (int i = -1; i <= 1; i++)
            {
                for (int j = -1; j <= 1; j++)
                {
                    if (i == 0 && j == 0)
                        continue;

                    int checkX = current->x + i;
                    int checkY = current->y + j;

                    if (checkX >= 0 && checkX < cols && checkY >= 0 && checkY < rows)
                    {
                        Node* neighbor = grid[checkX][checkY];
                        bool inClosed = false;
                        for (int k = 0; k < closedSet.size(); k++)
                        {
                            if (neighbor == closedSet[k])
                            {
                                inClosed = true;
                            }
                        }
                        if (!inClosed && neighbor->walkable)
                        {
                            int tempG = current->g + GetDistance(current, neighbor);

                            bool inOpen = false;
                            for (int k = 0; k < openSet.size(); k++)
                            {
                                if (neighbor == openSet[k])
                                {
                                    inOpen = true;
                                }
                            }
                            if (inOpen)
                            {
                                if (tempG < neighbor->g)
                                {
                                    neighbor->g = tempG;
                                    neighbor->parent = current;
                                }
                            }
                            else
                            {
                                neighbor->g = tempG;
                                openSet.push_back(neighbor);
                                std::push_heap(openSet.begin(), openSet.end());
                                neighbor->parent = current;
                            }
                            neighbor->h = GetDistance(neighbor, targetNode);
                            neighbor->f = neighbor->g + neighbor->h;

                        }
                    }
                }
            }
        }
        else
        {
            std::cout << "NO SOLUTION";
            find = true;
        }
    }
}
}

void Pathfinding::SetStartAndGoal(Node* start, Node* goal)
{
startNode = new Node(start->x, start->y);
targetNode = new Node(goal->x, goal->y);

startNode = start;
targetNode = goal;

startNode->g = 0;
startNode->h = GetDistance(startNode, targetNode);
startNode->parent = 0;

openSet.push_back(startNode);
std::push_heap(openSet.begin(), openSet.end());
}

int Pathfinding::GetDistance(Node* nodeA, Node* nodeB)
{
int dstX = fabs(nodeA->x - nodeB->x);
int dstY = fabs(nodeA->y - nodeB->y);

if (dstX > dstY)
    return 14 * dstY + 10 * (dstX - dstY);
return 14 * dstX + 10 * (dstY - dstX);
}

bool cmp(const Node &a, const Node &b)
{
if (a.f == b.f)
    if (a.h > b.h)
        return true;
    else
        return false;
else if (a.f > b.f)
    return true;
else
    return false;
}

```

Node.h

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

class Node
{
public:
int x, y;
float f = 0;
float g = 0;
float h = 0;
bool walkable = true;
Node* parent = NULL;
sf::Color col = sf::Color::White;
Node(int i, int j);
~Node();
};

```

Node.cpp

```
#include "Node.h"

Node::Node(int i, int j)
{
x = i;
y = j;
}

Node::~Node()
{}

```

main

```
#include <SFML/Graphics.hpp>
#include "Node.h"
#include <windows.h>
#include <time.h>
#include "Pathfinding.h"

int cols = 50;
int rows = 50;
int width = 800;
int height = 800;
int w, h;

std::vector<std::vector<Node*>> grid;
std::vector<Node*> tempGrid;

std::vector<Node*> openSet;
std::vector<Node*> closedSet;
std::vector<Node*> path;
Node* start;
Node* end;

int main()
{
//srand(time(NULL));

sf::RenderWindow window(sf::VideoMode(width, height), "A*");

w = width / cols;
h = height / rows;

for (int i = 0; i < cols; i++)
{
    for (int j = 0; j < rows; j++)
    {
        Node* node = new Node(i, j);
        float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
        if (r < 0.3 && !(i == 0 && j == 0 || i == cols - 1 && j == rows - 1))
            node->walkable = false;
        tempGrid.push_back(node);
    }
    grid.push_back(tempGrid);
    tempGrid.clear();
}

Pathfinding pathfind(cols, rows, grid);

while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
    }

    //algorithm

    pathfind.FindPath(grid[0][0], grid[cols - 1][rows - 1]);
    openSet = pathfind.openSet;
    closedSet = pathfind.closedSet;
    path = pathfind.path;

    //draw

    window.clear(sf::Color::Black);

    for (int i = 0; i < closedSet.size(); i++)
    {
        closedSet[i]->col = sf::Color::Red;
    }

    for (int i = 0; i < openSet.size(); i++)
    {
        openSet[i]->col = sf::Color::Green;
    }

    for (int i = 0; i < path.size(); i++)
    {
        path[i]->col = sf::Color::Blue;
    }

    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            sf::RectangleShape rectangle(sf::Vector2f(w, h));
            rectangle.setPosition(i*w, j*h);
            if (!grid[i][j]->walkable)
                rectangle.setFillColor(sf::Color::Black);
            else
                rectangle.setFillColor(grid[i][j]->col);
            rectangle.setOutlineThickness(-1);
            rectangle.setOutlineColor(sf::Color::Black);
            window.draw(rectangle);
        }
    }

    window.display();
}

for (int i = 0; i < grid.size(); i++)
{
    grid[i].clear();
}
grid.clear();

return 0;

```

}

What I doing wrong?

Thanks for help!

# Answer
```
if (tempG < neighbor->g)
{
    neighbor->g = tempG;
    neighbor->parent = current;
}

```

After this the heap needs to be updated so the neighbor properly bubbles up to preserve the heap property.

It would be much easier if there was a `std::change_element_heap(begin, end, it);` which assumes that except for the element at `it`, the heap invariant holds and then fixes the heap. It's possible to implement that yourself. It still requires that you find where the Node is in the heap before you can update it.
> 1 votes

---
Tags: c++, algorithm, path-finding
---


title: Efficient way to render tilemap

text:
# Question
Title: Efficient way to render tilemap
I have set up a tilemap system, and am rendering it in a way that lets me pan through the map using a camera offset. However, I have discovered it is incredibly inefficient, but am unsure of how I can increase efficiency.

Here is my current rendering code:

```
float lastCamOffSetX = -1, lastCamOffSetY = -1;

public override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);
    spriteBatch.Begin();

    int count = 0;

    int startCol = (int)camOffsetX/world.TileWidth;
    int startRow = (int)camOffsetY/world.TileHeight;
    int endCol = (int)(startCol + viewPortWidth - (camOffsetX/world.TileWidth));
    int endRow = (int)(startRow + viewPortHeight - (camOffsetY/world.TileHeight));

    if (startCol < 0) startCol = 0;
    if (startRow < 0) startRow = 0;

    if (endCol > world.Width) endCol = world.Width;
    if (endRow > world.Height) endRow = world.Height;

    for (int x = startCol; x < endCol; x++)
    {
        for (int y = startRow; y < endRow; y++)
        {
            int screenPosX = (int)((x * world.TileWidth) - (camOffsetX));
            int screenPosY = (int)((y * world.TileHeight) - (camOffsetY));

            Tile tile = world.Data[x, y];

            if (screenPosX >= -1 * world.TileWidth
                && screenPosX <= (viewPortWidth + 1) * world.TileWidth
                && screenPosY >= -1 * world.TileHeight
                && screenPosY <= (viewPortHeight + 1) * world.TileHeight)
            {
                Color color
                    = (tile.TileType == TileType.Land ? Color.Green : Color.Blue);

                DrawRectangle(spriteBatch, new Rectangle(screenPosX,
                    screenPosY, world.TileWidth, world.TileHeight), color);

                count++;
            }
        }
    }

    //Debug.WriteLine(count + " - " + (endCol-startCol)*(endRow-startRow));

    spriteBatch.End();

    lastCamOffSetX = camOffsetX;
    lastCamOffSetY = camOffsetY;
}

private void DrawRectangle(SpriteBatch spriteBatch, Rectangle coords, Color color)
{
    var rect = new Texture2D(this.GraphicsDevice, 1, 1);
    rect.SetData(new[] { color });
    spriteBatch.Draw(rect, coords, color);
}

```

Currently, I am only drawing tiles which are inside the screen/camera region. How can I improve the efficiency of my script?

# Answer
> 1 votes
your DrawRectangle is the bottleneck. Creating a texture is a very very expensive operation. Create the texture first and than use the reference from it to draw it.

# Answer
> 1 votes
You are creating a new texture every frame (and even worse, inside `Draw()` instead of `Update()`).

```
private void DrawRectangle(SpriteBatch spriteBatch, Rectangle coords, Color color)
{
    var rect = new Texture2D(this.GraphicsDevice, 1, 1);
    rect.SetData(new[] { color });
    spriteBatch.Draw(rect, coords, color);
}

```

You could create a more permanent variable to hold the texture and then reuse the texture over and over. Since you are using a color there are two ways about this.

Use a dictionary of sorts and cache a color when it comes across it and just create a new texture if the color does not already exist. This may be a bit overkill in this situation.

A better way would be to create the texture once and use `SpriteBatch` to tint it, you need to set your textures color to white, this can be done such as:

```
Texture2D rect = ... // do your new texture here. 1x1 and colored Color.White.
// Create this ONCE! not inside Update or Draw loops.

public override void Draw(GameTime gameTime)
{
    // Start of your drawing code

    Color color = GetColorLogicMethod(); // or your inline stuff above.
    spriteBatch.Draw(rect, coords, color); // This will tint the White 1x1 with the new color.

    // Rest of your drawing code
}

```

This way the expensive `new Texture2D()` and `Texture2D.SetData()` are only done once. The rest of your code looks like it should be pretty good as it is now for what you are doing.

---
Tags: c#, xna, tiles, maps
---