# Question
Title: How can I shorten the length of time spent on finding a path using my A* pathfinding code?
I am working on a game where the player and enemies move between discreet tiles, with only orthagonal movement (like pokemon). The game also runs on a turn system, so the player makes a move input, then the enemies calculate their paths and begin moving simultaneously with the player to the first node in their path. My enemies calculate their paths one after another and set move points at the position they intend to travel to. This lets enemies check if there is already a move point where they are trying to pathfind to, in which case they'll choose an alternate adjacent point to move to. After all the paths are calculated the enemies move simultaneously. I also implemented enemy aggro, so only enemies within the bounds of the camera path to the player. The rest path to a random adjacent node to keep the paths short. My problem is I've been playtesting with 20 enemies on a reasonably small grid (56x28) and it takes 130 ms or so to calculate the paths of all the enemies. This results in some pretty undesirable movement, since the player's control is locked until all enemies have finished moving. The player noticeably pauses for the enemies to finish moving in between taking steps.

I've posted the relevant sections of my code below, does anyone see a glaring issue with how I'm approaching this? I've adapted a pathfinding tutorial series by Sebastian Lague on YouTube to fit my game. I also looked at the A\* Pathfinding Project by Aron Granburg, but stayed away from it because it looked much more complicated to adapt to my specific project. If anyone is familiar with the A\* pathfinding project, is it highly optimized to the point where it might be worth it to scrap what I have and try to use that instead?

Also relevant: I changed my fixed timestep in my unity project settings to 0.001 from 0.02. Since I had to include a WaitForFixedUpdate to make sure enemies were accurately checking for collision this sped up the enemy turns quite a bit, and it doesn't seem to have created significant overhead.

Also also relevant (maybe): Performance differs when I have the scene view open. In this case enemy pathfinding takes ~ 255 ms rather than the ~130 ms when the game view is maximized.

Edit: Thanks for all the useful info everyone! I’m going through and implementing several suggestions to fine tune everything, but I found the major source of the problem. In turn system.cs I had a waitforfixedupdate, which I assumed would add an option extra 1 ms per enemy that was pathfinding. This was necessary because the physics 2D overlap circles I used to check collision weren’t always giving me accurate results otherwise. Well, turns out my computer wasn’t managing to keep up with the 0.001s fixed timestep interval and the waitforfixedupdates were adding more wait time than intended. I stumbled across Physics.synctransforms and used that where I had the fixed update, then set my fixed timestep back to the default 0.02s. Worked like a charm, collision checks are all working correctly and the pathfinding went from taking 130ms to about 40ms.

From TurnSystem.cs:

```
        public IEnumerator EnemyTurn(bool playerTookMoveAction)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            playerController.LockControl(true);

            sw.Start();
            WaitForFixedUpdate wait = new WaitForFixedUpdate();
            for (int i = 0; i < enemies.Count; i++)
            {
                if (enemies[i].GetTookFightAction()) continue;
                yield return StartCoroutine(enemies[i].SetMovePoint());
                yield return wait;
            }

            sw.Stop();
            print("Elapsed Time: " + sw.ElapsedMilliseconds/1000f);

            for (int i = 0; i < enemies.Count; i++)
            {
                if (enemies[i].GetTookFightAction()) continue;
                StartCoroutine(enemies[i].TakeStep());
            }

            while(enemiesFinishedAction < enemies.Count)
            {
                yield return null;
            }
            enemiesFinishedAction = 0;

            for (int i = 0; i < enemies.Count; i++)
            {
                enemies[i].SetAggro();
            }

            StartCoroutine(playerController.UnlockControlAfterMovement());
            OnReadyToSpawn();
        }

        public void AddEnemy(EnemyAIController enemy)
        {
            enemies.Add(enemy);
        }

        public void RemoveEnemy(EnemyAIController enemy)
        {
            enemies.Remove(enemy);
        }

        public void EnemyFinishedAction()
        {
            enemiesFinishedAction++;
        }

```

From EnemyAIController.cs:

```
        public void OnPathFound(Vector2[] newPath, bool pathSuccessful)
        {
            if (pathSuccessful && newPath.Length > 0)
            {
                path = newPath;
            }
        }

        public IEnumerator SetMovePoint()
        {
            if (!isLocked)
            {
                if (isAggroed)
                {
                    target = playerMovePoint.position;
                }
                else
                {
                    target = GetRandomAdjacentTarget();
                }
                yield return PathRequestManager.RequestPath(transform.position, target, OnPathFound);
                if (path != null && !Physics2D.OverlapCircle(path[0], 0.3f, collisionLayer))
                {
                    movePoint.position = path[0];
                }
                else
                {
                    movePoint.position = GetAlternateWaypoint();
                }
            }
            else yield return null;
        }

        protected Vector2 GetRandomAdjacentTarget()
        {
            float random = UnityEngine.Random.Range(0,4);
            if (random == 0) return new Vector2 (transform.position.x, transform.position.y - 2);
            if (random == 1) return new Vector2 (transform.position.x - 2, transform.position.y);
            if (random == 2) return new Vector2 (transform.position.x, transform.position.y + 2);
            if (random == 3) return new Vector2 (transform.position.x + 2, transform.position.y);
            return transform.position;
        }

        protected Vector2 GetAlternateWaypoint()
        {
            if (path != null && path[0] != null && path[0] != (Vector2)movePoint.position)
            {
                if(path[0].x != movePoint.position.x)
                {
                    if (target.y > movePoint.position.y && !Physics2D.OverlapCircle(new Vector2(movePoint.position.x, movePoint.position.y + 1), 0.3f, collisionLayer))
                    {
                        return new Vector2(movePoint.position.x, movePoint.position.y + 1);
                    }
                    else if (target.y <= movePoint.position.y && !Physics2D.OverlapCircle(new Vector2(movePoint.position.x, movePoint.position.y - 1), 0.3f, collisionLayer))
                    {
                        return new Vector2(movePoint.position.x, movePoint.position.y - 1);
                    }
                }
                else if (path[0].y != movePoint.position.y)
                {
                    if (target.x > movePoint.position.x && !Physics2D.OverlapCircle(new Vector2(movePoint.position.x + 1, movePoint.position.y), 0.3f, collisionLayer))
                    {
                        return new Vector2(movePoint.position.x + 1, movePoint.position.y);
                    }
                    else if (target.x <= movePoint.position.x && !Physics2D.OverlapCircle(new Vector2(movePoint.position.x - 1, movePoint.position.y), 0.3f, collisionLayer))
                    {
                        return new Vector2(movePoint.position.x - 1, movePoint.position.y);
                    }
                }
            }
            return movePoint.position;
        }

```

From PathRequestManager.cs:

```
public class PathRequestManager : MonoBehaviour
    {
        Queue<PathRequest> pathRequestQueue = new Queue<PathRequest>();
        PathRequest currentPathRequest;

        static PathRequestManager instance;
        Pathfinding pathfinding;

        bool isProcessingPath;

        private void Awake()
        {
            instance = this;
            pathfinding = GetComponent<Pathfinding>();
        }

        public static IEnumerator RequestPath(Vector2 pathStart, Vector2 pathEnd, Action<Vector2[], bool> callback)  //does this need to be static?
        {
            PathRequest newRequest = new PathRequest(pathStart, pathEnd, callback);
            instance.pathRequestQueue.Enqueue(newRequest);
            instance.TryProcessNext();
            yield return null;
        }
        private void TryProcessNext()
        {
            if (!isProcessingPath && pathRequestQueue.Count > 0)
            {
                currentPathRequest = pathRequestQueue.Dequeue();
                isProcessingPath = true;
                pathfinding.StartFindPath(currentPathRequest.pathStart, currentPathRequest.pathEnd);
            }
        }

        public void FinishedProcessingPath(Vector2[] path, bool success)
        {
            currentPathRequest.callback(path, success);
            isProcessingPath = false;
            TryProcessNext();
        }

        struct PathRequest
        {
            public Vector2 pathStart;
            public Vector2 pathEnd;
            public Action<Vector2[], bool> callback;

            public PathRequest(Vector2 _start, Vector2 _end, Action<Vector2[], bool> _callback)
            {
                pathStart = _start;
                pathEnd = _end;
                callback = _callback;
            }
        }
    }

```

From Pathfinding.cs:

```
    public class Pathfinding : MonoBehaviour
    {
        PathRequestManager requestManager;
        AStarGrid grid;

        private void Awake()
        {
            requestManager = GetComponent<PathRequestManager>();
            grid = GetComponent<AStarGrid>();
        }

        public void StartFindPath(Vector2 startPos, Vector2 targetPos)
        {
            StartCoroutine(FindPath(startPos, targetPos));
        }

        IEnumerator FindPath(Vector2 startPos, Vector2 targetPos)
        {
            Vector2[] waypoints = new Vector2[0];
            bool pathSuccess = false;

            Node startNode = grid.NodeFromWorldPoint(startPos);
            Node targetNode = grid.NodeFromWorldPoint(targetPos);

            if(startNode.walkable && targetNode.walkable)
            {
                Heap<Node> openSet = new Heap<Node>(grid.MaxSize);
                HashSet<Node> closedSet = new HashSet<Node>();
                openSet.Add(startNode);

                while (openSet.Count > 0)
                {
                    Node currentNode = openSet.RemoveFirst();
                    closedSet.Add(currentNode);

                    if (currentNode == targetNode)//found the path
                    {
                        pathSuccess = true;
                        break;
                    }

                    foreach(Node neighbor in grid.GetNeighbors(currentNode))
                    {
                        if(!neighbor.walkable || closedSet.Contains(neighbor)) continue;
                        int newMovementCostToNeighbor = currentNode.gCost + GetDistance(currentNode, neighbor);
                        if (newMovementCostToNeighbor < neighbor.gCost || !openSet.Contains(neighbor))
                        {
                            neighbor.gCost = newMovementCostToNeighbor;
                            neighbor.hCost = GetDistance(neighbor, targetNode);
                            neighbor.parent = currentNode;

                            if (!openSet.Contains(neighbor))
                            {
                                openSet.Add(neighbor);
                            }
                            else
                            {
                                openSet.UpdateItem(neighbor);
                            }
                        }
                    }
                }
            }
            yield return null;
            if (pathSuccess)
            {
                waypoints = RetracePath(startNode, targetNode);
            }
            requestManager.FinishedProcessingPath(waypoints, pathSuccess);
        }

        Vector2[] RetracePath(Node startNode, Node endNode)
        {
            List<Node> path = new List<Node>();
            Node currentNode = endNode;

            while(currentNode != startNode)
            {
                path.Add(currentNode);
                currentNode = currentNode.parent;
            }
            Vector2[] waypoints = SimplifyPath(path);
            // Array.Reverse(waypoints);
            return waypoints;
        }

        Vector2[] SimplifyPath(List<Node> path)//I simplified this section of code since I just needed the first waypoint of the path returned, this did help performance
        {
            List<Vector2> waypoints = new List<Vector2>();
            // Vector2 directionOld = Vector2.zero;

            for(int i = Mathf.Max(path.Count - 1, 0); i < path.Count; i ++)
            // for(int i = 1; i < path.Count; i ++)
            {
                // Vector2 directionNew = new Vector2(path[i-1].gridX - path[i].gridX, path[i-1].gridY - path[i].gridY);
                // if(directionNew != directionOld)
                // {

                    waypoints.Add(path[i].worldPosition);
                // }
                // directionOld = directionNew;
            }
            return waypoints.ToArray();
        }

        int GetDistance(Node nodeA, Node nodeB)
        {
            int distanceX = Mathf.Abs(nodeA.gridX - nodeB.gridX);
            int distanceY = Mathf.Abs(nodeA.gridY - nodeB.gridY);

            return distanceX + distanceY;
        }
    }

```

From node.cs:

```
    public class Node : IHeapItem<Node>
    {
        public bool walkable;
        public Vector2 worldPosition;
        public int gridX;
        public int gridY;

        public int gCost;
        public int hCost;
        public Node parent;
        int heapIndex;

        public Node( bool _walkable, Vector2 _worldPos, int _gridX, int _gridY)
        {
            walkable = _walkable;
            worldPosition = _worldPos;
            gridX = _gridX;
            gridY = _gridY;
        }

        public int fCost
        {
            get
            {
                return gCost + hCost;
            }
        }

        public int HeapIndex
        {
            get
            {
                return heapIndex;
            }
            set
            {
                heapIndex = value;
            }
        }

        public int CompareTo(Node nodeToCompare)
        {
            int compare = fCost.CompareTo(nodeToCompare.fCost);
            if (compare == 0)
            {
                compare = hCost.CompareTo(nodeToCompare.hCost);
            }
            return -compare;
        }
    }

```

From Heap.cs

```
    public class Heap<T> where T : IHeapItem<T> {

        T[] items;
        int currentItemCount;

        public Heap(int maxHeapSize) {
            items = new T[maxHeapSize];
        }

        public void Add(T item) {
            item.HeapIndex = currentItemCount;
            items[currentItemCount] = item;
            SortUp(item);
            currentItemCount++;
        }

        public T RemoveFirst() {
            T firstItem = items[0];
            currentItemCount--;
            items[0] = items[currentItemCount];
            items[0].HeapIndex = 0;
            SortDown(items[0]);
            return firstItem;
        }

        public void UpdateItem(T item) {
            SortUp(item);
        }

        public int Count {
            get {
                return currentItemCount;
            }
        }

        public bool Contains(T item) {
            return Equals(items[item.HeapIndex], item);
        }

        void SortDown(T item) {
            while (true) {
                int childIndexLeft = item.HeapIndex * 2 + 1;
                int childIndexRight = item.HeapIndex * 2 + 2;
                int swapIndex = 0;

                if (childIndexLeft < currentItemCount) {
                    swapIndex = childIndexLeft;

                    if (childIndexRight < currentItemCount) {
                        if (items[childIndexLeft].CompareTo(items[childIndexRight]) < 0) {
                            swapIndex = childIndexRight;
                        }
                    }

                    if (item.CompareTo(items[swapIndex]) < 0) {
                        Swap (item,items[swapIndex]);
                    }
                    else {
                        return;
                    }

                }
                else {
                    return;
                }

            }
        }

        void SortUp(T item) {
            int parentIndex = (item.HeapIndex-1)/2;

            while (true) {
                T parentItem = items[parentIndex];
                if (item.CompareTo(parentItem) > 0) {
                    Swap (item,parentItem);
                }
                else {
                    break;
                }

                parentIndex = (item.HeapIndex-1)/2;
            }
        }

        void Swap(T itemA, T itemB) {
            items[itemA.HeapIndex] = itemB;
            items[itemB.HeapIndex] = itemA;
            int itemAIndex = itemA.HeapIndex;
            itemA.HeapIndex = itemB.HeapIndex;
            itemB.HeapIndex = itemAIndex;
        }

    }

    public interface IHeapItem<T> : IComparable<T> {
        int HeapIndex {
            get;
            set;
        }
    }

```

From AStarGrid.cs

```
    public class AStarGrid : MonoBehaviour
    {
        public bool displayGridGizmos;
        public LayerMask unwalkableMask;
        public Vector2 gridWorldSize;
        public float nodeRadius;
        Node[,] grid;

        float nodeDiameter;
        int gridSizeX, gridSizeY;

        private void Awake()
        {
            nodeDiameter = nodeRadius *2;
            gridSizeX = Mathf.RoundToInt(gridWorldSize.x/nodeDiameter);
            gridSizeY = Mathf.RoundToInt(gridWorldSize.y/nodeDiameter);
            CreateGrid();
        }

        public int MaxSize
        {
            get
            {
                return gridSizeX * gridSizeY;
            }
        }

        private void CreateGrid()
        {
            grid = new Node[gridSizeX, gridSizeY];
            Vector2 worldBottomLeft = (Vector2)transform.position - Vector2.right * gridWorldSize.x/2 - Vector2.up * gridWorldSize.y/2;

            for (int x = 0; x < gridSizeX; x++)
            {
                for (int y = 0; y < gridSizeY; y++)
                {
                    Vector2 worldPoint = worldBottomLeft + Vector2.right * (x * nodeDiameter + nodeRadius) + Vector2.up * (y * nodeDiameter + nodeRadius);
                    bool walkable = (Physics2D.OverlapCircle(worldPoint,nodeRadius,unwalkableMask) == null);
                    grid[x,y] = new Node (walkable, worldPoint, x, y);
                }
            }
        }

        public List<Node> GetNeighbors(Node node)
        {
            List<Node> neighbors = new List<Node>();

            for (int x = -1; x <= 1; x++)
            {
                for (int y = -1; y <= 1; y++)
                {
                    if (x == 0 && y == 0 || Mathf.Abs(x) + Mathf.Abs(y) == 2) continue;

                    int checkX = node.gridX + x;
                    int checkY = node.gridY + y;

                    if(checkX >= 0 && checkX < gridSizeX && checkY >= 0 && checkY < gridSizeY)// if checkX and checkY are on the grid
                    {
                        neighbors.Add(grid[checkX, checkY]);
                    }
                }
            }

            return neighbors;
        }

        public Node NodeFromWorldPoint(Vector2 worldPosition)
        {
            float percentX = worldPosition.x / gridWorldSize.x + 0.5f;
            float percentY = worldPosition.y / gridWorldSize.y + 0.5f;

            int x = Mathf.FloorToInt(Mathf.Clamp((gridSizeX) * percentX, 0, gridSizeX - 1));
            int y = Mathf.FloorToInt(Mathf.Clamp((gridSizeY) * percentY, 0, gridSizeY - 1));

            return grid[x,y];
        }

        public List<Node> path;
        void OnDrawGizmos()
        {
        Gizmos.DrawWireCube(transform.position,new Vector2(gridWorldSize.x,gridWorldSize.y));
        if (grid != null && displayGridGizmos) {
            foreach (Node n in grid) {
                Gizmos.color = Color.red;
                if (n.walkable)
                    Gizmos.color = Color.white;

                Gizmos.DrawCube(n.worldPosition, Vector3.one * (nodeDiameter-.8f));
            }
        }
        }
    }

```

# Answer
Let's start with some general C# optimization advice:

**Avoid heap allocations in your hot path**. That means anywhere you have `new Foo(...)` where `Foo` is a reference type (that's any `class`, including any collections like arrays, lists, sets, heaps, etc).

* If you're going to finish your work with this one, then make another one for the next job (eg. your open / closed set collections), just keep a persistent one and re-use it, calling `Clear()` or the equivalent before each new use.

Fun fact: `YieldInstructions` like `WaitForFixedUpdate` can be reused this way. You don't need to allocate a `new` one every time you want to yield. You can even store a single one as a `static readonly` variable for all your yields to reference.
* If you're returning a collection of results, definitely don't create a new zero-capacity array then replace it like you're doing with `waypoints = new Vector2[0]` \- that's a completely useless heap allocation. Just let the variable be `null` in the event that no waypoints are provided, and handle the `null` case in the code that consumes it.

You can even get rid of the allocation for the returned collection in `SimplifyWaypoints` and similar methods, by following the pattern used by Unity's own `NonAlloc` methods: accept a list or array as one of the method parameters, and store your results there (and if using an array, return the number of items so the caller knows how much of the buffer is the new data). That lets the caller re-use one collection instead of allocating new ones.
* When using variable-sized collections (`List`, `HashSet`, `Heap`, etc.), pre-size them for the capacity you're likely to need. Under the hood, these data structures allocate a small buffer of memory for starters, and when you add more items than they have room for, they allocate a new, larger buffer and move their contents over to that. By telling them how much space you expect them to need up-front, by passing a number to the constructor, you avoid doing these shuffles in the middle of your work. (Re-using your containers helps here too - you pay the resizing cost early on, but once the structure has "warmed up" it doesn't need resizing again on the next use)
* Where you can, use value types instead of reference types. These don't require a separate heap allocation if used as temporaries inside a method, and they piggyback on the parent's allocation when stored as member variables or placed inside a collection (provided the type of the storage location matches - that you're not casting them to an interface that would cause boxing). These can also be faster to access, since they're stored directly in the parent container's memory, rather than storing just a pointer that needs to be chased. When doing lots of iterations, this can improve cache locality.

Instead of a class for `Node`, can you make it a `struct`? You can use a "Structure of Arrays" approach to unpack your node class into multiple arrays that store stuff *about* the nodes. Your open set could just store `Vector2Int` coordinates for each node (or your own custom version that uses `short` or `sbyte` for compactness), and then you can use those coordinates to look up or compute the cost / position / etc. when needed.

Now let's look at **algorithmic improvements** specific to the pathfinding problem:

* When you have many agents pathfinding toward the same goal, it can be faster to **reverse the problem**: pathfind *from* the goal (player) *to* the agent (enemy).

This lets you re-use data from the previous pathfinding attempt. After agent 1 has finished their A\* search, your node grid contains exactly correct path distances to the player from every tile along agent 1's path, and many adjacent tiles evaluated along the way. If agent 2 is somewhat near agent 1, or their shortest paths converge along the way, then their A\* search will want to look at many of the same tiles, where it can find the right answer already recorded, with no re-computation or heuristic guessing.
* If you have *many* enemies all over the map, so that you're probably going to search the majority of the tiles *anyway*, then you can **use a simpler algorithm**: just do a breadth-first search of walkable tiles out from the player's position, and record the search depth at each tile (if all tiles have the same traversal cost - if not, use Dijkstra's algorithm instead). This produces what's called a distance field. Agents can then find a path to the player from anywhere just by "rolling down-hill" - checking the distance values at their adjacent tiles, and moving into whichever one has the lower number.

This might initially look like a pessimization because it involves iterating *every* tile on the map, but it visits each tile only once, and the code executed per node is much simpler, so this tends to be a net win when your agent counts are large and your map is small.
* Since you only want enemies to pathfind to the player when they're within the camera bounds, generate a distance field as above but windowed to just those bounds plus a few tiles' margin. Now the most expensive part - writing a value for every reachable tile - is cut down to just writing a value for every reachable tile *on-screen* (or very nearly).
* If agents are off-screen, does it matter whether they're following a path toward a randomly-chosen goal? Will the player be able to tell, when they get close to the agent, that it got to where it is by following a path? If not, you might be able to massively simplify the behaviour of off-screen agents: just have them do a random walk. Each time they want to move a tile, pick an adjacent walkable tile at random (possibly excluding tiles outside the agent's designated "wander zone").

When the player encounters the agent, they'll find it on some random tile near its start point, just like with the more expensive path-finding approach, and now that it's on screen it will start using goal-following behaviour so it doesn't look random anymore.

Lastly (and this should probably be your *last* resort), you can use threads to do the pathfinding work in the background - especially for off-screen enemies. This keeps it from blocking the main thread, and lets you continue working on your pathfinding even while the engine is doing other work, or even compute paths for multiple agents in parallel rather than sequentially. But multithreading can significantly increase the complexity of your code and introduce new opportunities for bugs, so you should try to exhaust other options first. For just a few thousand nodes, there's no reason you shouldn't be able to get a result quickly on a single thread.
> 28 votes

# Answer
# Consider using a grid-optimized pathfinding algorithm

A\* is the canonical pathfinding algorithm. It's great for general purpose pathfinding on a graph.

It looks like your terrain is a 2D grid specifically. If that terrain is not deformed or modified during play, then there are more specialized algorithms available.

Either of the following algorithms (if implemented well) will likely result in very significant speed-improvements over well-implemented A\*, however, they both require some pre-processing of the map, are not terribly well documented online. I recommend following DMGregory's answer *first* and then only pursuing these algorithmic improvements if you still need the speed (and have time to spare).

## Jump Point Search

Jump Point Search is an algorithm that reduces the grid to a set of key vertices, such as the narrowest possible corners when making turns. A short paper that describes the algorithm can be found here.

### Pruning

During pathfinding, pre-emptively prune (meaning: do not add to the open list) potential options based on the direction from which the current node was entered. When leaving a node *x* that was reached from node *p*, do not consider moving to any node *n* if

* A path exists from *p* to *n* that is shorter than *{p, x, n}* \- for example, a path that moves northeast then south to arrive at a square immediately east of where it started would not be considered, because a path that moves east directly would be shorter.
* A path exists from *p* to *n* that is of the same length as *{p, x, n}*, but makes diagonal moves earlier. For example, moving east and then northeast would not be considered, because a path that moves northeast and then east would be preferred.

You can detect these short paths necessary for pruning without doing any actual pathfinding. For example, If you have just made a non-diagonal move, you can moves in any other direction unless you've just passed a wall (because otherwise, a path would exist with earlier diagonals). From a diagonal move, you only need to consider moves in the same direction, or its two adjacent non-diagonal moves, again, unless you pass a wall.

If you pass a wall - meaning that *p* was adjacent to a wall in some direction, but *x* has empty space in that direction, and that direction is at most 90-degrees off from the direction of travel - you need to consider movement in that direction (and any intervening diagonals) as well.

The JPS algorithm authors refer to nodes reached by continuing movement in the same direction as "natural successors" and nodes that must also be considered due to passing a wall as "forced successors."

### Jumping

When pathfinding, you can move multiple steps in the same direction, so long as:

* You do not jump over any nodes that have forced successors
* When moving diagonally, you do not jump over any nodes from which you could jump non-diagonally to a node with forced neighbors.

### Precomputation and Caching

The successors of a node from a given direction do not change unless the map itself does. It is therefore possible to trade memory for speed by precomputing the jump points for every node in the graph in every driection. This can either be done before publishing and saved as part of the map data, computed during load-time on the client, or lazy-evaluated (but then stored) when pathfinding is actually performed.

## Goal Bounding

Goal Bounding is another grid-based optimization on top of A\* (compatible with JPS). For goal bounding, preprocess the map by the following algorithm. A more detailed explanation of this algorithm (as applied to nav-meshes) can be found here.

* During load-time, run Dijkstra's Algorithm on the map to find the shortest path from each node to every other node.
* If your map is small enough that have enough memory to save the output of Dijkstra's Algorithm, use that instead. Goal Bounding is an optimization to save space.
* For each node, for each neighbor, calculate the bounding box that contains all of the shortest paths which move in that direction. (This should be a fixed size of 4 rectangles per node, since you only allow movements in the cardinal directions)
* During runtime, when doing pathfinding, discard all candidate paths that attempt to move in a direction where the goal is outside the bounds for that direction.
> 4 votes

# Answer
Your grid (56x28) has 1568 spaces in it.

For each location, all you need is the direction to go in. That is 2 bits.

1568^2 * 2 bits is only 615k.

So: use a lookup table. At `Table[Index(x,y)][Index(a,b)]` it tells you which direction (NESW) is the shortest distance from `x,y` to `a,b`.

Building a complete graph of shortest paths in a 56x28 world isn't hard. And now lookup is instant. The memory requirements are modest.

You can get fancier if you really want to. But in this case, don't bother.
> 3 votes

---
Tags: unity, 2d, performance, path-finding, optimization
---


title: Designing a stats system

text:
# Question
Title: Designing a stats system
**NOTE:** *I am currently not using any frameworks or other game dev tools like Unity - this is purely written using c# 6.0 in Visual Studio 2015. I would be interested to learn about any frameworks or tools that have an implementation of this system for learning purposes, but ultimately I wish to design my own system.*

For the past several weeks, I've been working on building (the engine for) an RPG game. The work done has purely been based around things like what happens when a player attacks an enemy, etc. More recently, I've been trying to figure out how to implement the stats system.

If you're familiar with EverQuest, this is the sort of system I'm going for, namely:

* Players and enemies share the same common stats.
* Stats are capped (based on level or otherwise). Example: crit chance cannot exceed 100, `Stamina` cannot exceed 250 at level 40.
* Stats are calculated into the basic `Damage`, `Defense` and `Health` stats. Example: `Stamina` increases the `Health` stat by `X` per point.
* Stats are affected by things like potions, friendly spells, debuffs, item effects, etc.
* There is a maximum number of effects that can be used at one time (ex. 10)
* Item effects *may* increase a stat past the cap

There are other details that I'd ultimately like to consider, but this is the primary goal: *A player (or enemy) has a set of statistics that, at any given time, can be changed by a (maximum) number of statistic effects.*

Consider the following example:

A player with 100 `Health` and 10 `Strength` has a calculated `Damage` stat of 18 (arbitrary). He then receives a buff, increasing his `Strength` to 14. If he then drinks a potion that gives `Strength + 2`, his strength should be recalculated to 16 (base strength + buff + potion).

The system I am trying to design should be able to calculate the `Damage` stat to its new value, **regardless of the source of the stat change**. Whether it's a potion, spell or otherwise that changes the stat, the stats should ultimately be represented as one single calculated value.

Similarly, when the timer on an item effect expires, the buff should be removed and its effects should fall off.

**What I have so far**

I have created a base class, holding the individual statistics, and using `OnPropertyChanged()` to recalculate base stats when a secondary stat changes:

```
public int Defense //base stat, no change event fired
{
    get { return this._defense; }
    set { this._defense = value; }
}

public int Stamina //affects health
{
    get { return this._stamina; }
    set { this._stamina = value; OnPropertyChanged(nameof(Stamina)); }
}

```

This works for the time being, but I've already run into snags trying to add item effects into the equation. At this point, I'm simply stuck on the implementation and am not sure about the "proper" way to proceed further.

**Edit:**

Based on comments to the question, I'm narrowing the scope to be less broad. I would like assistance designing the `Statistics` class to facilitate the requirements given above.

```
public void ApplyStatEffects()
{
    Statistics playerStats = new Statistics
    {
        Health = 10,
        Damage = 3,
        CritChance = 20
    };

    Statistics buffStats = new Statistics
    {
        Health = 5
        //only declare properties that are changing
    };

    //apply a blanket update to the base stats based on current effects
    //playerStats += buffStats;
}

```

Ultimately, what I would like to do is take one `Statistics` object (`base`) and apply the effects of other `Statistics` objects to `base`. It should also support things like buff timers and stat caps, BUT:

I'm not sure how to design the properties to make this easier. A few thoughts:

* I could use a `KeyValuePair<>` with an `enum` to represent the stats
* Make every `Statistic` it's own object with properties `string name;` and `T (object?) value`.
* Roll the current properties into a `List` or `Array`.

However, some properties are `int`, where others are `double`. Additionally, some may be capped in a range `0-100` while others might be capped at `x * level`.

*How should I implement my `Statistics` class to make it easier to apply one or many stat changes like `Health + 10, Damage - 2` from multiple sources?*

# Answer
As with most programming problems there is more than one way to skin a cat, but here is a small example program that will roughly implement the type of behaviour you are after, it should be enough for you to work with in your own project:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace StatTesting
{
    class Program
    {
        public static Random ran = new Random();

        static void Main(string[] args)
        {
            var player = new GameEntity();

            Console.WriteLine("Defense: {0}", player.Defense);
            Console.WriteLine("Damage: {0}", player.Damage);
            Console.WriteLine("Health: {0}", player.Health);

            var buffDescriptions = new string[11] { "Striking", "Thundering", "Hammering", "Piercing", "Slashing", "Vampiric", "Icing", "Flaming", "Shocking", "Noxious", "Acidic" };
            for (var i = 0; i < 11; i++)
            {
                var buffDesc = buffDescriptions[i];
                var buffValue = ran.Next(1, 51);
                var duration =  ran.Next(5, 20);

                var buff = new Buff(buffValue, buffDesc, duration);

                if(player.AddDamageBuff(buff))
                    Console.WriteLine("Buff '{0}' Applied, damage Value modified by {1}, damage is now {2}, duration: {3}", buffDesc, buffValue, player.Damage, duration);
            }

            Console.WriteLine("Finished adding damage buffs.");

            // simulate ticks with Thread.Sleep(1000) in a loop
            // in a game this would be replaced with an .Update() function within the game loop
            var timeAlive = 0;
            while (timeAlive < 25)
            {
                Console.WriteLine("tick...{0}", timeAlive);

                // remove all expired buffs:
                player.DamageBuffs.RemoveAll(item => item.DurationInSeconds <= timeAlive);

                // display remaining buffs:
                Console.WriteLine("Damage Score: {0}", player.Damage);

                // increase time alive:
                timeAlive++;
                Thread.Sleep(1000);
            }

            Console.WriteLine("All buffs expired...");
            var x = Console.ReadLine();

        }
    }

    public class GameEntity
    {
        // value based on level or some other metric:
        private int MAX_UNBUFFED_STAT = 40;

        private int damage;
        private int defense;
        private int health;

        public RestrictedList<Buff> DamageBuffs;
        public RestrictedList<Buff> DefenseBuffs;
        public RestrictedList<Buff> HealthBuffs;

        public int Damage
        {
            get
            {
                // get the base damage amount:
                var damageScore = damage < MAX_UNBUFFED_STAT ? damage : MAX_UNBUFFED_STAT;

                //apply any status effects:
                damageScore += DamageBuffs.Select(t => t.StatModifier).Sum();

                // return total damage value:
                return damageScore;
            }
            set { damage = value; }
        }

        public int Defense
        {
            get
            {
                // get the base defense amount:
                var defenseScore = defense < MAX_UNBUFFED_STAT ? defense : MAX_UNBUFFED_STAT;

                //apply any status effects:
                defenseScore += DefenseBuffs.Select(b => b.StatModifier).Sum();

                // return total damage value:
                return defenseScore;
            }
            set { defense = value; }
        }

        public int Health
        {
            get
            {
                // get the base health amount:
                var healthScore = health < MAX_UNBUFFED_STAT ? health : MAX_UNBUFFED_STAT;

                //apply any status effects:
                healthScore += HealthBuffs.Select(b => b.StatModifier).Sum();

                // return total damage value:
                return healthScore;
            }
            set { health = value; }
        }

        public GameEntity()
        {
            // initialise list of damage buffs:
            DamageBuffs = new RestrictedList<Buff>();
            DefenseBuffs = new RestrictedList<Buff>();
            HealthBuffs = new RestrictedList<Buff>();

            // set base stats:
            this.damage = 20;
            this.defense = 35;
            this.health = 50;
        }

        public bool AddDamageBuff(Buff buff)
        {
            try
            {
                // try and add this buff to player:
                this.DamageBuffs.Add(buff);

                return true;
            }
            catch (OverCapacityException oex)
            {
                Console.WriteLine("Buffs at maximum capacity!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Well, I wasn't expecting that... {0}", ex.Message);
            }

            return false;
        }
    }

    public class RestrictedList<T> : List<T>
    {
        private int maxCapacity = -1;

        public RestrictedList(int capacity = 10)
        {
            this.maxCapacity = capacity;
        }

        public new void Add(T value)
        {
            if (this.Count < maxCapacity)
            {
                base.Add(value);
                return;
            }

            throw new OverCapacityException("The RestrictedList is at maximum capacity.");
        }
    }

    public class OverCapacityException : Exception
    {
        public OverCapacityException(string message)
            : base(message) { }
    }

    public struct Buff
    {
        public Buff(int statModifier, string description, int durationInSeconds = 10)
        {
            StatModifier = statModifier;
            Description = description;
            DurationInSeconds = durationInSeconds;
        }

        public int StatModifier;
        public string Description;
        public int Id;
        public int DurationInSeconds;
    }
}

```
> 2 votes

# Answer
I think the use of a property change event is wise. Situating all the stats inside one class though seems tricky to work with. I made a lot of progress on this problem with a relatively simple pair of interfaces.

```
public interface IModifiableValue<T> {
  T baseValue { get; set; }
  T value { get; }
  /** The list implementation sets up property change events automatically. */
  ICollection<IModifier<T>> modifiers { get; }
  event PropertyChangedEventHandler PropertyChanged;
}

public interface IModifier<T> {
  bool enabled { get; set; }
  T Modify(T given);
  event PropertyChangedEventHandler PropertyChanged;
}

```

One can limit the number of modifiers as you've done by providing a particular implementation of `ICollection<T>`, or perhaps it'd be better to only have the `IModifiableValue<T>` implementation apply the first 10 enabled modifiers.

One can also use stats as modifiers for other stats, and all the changes are properly fired.

```
var maxHealth = new ModifiableValue<float> { baseValue = 100f };
var health = ModifiableValue.FromValue(maxHealth);
var damage = Modifier.Subtract(0f);

health.PropertyChanged += (_, _) => Console.WriteLine($"Health is {health.value}/{maxHealth.value}.");
health.modifiers.Add(damage);
// Prints: Health is 100/100.
damage.value = 10f;
// Prints: Health is 90/100.
maxHealth.modifier.Add(Modifier.Plus(20f, "+20 level gain"));
// Prints: Health is 110/120.

```

The actual library is SeawispHunter.RolePlay.Attributes. It is MIT licensed.
> 0 votes

---
Tags: c#
---


# Question
Title: OOP architecture for Hero with many attributes
I'm about to start a simple browser text RPG, with characters that can (passively) fight other people. This involves a list of about 10 skills like strength, dexterity and so on, with additional proficiencies for different weapons.

Is there a better way to design this character class then just having those skills as class attribute? It seems easy, but I'm reluctant because it's clumsiness.

```
class Char(self):
    int strength
    int dexterity
    int agility
    ...
    int weaponless
    int dagger
    ...

```

# Answer
As long as you keep your system relatively simple, this should work. But when you add things like temporary skill modifiers, you will soon see a lot of duplicate code. You will also run into problems with different weapons using different proficiencies. Because each skill is a different variable, you will have to write different code for each skill-type which basically does the same (or use some ugly reflection hacks - under the condition your programming language supports them).

For that reason I would recommend you to store both skills and proficiencies in an associative data-structure which maps skill-constants to values. How to do that elegantly differs from programming language to programming language. When your language supports it, the constants should be in an `enum`.

To give you an example how this would work in practice, your code for calculating attack damage would then look something like this:

```
int damage = attacker.getSkill(STRENGTH) +
             attacker.getProficiency(weapon.getProficiencyRequired()) -
             defender.getSkill(TOUGHNESS);

```
> 17 votes

# Answer
Why not use associated arrays?, this gives the benefit of being easily extended (using PHP for example)

```
$Stats["Strength"] = "8";
$Stats["Dexterity"] = "8";

```

for things such as weapons, you would probably want to create some base classes

Weapon -\> MeleeWeapon, RangedWeapon

and then create your weapons from there.

The end result I would aim for is a class looking like this

```
class Character
{
    public $Stats;
    public $RightHand;
    public $LeftHand;
    public $Armor;
    public $Name;
    public $MaxHealth;
    public $CurrentHealth;

    public function __construct()
    {
        //Basic
        $this->Name = "Fred";
        $this->MaxHealth = "10";
        $this->CurrentHealth = "10";

        //Stats
        $this->Stats["Strength"] = 8;
        $this->Stats["Dexterity"] = 8;
        $this->Stats["Intellect"] = 8;
        $this->Stats["Constitution"] = 8;

        //Items
        $this->RightHand = NULL;
        $this->LeftHand  = NULL;
        $this->Armor = NULL;

    }
}

```

You could store everything in an array if you really wanted too.
> 4 votes

# Answer
I'll try to answer this question the most OOP way (or at least what I think it would be). It may be completely overkill, depending on the evolutions you see about the stats.

You could imagine a SkillSet (or *Stats*) class (I'm using C-like syntax for this answer):

```
class SkillSet {

    // Consider better data encapsulation
    int strength;
    int dexterity;
    int agility;

    public static SkillSet add(SkillSet stats) {
        strength += stats.strength;
        dexterity += stats.dexterity;
        agility += stats.agility;
    }

    public static SkillSet apply(SkillModifier modifier) {
        strength *= modifier.getStrengthModifier();
        dexterity *= modifier.getDexterityModifier();
        agility *= modifier.getAgilityModifier();

    }

}

```

Then the hero would have an intrinsicStats field of the SkillSet type. A weapon could have a modifier skillSet as well.

```
public abstract class Hero implements SkillSet {

    SkillSet intrinsicStats;
    Weapon weapon;

    public SkillSet getFinalStats() {
        SkillSet finalStats;
        finalStats = intrinsicStats;
        finalStats.add(weapon.getStats());
        foreach(SkillModifier modifier : getEquipmentModifiers()) {
            finalStats.apply(modifier);
        }
        return finalStats;
    }

    protected abstract List<SkillModifier> getEquipmentModifiers();

}

```

This is of course an example to give you idea. You may also consider using the Decorator design pattern, so that the modifiers on the stats work as "filters" that are applied one after the other…
> 3 votes

# Answer
The most OOP way of doing things would probably be doing something with inheritance. Your base class (or super class depending on language) would be person, then maybe villains and heroes inherit from the base class. Then your strength based heroes and flight based heroes would branch off as their mode of transport is different, for instance. This has the added bonus that your computer players can have the same base class as the human players and it will hopefully simplify your life.

The other thing regarding attributes, and this is less OOP specific would be to represent your character attributes as a list so you don't have to have them all defined explicitly in your code. So maybe you would have a list for weapons and a list for physical attributes. Make some sort of base class for these attributes so they can interact, so each one is defined in terms of damage, energy cost, etc. so when two individuals come together it is relatively clear how the interaction will take place. You would iterate through the list of each character's list of attributes and calculate the damage one does to the other with a degree of probability in each interaction.

Using a list will help you to avoid rewriting a lot of code as in order to add a character with an attribute you hadn't thought of yet, you just have to make sure it has an interaction that works with your existing system.
> 3 votes

# Answer
I'd recommend a stat type manager, populated from a datafile (e.g. I use XML) and Stat objects, with a type and a value stored in the character insatnce as a hashtable, with the stat type unique ID as the key.

Edit: Psudo code

```
Class StatType
{
    int ID;
    string Name;

    public StatType(int _id, string _name)
    {
        ID = _id;
        Name = _name;
    }
}

Class StatTypeManager
{
    private static Hashtable statTypes;

    public static void Init()
    {
        statTypes = new Hashtable();

        StatType type;

        type = new StatType(0, "Strength");
        statTypes.add(type.ID, type);

        type = new StatType(1, "Dexterity");
        statTypes.add(type.ID, type);

        //etc

        //Recommended: Load your stat types from an external resource file, e.g. xml
    }

    public static StatType getType(int _id)
    {
        return (StatType)statTypes[_id];
    }
}

class Stat
{
    StatType Type;
    int Value;

    public Stat(StatType _type, int _value)
    {
        Type = _type;
        Value = _value;
    }
}

Class Char
{
    Hashtable Stats;

    public Char(Stats _stats)
    {
        Stats = _stats;
    }

    public int GetStatValue(int _id)
    {
        return ((Stat)Stats[_id]).Value;
    }
}

```
> 3 votes

# Answer
Ι'll try to give you an example on how you can design your arsenal and your armory.

Our goal is to decouple entities, therefore weapon should be an interface.

```
interface Weapon {
    public int getDamage();
}

```

Presume that each player can only possess one weapon, we can use the `Strategy pattern` in order to changes weapons easily.

```
class Knife implements Weapon {
    private int damage = 10;
    @Override
    public int getDamage() {
        return this.damage;
    }
}

class Sword implements Weapon {
    private int damage = 40;
    @Override
    public int getDamage() {
        return this.damage;
    }
}

```

Another useful pattern would be the Null Object Pattern in case the player is unarmed.

```
class Weaponless implements Weapon {
    private int damage = 0;
    @Override
    public int getDamage() {
        return this.damage;
    }
}

```

As for the armory ,we can wear multiple defense equipment.

```
// Defence classes,interfaces

interface Armor {
    public int defend();
}

class Defenseless implements Armor {

    @Override
    public int defend() {
        return 0;
    }
}

abstract class Armory implements Armor {

    private Armor armory;
    protected int defence;

    public Armory() {
        this(new Defenseless());
    }

    public Armory(Armor force) {
        this.armory = force;
    }

    @Override
    public int defend() {
        return this.armory.defend() + this.defence;
    }

}

// Defence implementations

class Helmet extends Armory {
    {
        this.defence = 30;
    }
}

class Gloves extends Armory {
    {
        this.defence = 10;
    }
}

class Boots extends Armory {
    {
        this.defence = 10;
    }
}

```

For decoupling, I created an interface for the defender.

```
interface Defender {
    int getDefended();
}

```

And the `Player` class.

```
class Player implements Defender {

    private String title;

    private int health = 100;
    private Weapon weapon = new Weaponless();
    private List<Armor> armory = new ArrayList<Armor>(){{ new Defenseless(); }};

    public Player(String name) {
        this.title = name;
    }

    public Player() {
        this("John Doe");
    }

    public String getName() {
        return this.title;
    }

    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }

    public void attack(Player enemy) {

        System.out.println(this.getName() + " attacked " + enemy.getName());

        int attack = enemy.getDefended() + enemy.getHealth()- this.weapon.getDamage();

        int health = Math.min(enemy.getHealth(),attack);

        System.out.println("After attack " + enemy.getName() + " health is " + health);

        enemy.setHealth(health);
    }

    public int getHealth() {
        return health;
    }

    private void setHealth(int health) {
        /* Check for die */
        this.health = health;
    }

    public void addArmory(Armor armor) {
        this.armory.add(armor);
    }

    @Override
    public int getDefended() {
        int defence = this.armory.stream().mapToInt(armor -> armor.defend()).sum();
        System.out.println(this.getName() + " defended , armory points are " + defence);
        return defence;
    }

}

```

Let's add some gameplay.

```
public class Game {
    public static void main(String[] args) {
        Player yannis = new Player("yannis");
        Player sven = new Player("sven");

        yannis.setWeapon(new Knife());
        sven.setWeapon(new Sword());

        sven.addArmory(new Helmet());
        sven.addArmory(new Boots());

        yannis.attack(sven);
        sven.attack(yannis);
    }
}

```

Voila!
> 0 votes

# Answer
I think it depends on how many effects and calculations your stats are bound to. It feels like many stats-based games produce a great many effects. You get "+10% damage" from this potion, or something like that. If you want to make a game like that, I'd encourage you to consider one of the stat composite designs or libraries. Then you could write something like this:

```
var health = new ModifiableValue<float> { baseValue = 100f };
health.modifiers.Add(Modifier.Times(1.10f));
Console.WriteLine($"Health is {health.value}."); // Prints: Health is 110.
health.modifiers.Add(Modifier.Plus(5f, "+5 health"));
Console.WriteLine($"Health is {health.value}."); // Prints: Health is 115.

```
> 0 votes

---
Tags: architecture, oop
---


# Question
Title: Is it possible to have shared data between shaders in GLSL that is loaded once?
For my game engine, I would like to be able to load all of the matrices (i.e. mvp, model, etc.) once per frame to save a bit of time, and have a set of uniforms that any shader can access by using layout or binding or something similar. I was wondering if this would be possible or would I have to load them each for every shader?

# Answer
Yes, you can put your uniforms in a Uniform Buffer Object. These uniforms can be shared between programs. https://www.khronos.org/opengl/wiki/Uniform\_Buffer\_Object
> 0 votes

---
Tags: opengl, c++, glsl
---


# Question
Title: How to store and organize my data in a JRPG style game?
I am trying to make a JRPG style game using Unity. See this image below to get a sense of the "feel" of the type of game I am making:

http://www.juicygamereviews.com/uploads/3/0/5/0/30501048/9185639\_orig.jpg

Currently I'm struggling to find a good way to organize the data in my game.

Referring to the image above, see how each party member has stats, as shown in the UI? I'm sure the monster also has the same kinds of stats, just hidden away. Hence, I want to make a struct called Stats, that both PartyMembers and Monsters contain a reference to.

To summarize what I'm saying so far:

Right now I'm pretty sure I want two classes - one called PartyMember and one called Monster, both of them deriving from a common class - I'll call it TurnTaker - that takes turns during battle. In the TurnTaker class I want a reference to a struct called Stats, which contains HP, MP, Attack, Defense, etc.

The problem is, for player data I want the Stat class to be \[Serializable\] because I want to save player progress in a binary format, yet for Monsters I wish to make the Stat class inherit from Scriptable Object (SO) for easy development and editing.

Is it possible to make Stats both serializable and derive from SO in Unity? (Note: a struct cannot derive from SO; only a class can. Should I change my stats from a struct to a class? Seems a bit of a waste, just for the inheritance functionality.)

Further, I'm thinking party members have data specific to themselves (equipment, total EXP, character class, etc), as do monsters(drop items, movement type, etc.)

Should I make these two "things," I'll call them PartyMemberSpecificData and MonsterSpecificData

* separate classes altogether
* separate interfaces that attach themselves to PartyMember, Monster, or Stat
* classes that derive from Stats

(I think I want PartyMember to contain a reference to PartyMemberSpecificData and Monster to contain a reference to MonsterSpecificData.)

Any help appreciated!

# Answer
> 2 votes
I'd second Bálint's comment above that inheritance is not necessarily the best pattern to use here. Especially in a component-based engine like Unity, you may find that favouring composition over inheritance gives you more flexibiity.

I might try something like this:

```
[System.Serializable]
public struct Stats {
   public int Attack;
   public int Defense;
   public int Magic;
   // etc.
}

// Plain old data structure - this just makes it easy to
// author shared stats objects in the Unity editor.
[CreateAssetMenu(fileName="Stats.Asset", menuName="Character/Stats")]
public BaseStats : ScriptableObject {
   public Stats stats;
}

// Attach this to your characters/monsters and
// reference their base stats object in the Inspector.
public RuntimeStats : MonoBehaviour {
    public BaseStats baseStats;
    public Stats current;

    void Awake() {
        current = baseStats.stats;
    }
}

```

Using this "has-a" relationship, you get:

* a single common `Stats` struct that's ready to serialize into a save file if needed
* a `BaseStats` object you can store as an asset in your project and share between multiple instances of a character archetype (eg. every goblin can reference the same base goblin stats)
* a mutable runtime instance of the stats that can be attached to a character instance, can be influenced by leveling / status effects, and is easy to reset to the shared base stats for the archetype when needed. Both party members and monsters can reference this component, they don't each need to implement their own version (unless they need unique stats, but even that can be accommodated with only small variations to the pattern above)

You can carry this "has-a" relationship through the rest of your design too:

* Rather than have a MonsterData class to handle drops, have a `DropPayload` component that both monsters and chests can share. Maybe you can also attach this component to a spell effect to make an item-summoning spell!
* Rather than a PartyMember class handling equipment, have an Equipment component. Then you can freely mix and match, having a monstrous party member who doesn't wear equipment, or town guard "monsters" you can fight, who do wear equipment.
* Rather than a PartyMember class handling experience and leveling, have an Experience component you can attach to party members. You can then clone the party member and take off the experience component if you need to fight a fixed-level version of a party member as an "evil twin / shadow version" monster at some point. ;)

Thinking about each feature as a self-contained component can give you a lot of freedom to create new gameplay scenarios just by mixing & matching code you already have, in ways that would be much more laborious if everything were bound in strict inheritance hierarchies.

# Answer
> 0 votes
You can serialize `ScriptableObject`s as json or binary.

```
using UnityEngine;

// Custom asset type that prefers binary serialization.
//
// Create a new asset file by going to "Asset/Create/Custom Data".
// If you open this new asset in a text editor, you can see how it
// is not affected by changing the project asset serialization mode.
//
[CreateAssetMenu]
[PreferBinarySerialization]
public class CustomData : ScriptableObject
{
    public float[] lotsOfFloatData = new[] { 1f, 2f, 3f };
    public byte[] lotsOfByteData = new byte[] { 4, 5, 6 };
}

```

---
Tags: unity, c#, data-structure
---


# Question
Title: How is the GLM '*' operator on quaternion and vec3 defined?
Using the definition of quaternion rotation given here:

So the equivalent code in GLM of the above formula would be like this:

```
glm::quat q;
glm::vec3 v;
glm::vec3 rotated_vector = q * v;

```

and the `rotated_vector` above is the result of applying the `Lq` transformation to vector `v`.

Am I right on this?

Here's the testing code I wrote(not exhaustive):

```
for (size_t number_of_conducted_testing = 0; number_of_conducted_testing < 10000; number_of_conducted_testing++)
{
    //axis to rotate around
    glm::vec3 axis = glm::sphericalRand(1.0);
    //vector to be rotated
    glm::vec3 v    = glm::sphericalRand(1.0);
    //quaternion
    glm::quat q;

    for (auto degree = 0.f; degree < 370.f; degree += 0.0001f)
    {
        q = glm::angleAxis(glm::radians(degree), axis);
        glm::vec3 q_vector = glm::vec3(q.x, q.y, q.z);

        const glm::vec3 rotated_vector   = q * v;
        const glm::vec3 rotated_vector_0 = ((q.w) * (q.w) - glm::length2(q_vector)) * v + 2 * (glm::dot(q_vector, v)) * q_vector + 2 * q.w * (glm::cross(q_vector, v));

        float difference = 0.0f;
        if (!test_similarity(rotated_vector, rotated_vector_0, difference))
        {
            throw std::runtime_error("two vectors are different!");
        }
    }
}

bool App::test_similarity(glm::vec3 a, glm::vec3 b,float& difference)
{
    const auto difference = glm::length((a - b));
    return difference < 1e-5f;
}

```

And it didn't throw any exception for the case `difference < 0.00001`.

# Answer
I finally found out the implementation of GLM '\*' operator in **Kavan, Ladislav, et al., "*Geometric skinning with approximate dual quaternion blending.*" ACM Transactions on Graphics (TOG) 27.4 (2008): 105**:

> **Lemma 4.** *Let \\$\textbf{q} = a + \textbf{r}\\$ be a unit regular quaternion with scalar part \\$a\\$ and vector part \\$\textbf{r}\\$. Rotation of a vector \\$(v\_0, v\_1, v\_2)\\$ represented by the regular quaternion \\$\textbf{v} = v\_0i + v\_1j + v\_2k\\$ can be computed as* $$\textbf{v}' = \textbf{v} + 2\textbf{r} \times (\textbf{r} \times \textbf{v} + a\textbf{v})\tag{15}$$ *where \\$\textbf{v}′\\$ is the vector \\$\textbf{v}\\$ rotated by \\$\textbf{q}\\$*.
>
> *Proof.* The proof consists of re-arranging the well-known expression \\$\textbf{v}′ = \textbf{qvq}^∗\\$. Using Equation (14), we can expand $$ \begin{align} \textbf{v}′ &= \textbf{qvq}^∗ = (a + \textbf{r})\textbf{v}(a − \textbf{r}) = (−\langle\textbf{r}, \textbf{v}\rangle + a\textbf{v} + \textbf{r} \times \textbf{v})(a − \textbf{r}) = \\ &= −a\langle\textbf{r}, \textbf{v}\rangle + a\langle\textbf{v}, \textbf{r}\rangle + \langle\textbf{r}, \textbf{v}\rangle\textbf{r} + a^2\textbf{v} + a(\textbf{r} \times \textbf{v}) − a(\textbf{v} \times \textbf{r}) − (\textbf{r} \times \textbf{v}) \times \textbf{r} = \\ &= \langle\textbf{r}, \textbf{v}\rangle\textbf{r} + a^2\textbf{v} + 2a(\textbf{r} \times \textbf{v}) + \textbf{r} \times (\textbf{r} \times \textbf{v}) \end{align} $$ Recall Lagrange’s formula $$ \textbf{r} \times (\textbf{r} \times \textbf{v}) = \textbf{r}\langle\textbf{r}, \textbf{v}\rangle − \textbf{v}\langle\textbf{r}, \textbf{r}\rangle $$ which, added to the previous equation, results in $$ \begin{align} \textbf{v}′ &= \langle\textbf{r}, \textbf{v}\rangle\textbf{r} + a^2\textbf{v} + 2a(\textbf{r} \times \textbf{v}) + 2\textbf{r} \times (\textbf{r} \times \textbf{v}) − \textbf{r}\langle\textbf{r}, \textbf{v}\rangle + \textbf{v}\langle\textbf{r}, \textbf{r}\rangle = \\ &= \textbf{v}(a^2 + \Vert\textbf{r}\Vert^2 ) + 2a(\textbf{r} \times \textbf{v}) + 2\textbf{r} \times (\textbf{r} \times \textbf{v}) \end{align} $$ from which Equation (15) readily follows.

And it's exactly how GLM implements its '\*' operator on quaternion and vec3:

```
template<typename T, qualifier Q>
GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator*(qua<T, Q> const& q, vec<3, T, Q> const& v)
{
    vec<3, T, Q> const QuatVector(q.x, q.y, q.z);
    vec<3, T, Q> const uv(glm::cross(QuatVector, v));
    vec<3, T, Q> const uuv(glm::cross(QuatVector, uv));

    return v + ((uv * q.w) + uuv) * static_cast<T>(2);
}

```
> 1 votes

---
Tags: opengl, quaternion, glm
---


# Question
Title: Does game design (numerical value planning such as attack/defense/ rates of critical hit) need a strong mathematical background?
I will go to college very soon and I want to choose math major. I want to know if being graduate with a strong mathematical background will help me success in game design.

For example if I want to be a numerical planner to decide the value of attack/defense/critical hits, does it need a strong mathematical background, the ability to use a really complicated mathematical formula?

# Answer
> 5 votes
# It depends.

There's more than one way to be a game designer. So the best answer to your question is tautological: if you want to be *the kind of designer* who solves problems with math, then knowing some math is helpful.

**I'm a fairly math-y game designer myself**. I'm in the Analyst category, using the taxonomy of designers Richard Carrillo presents in the link above. When I encounter a design question, my first impulse is "how can I model that with an equation or spreadsheet, to understand the parameter space and make numerical predictions?" Ian Schreiber might be another good example of this kind of designer.

This approach has led to me doing a lot of economy and progression balancing work, because that's an area of game design where those math and spreadsheet tactics are especially fruitful. I'll also use my knowledge of geometry and math functions to help solve 3D problems, like making objects move through space the way I want when designing character controllers or AI behaviours, or sculpting procedurally generated content or shader visuals. (Though those last few activities are less commonly the responsibility of a game designer, it can still help when collaborating on a small team, or when making solo projects)

But even for all that, I don't use *that much* math, compared to a full major. Scan through my answers here and you probably won't find much that involves more than first-year calculus and linear algebra, stats and probability formulas you can pull off of Wikipedia, or the occasional differential equation that I just ask Wolfram Alpha to solve for me. This is all stuff you could learn on your own, without a full degree in math. Knowing *that* there's a math-y way to solve something, and having a hunch for the right keywords to search for it, is enough, even if you don't have the full theory memorized and at the tip of your tongue at all times.

Meanwhile, **many game designers do their work without complicated math formulas**. The designer I worked with who laid the foundations of the economy and progression systems in Splinter Cell Blacklist was definitely not a math-y person, and went into games straight out of high school, and continues to do excellent game design work to this day with nary a formula in sight. I'd say less than a fifth of the game designers I've worked with so far lean heavily on math in their process. Because there are lots of other ways to do good game design:

* Develop experience: by playing and making lots of games, you'll develop a mental repository of designs that worked, and you can draw from that rich background to remix and combine solutions to novel problems.
* Use iteration and playtesting: guess and check your work by feel or by observing and experimenting with other players. This approach can help capture a lot of the complexities of the experience that a formula might simplify out, though it can of course be time consuming!
* Understand player psychology: knowledge of how human minds work, what different types of players seek, and empathy to see the player perspective can guide you in making decisions that are right by them.
* Listen to instinct: with enough experience, you develop a "gut feel" for what choices are likely to work, and that itself is a skill you can train.
* Leverage experts: when you encounter a problem that needs a skill like math that's outside your expertise, find someone who can help and work with them to find a solution. That could be working within your team, or finding and engaging in online resources, as you're doing by asking here. Good communication and search skills are a kind of skeleton key for knowledge - use them right and any expertise on the planet can be yours to wield!

There are also limitations to the mathematical approach. It can help you optimize your formulas and design parameters for a given goal, but it won't tell you what goal you should be seeking in the first place. This is a common problem we see with questions on this site: folks looking for a formula that gives the "right" numbers to make their game fun, but the formula isn't the hard part, it's figuring out what's "fun" - and unfortunately there's no mathematical expression for that. Questions involving human behaviour and perception are also notoriously difficult to formalize. We can use a spreadsheet model to show what the optimizing / min-maxing player would do, but not what players who haven't done the math / read the strategy guide would be drawn to, or how they'd feel about the experience at each step. We need other design skills there.

But, once you do identify the right goals via other means, math can be a useful accelerator in finding the right systems and parameters to meet those goals, and for making evidence-based arguments *that* they're the right choices, which can be useful if you need to win over stakeholders in a larger studio.

So, we can't tell you what to study. Just about anything you learn can be helpful to the design of some games. What kind of game creator you want to be and how you'll apply your knowledge, experience, and skills to craft your games is something you'll have to figure out for yourself.

---
Tags: mathematics, game-design, game-mechanics, career
---


# Question
Title: Why does lighting on the object changes when I import it as Unity Package from my old project to new one?
Here is the original lighting ( Unity 2021.1)

And Here is the same setup imported in a new project ( Unity 2021.1):

As you can see importing this package in new Unity project makes it a lot lighter and I am not sure why. There aren't any additional lights int the scene and setting are the same. I use standard rendering pipeline.

For the prefab it is just a model with 3 directional lights.

# Answer
> 0 votes
I figured it out; it was something I completely overlooked. The original scene was created with Default Behavior Mode set to 2D and my new scene is created with Default Behavior set to 3D, so that was causing a lighting difference and I wasn't aware of this.

I just removed the skybox material from the Lighting window -\> Enviroment.

---
Tags: unity, lighting
---


# Question
Title: Can less than 30 FPS feel good with 60 FPS input handling?
2D animation can go as low as 12 FPS and still feel good to watch, but the minimum FPS considered to be "playable" in games is 30 fps. I believe this to be a consequence of the user controlling the image in the game and only watching in the movie. But if you where to separate the input handling from the graphics rendering, so that inputs run at 60 FPS and graphics run at 12 FPS, would the game still be "unplayable", or could you get away with that?

# Answer
> 4 votes
## Yes.

But it depends on what you do with that input, the player, and the game design as a whole.

### How a game "feels" is all about feedback.

> I beleive this to be a consequence of the user controlling the image in the game and only watching in the movie.

The critical difference between a movie and a game is that the player gets to interact with the game. The player and the game are connected in a feedback loop. Which is not true for a movie.

1. The game presents frames to the player.
2. The player decides what to do based on that feedback.
3. The player provides inputs to the game.
4. The game decides what happens next and renders a new frame.

This loop runs as fast as the slowest step. So if the player is allowed to send inputs at 60 Hz and the game is only rendering at 30 FPS then your loop repeats at 30 Hz.

So what happens to that input on the un-rendered input "frames"? If you update the gamestate and just not render another frame then that's actually a completely valid thing to do. I believe that lots of games work this way!
*(I would appreciate if someone could comment a reference for a well known game that has the render loop separated from the input/gamestate loop.)*

However, if there is any kind of visual feedback created by an input then the next frame you render should show that feedback. For example, if you can block an attack and there should be a sprite shown for 1 frame. The player needs to know what happened on the unrendered "frame", otherwise you're completely breaking the feedback loop!

Every input the player makes comes with an expectation that the game will show that their input had an effect.

### What feels "playable" though?

> 2D animation can go as low as 12 fps and still feel good to watch, but the minimum fps considered to be "playable"in games is 30 fps.

I would start by challenging that statement. Was it an assumption? Who decides what is "playable"?

I believe that limit will be unique to every game and the user themselves factors into the limit.

When this loop runs really fast (like 60 FPS) then the game can become more immersive and also present more difficult timing challenges to the player. Games like first-person shooters benefit from this fast loop because fast moving targets require some quick aim adjustment from the user. If the feedback loop is too slow then you can't accomplish very good aim and the game doesn't feel good.

Meanwhile other games like turn-based strategy, card games, board games, all feel playable at very low framerates. These games do not expect the player to be continuously making inputs, so the player also doesn't expect continuous feedback from the game. The game design allows the framerate to get pretty low before the player would consider it "unplayable".

If you slow down the framerate too much, at some point there will be a noticeable delay on actions like clicking buttons. That can also frustrate a player. (Imagine 1 or 2 FPS)

### Low Framerate Animation + High Framerate Motion

You should also consider that the rate that an animation plays does not have to be the same thing as the framerate. You can design a sprite sheet with 10 frames to play in a loop at 10 FPS (making 1 second loop), but still render the whole screen at 60 FPS. As the player moves their character around it could play the 10 FPS animation but update their position at 60 FPS.

---
Tags: graphics, performance, input
---


# Question
Title: When detecting a keyboard key is released. What happened if the key is released at the end of the game loop?
When detecting a keyboard key is released. What happened if the key is released at the end of the game loop, how could the pollEvent function, which is at the top of the game loop, and it is a brand new call of the function every iteration of the game loop, detect that key released at the end of the game loop in the last frame?

```
while (window.isOpen())
{
    /*
    ****************************************
    Handle the player input
    ****************************************
    */
    Event event;
    while (window.pollEvent(event))
    {
      if (event.type == Event::KeyReleased && !paused)
      {
          // Some code here
      }
    }
    ...
    /*
    ****************************************
    Update the scene
    ****************************************
    *
    ...
    /*
    ****************************************
    Draw the scene
    ****************************************
    *
    // a finger released from a key here!!!
    // The next loop will reset all the entire event types, I think
}

```

# Answer
> 4 votes
The System events will be placed in SFML's event queue and be processed during the next loop. Imagine if the events were lost? What a bad game dev library that would make!

*Roughly*, the way a program works on Windows is like this:

1. System events are queued by the OS into a queue for the program
2. At some point the program tells the OS it's ready to receive the OS events queued for it; this is done through a set of special functions
3. The program reacts to each event in the way it sees fit
4. The program tells the OS that they're done with handling the queue
5. The OS does its thing and queues more System events for the the program (loop back to 1.)

When you start an SFML app, it does essentially the same thing. When it receives OS events, it queues them until you're ready to process them. Once you process them, and when the SFML event queue is empty, you update your game logic, you render and then you start again.

No System events are lost.

---
Tags: sfml, events, keyboard
---


title: Entity Framework and reactive

text:
# Question
Title: Entity Framework and reactive
In my games using entity framework (for example using https://github.com/libgdx/ashley ) help me to separate data from logic in different systems. But a problem I've found is how to handle events between systems using messages. A possible solution of this could be reactive programming ( like https://github.com/ReactiveX/RxJava ), so for example an observer can be notified of changes on a specific model and react on that.

I'm not sure if this breaks the data / logic separation, because it will be at system level, any thoughts on that ?

Not sure also how to approach the ui part using also events from rxjava

# Answer
I did not look in depth the framework you're proposing, so my answer is based on "using the observer pattern to help de-couple systems to make them independent, easier to manage, change, evolve".

This post is not a definitive answer, it's just a point of view.

Using the observer pattern, with messages, is *a* way to solve communication situations between systems. However, I'm not sure it is "easier to manage, change, evolve": you'll still need to determine what kind of messages are to be transmitted and received, you'll still need to setup the listening end. Although, strictly speaking, your system will be independent, a system is rarely evolving in its own silo, it's always part of the rest of your software.

From experience, using events to de-couple systems may make the software harder to read, with the execution flow more difficult to follow.

Depending on your events and messages passed around, it *could* make your program a bit faster.

Alternatively, you could define your contracts between your systems using Interfaces, which are implemented by the interested system, then injected into the other systems. Those systems then take for granted that the host system may or may not be there. Something like this (pseudocode):

```
interface IFrameTimeProvider
    double getFrameTime();

class SimulationSystem : IFrameTimeProvider
    double getFrameTime() { return frameTime_; }

class UiSystem
    construct( IFrameTimeProvider frameTimeProvider )
    {
        frameTimeProvider_ = frameTimeProvider;
    }

    void draw()
    {
        if ( frameTimeProvider_ )
            renderer.drawText( "frameTime = " + frameTimeProvider_.getFrameTime() );
    }

    IFrameTimeProvider frameTimeProvider_;

```

This also comes with its load of boilerplate handling.
> 1 votes

---
Tags: entity-system
---


# Question
Title: since unity upgrade, OnSceneLoaded not getting called on scene start
I upgraded my unity project to 2018.3.11f. Since that upgrade, the `OnSceneLoaded` event is not getting called, even though I am registering the event handler.

Here's the class:

```
public class SceneSwitcher : MonoBehaviour
{
    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        print("scene loaded: " + scene.name);
    }

    void Start()
    {
        print("SceneSwitcher.Start() called");
        print("adding event handler to SceneManager");
        SceneManager.sceneLoaded += OnSceneLoaded;
    }
}

```

here's the console output:

```
SceneSwitcher.Start() called
UnityEngine.MonoBehaviour:print(Object)
SceneSwitcher:Start() (at Assets/Scripts/SceneSwitcher.cs:45)
adding event handler to SceneManager
UnityEngine.MonoBehaviour:print(Object)
SceneSwitcher:Start() (at Assets/Scripts/SceneSwitcher.cs:46)

```

`scene loaded: 3` is never in the console output.

I see others have had this problem, with no answers.

This code worked before the upgrade. Now I am stuck. Not sure what I can do. Any help is appreciated.

Thnx

# Answer
> 3 votes
Please check your Project Settings (Edit/Project Settings) - under the Editor tab you will find the Enter Play Mode Settings option.

As long as this option is disabled, or both this and the Reload Scene option are enabled, the sceneLoaded event should be triggered as expected. If you enable Enter Play Mode Options but disable Reload Scene, the editor apparently does not fully "load" the scene which in turn prevents the sceneLoaded event from triggering.

(IIRC disabling this option is one of the recommended settings to speed up switching from editor to play mode but it seems to have unwanted side effects)

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


title: how to get camera width in unity

text:
# Question
Title: how to get camera width in unity
**Problem**

I have a spawn manager written in c# which spawns my game object, i use screen.width, to set the maximum screen with and -screen.width to set the minimum screen width for the spawning, but my game object spawns way off the screen.

I am using a portrait camera 2:3 instead of free aspect as my camera view, as i want my game to be in portrait mode

how do i make my game object spawn within the camera widths(max and min)?

**my code**

```
public class SpawnManager : MonoBehaviour {

    public int maxBalloons = 100;
    public GameObject balloon;
    public float horizontalMin = -Screen.width;
    public float horizontalMax = Screen.width;
    public float verticalMin = -5.0f;
    public float verticalMax = 1.0f;

    private Vector2 originPosition;

    void Start () {

        originPosition = transform.position;
        Spawn ();

    }

    void Spawn()
    {
        for (int i = 0; i < maxBalloons; i++)
        {
            Vector2 randomPosition = originPosition + new Vector2 (Random.Range(horizontalMin, horizontalMax), Random.Range (verticalMin, verticalMax));

            Instantiate(balloon, randomPosition, Quaternion.identity);
            originPosition = randomPosition;
        }
    }

}

```

# Answer
> 8 votes
`Screen.width` and `.height` give you the current sizes of your game's display/window *in pixels*.

For positioning objects in our world, we want to work in worldspace units.

When you're using an orthographic camera, `camera.orthographicSize` gives you the verical half-height of the camera in world units (the distance from the center of the view to the top).

Multiplying that by the camera's width:height aspect ratio, `camera.aspect`, gives us our half-width in worldspace units.

So you can create your `horizontalMin` & `Max` like so:

```
Camera camera = Camera.main;
float halfHeight = camera.orthographicSize;
float halfWidth = camera.aspect * halfHeight;

horizontalMin = -halfWidth;
horizontalMax =  halfWidth;

```

For completeness, here's how you'd do it with a perspective camera that gets wider the further back in depth you go. For this we'll need an input `depth` value representing how far from the camera we want to spawn our objects, along the camera's forward vector.

```
float halfFieldOfView = camera.fieldOfView * 0.5f * Mathf.Deg2Rad;
float halfHeightAtDepth = depth * Mathf.Tan(halfFieldOfView);
float halfWidthAtDepth = camera.aspect * halfHeightAtDepth;

 // And the rest is the same.

```

Or you can just compute your desired position in viewport space (from (0,0) in the bottom-left of the camera's view to (1,1) at the top-right) and convert it to a world space position with Camera.ViewportToWorldPoint(), passing your desired depth as the third coordinate. This will automatically handle both perspective and orthographic cameras.

# Answer
> 0 votes
You need to use `Vector3 randomPosition = Camera.main.ScreenToWorldPoint(originPosition + new Vector2 (Random.Range(horizontalMin, horizontalMax), Random.Range (verticalMin, verticalMax)));` or you can try `Camera.main.ViewportToWorldPoint` as well

# Answer
> 0 votes
To find the "screen width" at the point of any transform, simply use this

```
using UnityEngine;
using System.Collections;

public static class ExtensionsMeasures {

    public static float NominalScreenWidthAt(this Camera c, Transform t) {
        float yFromCamera = t.transform.position.z - c.transform.position.z;

        return
            c.ViewportToWorldPoint(new Vector3(1f, 1f, yFromCamera)).x
            - c.ViewportToWorldPoint(new Vector3(0f, 1f, yFromCamera)).x;
    }

    public static float NominalScreenHeightAt(this Camera c, Transform t) {
        float yFromCamera = t.transform.position.z - c.transform.position.z;

        return
            c.ViewportToWorldPoint(new Vector3(0f, 1f, yFromCamera)).y
            - c.ViewportToWorldPoint(new Vector3(0f, 0f, yFromCamera)).y;
    }

```

Note that, of course, any such extension must work with **any** camera projection ...

conventional, orthographic or some custom frustum shape.

An example of using the call,

```
    layers = new List<Transform>();
    foreach (Transform t in transform) {

        layers.Add(t);
        float widthOfLayer = t.GetComponent<Renderer>().bounds.size.x;
        float widthOfScreenThere = Camera.main.NominalScreenWidthAt(t);
        Debug.Log("w layer, screen " + widthOfLayer + " " + widthOfScreenThere);

```

(Footnote - generally, avoid using Unity's hokey "Camera.main"; of course, you'd have the specific camera in question in a variable somehow.)

In almost all scrolling-type games (whether 2D, 3D or anything else) when the game launches you have the difficult issue of what to do about different physical device aspect ratios. (Players on wider screens will "see enemies sooner" that players on narrower screens, so to speak.) Whatever strategy you adopt to solve this difficult issue, the first step is always getting the screen width/height (at the position of your enemies, background, or whatever the case may be) and then adopting your approach to the problem.

# Answer
> 0 votes
After looking around for some confirmation about something, under the hood, similar to this, I found my answer and though I could share it here (as this is one of the top result on google while looking this up).

While I can't tell if this was available over 4 years ago, at least in the recent version of Unity, you can get the "actual" pixel-width of any camera by the use of pixelHeight and pixelWidth as well as pixelRect. (A camera's rect value allows you to get the position of each corner of a camera in screen space.)

This works regardless of if you're using the Perspective or Orthographic camera view.

By using ScreenPointToRay, once you know the pixel width and height of the camera's viewport, you can get the 3D coordinates of all 4 corners of the camera viewport at any given distance you might need. (You only need 2 corners, but you can still use the 2 others for the sake of making it easier to remember/read.)

A good note about ScreenPointToRay is that it automatically takes into consideration if the camera is orthographic or not so you don't have to scratch your head regarding angles and field of view or whatever.

Then it's only a matter of setting the rules of either spawning the stuff within the 4 corners (between the X and Y of both the bottom-left and top-right corners for example). If someone else want to spawn stuff just outside of the viewport, you can set up the 4 directional zone (just outside of the viewport) by first selecting one of the 4 direction (at each spawn) and then, on the selected side, determine the position slightly outside of the camera's viewport's position.

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


# Question
Title: How to know if a rigidbody2D is moving away or towards another position?
I want to know if the rb2D is moving away or towards the other position. Is there a formula to determine this?

# Answer
> 1 votes
This is a straightforward use of a dot product:

```
// Returns 1 if the body is moving away (distance increasing),
// -1 if moving toward (distance increasing),
// and 0 if moving perpendicular (no change in distance)
float MovementDirection(Rigidbody2D body, Vector2 position) {
    // Construct a vector that points from the reference position to the body.
    var away = body.position - position;

    // Compare this direction against the body's velocity.
    float dot = Vector2.Dot(body.velocity, away);

    if (Mathf.Approximately(dot, 0)) return 0;
    return Mathf.Sign(dot);
}

```

For more information about how the dot product works, see How do I interpret the dot product of non-normalized vectors?

---
Tags: unity, physics
---


# Question
Title: Behavior tree: invert grandparent's return value
I'm trying to figure out how to return one result to the immediate parent, while returning a different one to the grandparent. The idea is: given a "turnToFaceTarget" tree, skip the rotation if already facing the right direction, and continue doing whatever's next. This means the condition node should return Failure to its parent (turnIfNeeded), but the parent should return Success to *its* parent (walkToPosition). How can we accomplish this?

I thought of using an `invert` decorator, but I'm not sure how to implement it, since no nodes don't have a parent reference. I can think of ways to hack it, but... how is this "supposed" to be done?

```
walkToPosition:
  sequence("walkToPosition") {
    turnToFaceTarget // this should return Success when done turning
    action("startWalking") {
    }
  }

// returns Success if/when facing the right way, and Running while it's turning
turnToFaceTarget:
  selection("turnIfNeeded") {
    condition("shouldTurn") {
      // We want to optionally skip rotation (return Failure), but return an overall Success
      return currentAngle == targetAngle ? Failure : Success
    }
    sequence("turn") {
      action("setRotationVelocity") {
      }
      action("rotate") {
          // apply rotation
          return targetAngle == targetAngle ? Success : Running
      }
    }
  }

```

# Answer
First of all, I think you don't need this. If you set the rotation velocity to zero, and then the action verifies that the angle matches, it should be effectively no rotation and it sucedes.

I believe you should make your actions more complex. For example, you can set the target angle, and then set the rotation velocity in such way it does not overshoot (knowing the delta time). In fact, I would probably make "turn" an action instead of two actions in a sequence. *I think you are being too granular.*

---

Yet, for the sake of argument let us say that rotation is expensive, and we want to optimize it away, and the tool we have is behavior trees.

Well… This is what I imagine:

```
selection("turnIfNeeded") {
    condition("shouldNotTurn") {
      return currentAngle == targetAngle ? Success : Failure
    }
    sequence("turn") {
      action("setRotationVelocity") {
      }
      action("rotate") {
          return targetAngle == targetAngle ? Success : Running
      }
    }

```

*I'm guessing condition just executes the condition, but action goes and does something else elsewhere.*

Notice I changed "shouldTurn" to "shouldNotTurn" with swapped `Success` and `Failure`.

So when the angle is at its target, "shouldNotTurn" succeeds, and so the selector succeeds (and it is done turning). If the angle is not at its target, "shouldNotTurn" fails, and so the selector goes to the next item which is the "turn" sequence (which only sucedes when it is done turning).

Isn't that what you want? You want to invert he condition, then invert the condition.

---

About how to do an invert. What I do - instead of using decorators - is have an negated sequence and a negated selector.

There are two things a node can be looking for `Success` or `Failure`, and there are two things a node can return when it is done `Success` or `Failure`. So that is two by two for a total of four cases.

The negated sequence and negated selector complete the set:

* Selector:

Is looking for a `Success`. Returns `Success` when it finds it, `Failure` otherwise.
* Negated selector:

Is looking for a `Success`. Returns `Failure` when it finds it, `Success` otherwise.
* Sequence:

Is looking for a `Failure`. Returns `Failure` when it finds it, `Success` otherwise.
* Negated sequence:

Is looking for a `Failure`. Returns `Success` when it finds it, `Failure` otherwise.

If you need to make an invert, then use either of the negated versions with only one child. And no parent reference is involved.
> 0 votes

---
Tags: behavior-tree
---


# Question
Title: Is it useless to check whether a window is requested to be closed in full-screen mode?
Is it still necessary to check if the window is requested to be closed when I prepare a 1920x1080 window, in full-screen mode? How could the user close the window in full-screen mode, when you could not click the X button of the window? I take this code from a book.

```
int main()
{
    // Create a video mode object
    VideoMode vm(1920, 1080);
    // Create and open a window for the game
    RenderWindow window(vm, "Pong", Style::Fullscreen);
    /*
    Some code here
    *******************************
    *******************************
    *******************************
    */
    while (window.isOpen())
    {
        /*
        Handle the player input
        *******************************
        *******************************
        *******************************
        */
        Event event;
        while (window.pollEvent(event))
        {
           if (event.type == Event::Closed)
           {
               // Quit the game when the window is closed
               window.close();
           }
        }
        /*
        Update the bat, the ball and the HUD
        ****************************
        ****************************
        ****************************
        */
        /*
        Draw the bat, the ball and the HUD
        ****************************
        ****************************
        ****************************
        */
    }
}

```

# Answer
Check sfml-window-events:

> The sf::Event::Closed event is triggered when the user wants to close the window, through any of the possible methods the window manager provides ("close" button, keyboard shortcut, etc.). This event only represents a close request, the window is not yet closed when the event is received.

Clicking the X button of the window is just one of the ways to send `Closed` events. For example, When `Close()` is called, or if the user presses ALT+F4, `Closed event` will also be raised.
> 3 votes

---
Tags: sfml, keyboard
---


title: Google Play Games achievements have 0xp

text:
# Question
Title: Google Play Games achievements have 0xp
I'm currently working on adding achievements to an existing game. Achievements are not published yet. When unlocking an achievement, we have system popup that says it gained 0xp. Every achievement have correct xp values assigned in Play Games Console UI.

Is that "0xp" thing happens because of unpublished achievements? Did anyone have this problem?

# Answer
> 1 votes
This problem was fixed after publishing achievements. Seems like unpublished achievements for a published game have this issue. Unfortunately I couldn't find any mention of this behavior on Google Play Services Guides page.

---
Tags: android, google-play, google-play-services, achievements
---