title: Need some help with A* Pathfinding

text:
# Question
Title: Need some help with A* Pathfinding
I am trying to read in from 2 text files (one contains the start and end coordinates, the other is a map of costs for use with the Manhatten Distance) and I'm really struggling with the implementation of the code from various algorithms I've found.

I've been able to read in the text files and put them into 2 separate arrays fine, the real issue I'm having is with adding to the open list and compares their costs so that the smallest goes onto the priority queue and then compare its neighbors, I just cannot work this out after hours upon hours of reading and watching YouTube videos on the subject, any help?

Here is my code so far:

```
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <deque>
#include <math.h>
#include <vector>
#include <deque>
using namespace std;

struct pNode
{
    int xPos;
    int yPos;
    pNode* Parent;
    pNode* child;

    float g; //Cost of this Node plus predecessors
    float h;//Heuristic estimate to Goal state
    float f; // f= g+h

    pNode() :
        Parent(0),
        child(0),
        g(0.0f),
        h(0.0f),
        f(0.0f)
    {
        bool wall = false;
        bool water = false;
        bool grass = false;
        bool startNode = false;
        bool endNode = false;
    }
};

class compare
{
public:

    bool compareNodes()
    {
        pNode *x;
        pNode *y;
        return x->f > y->f;
    }
};

class dMap
{
public:
    static const int ARRAY_SIZE = 100;

    void LoadFile();
    void Display() const;
    void priorityQueue();
    void aStar();

private:
    pNode   mArray[ARRAY_SIZE];
    pNode   mArrayCoords[ARRAY_SIZE];
};

void dMap::LoadFile()
{
    ifstream infile("dMap.txt");
    if (!infile)
    {
        cout << "Cannot open File";
        exit(1);
    }
    for (int i = 0; i < ARRAY_SIZE; i++)
    {
        infile >> mArray[i].xPos >> mArray[i].yPos;
    }
}

void dMap::priorityQueue()
{
    int disX = mArray[ARRAY_SIZE].xPos;
    int disY = mArray[ARRAY_SIZE].yPos;
    int heuristic(int xPos, int yPos);

    struct pQueue
    {

        int fx;
        int fy;
        int x;
        int y;

        int cost;
        int h;
        int totalCost;

        pQueue(int _x, int _y, int _cost)
        {
            x = _x;
            y = _y;
            cost = _cost;
            h = heuristic(x, y);

            totalCost = cost + h;
        }

        int manhattenDistance(int xPos, int yPos)
        {
            return abs(xPos - fx) + abs(yPos - fy);
        }//Manhatten Distance

        bool operator<(const pQueue &b)const
        {
            return totalCost>b.totalCost;
        }

    };
}

void dMap::aStar()
{
    LoadFile();

    pNode mArrayCoords[ARRAY_SIZE];
    ifstream infile("dCoords.txt");
    if (!infile)
    {
        cout << "Cannot open File";
        exit(1);
    }
    for (int i = 0; i <9; i++)
    {
        infile >> mArrayCoords[i].xPos >> mArrayCoords[i].yPos;
    }

    deque <pNode*> openList;
    pNode* startNode = new (pNode);
    deque <pNode*> closedList;
    pNode* endNode = new (pNode);
    pNode* currentNode = new (pNode);
    deque <pNode*> finalList;

    //startNode ->

}

```

# Answer
> 0 votes
Currently, I am working on the same thing, except that the nodes are hexagons and not squares(I assume you are using squares).

Red Blob Games is a great resource.

> 2.4 A\* Search
>
> A\* is almost exactly like Dijkstra’s Algorithm, except we add in a heuristic. Note that the code for the algorithm isn’t specific to grids. Knowledge about grids is in the graph class (SquareGrids in this case) and in the heuristic function. Replace those two and you can use the A\* algorithm code with any other graph structure.

```
inline double heuristic(SquareGrid::Location a, SquareGrid::Location b) {
  int x1, y1, x2, y2;
  tie (x1, y1) = a;
  tie (x2, y2) = b;
  return abs(x1 - x2) + abs(y1 - y2);
}

```

and

```
template<typename Graph>
void a_star_search
  (const Graph& graph,
   typename Graph::Location start,
   typename Graph::Location goal,
   unordered_map<typename Graph::Location, typename Graph::Location>& came_from,
   unordered_map<typename Graph::Location, double>& cost_so_far)
{
  typedef typename Graph::Location Location;
  PriorityQueue<Location, double> frontier;
  frontier.put(start, 0);

  came_from[start] = start;
  cost_so_far[start] = 0;

  while (!frontier.empty()) {
    auto current = frontier.get();

    if (current == goal) {
      break;
    }

    for (auto next : graph.neighbors(current)) {
      double new_cost = cost_so_far[current] + graph.cost(current, next);
      if (!cost_so_far.count(next) || new_cost < cost_so_far[next]) {
        cost_so_far[next] = new_cost;
        double priority = new_cost + heuristic(next, goal);
        frontier.put(next, priority);
        came_from[next] = current;
      }
    }
  }
}

```

> The type of the priority values including the type used in the priority queue should be big enough to include both the graph costs (cost\_t) and the heuristic value. For example, if the graph costs are ints and the heuristic returns a double, then you need the priority queue to accept doubles. In this sample code I use double for all three (cost, heuristic, and priority), but I could’ve used int because my costs and heuristics are integer valued.
>
> Minor note: It would be more correct to write frontier.put(start, heuristic(start, goal)) than frontier.put(start, 0) but it makes no difference here because the start node’s priority doesn’t matter. It is the only node in the priority queue and it is selected and removed before anything else is put in there.

```
#include "redblobgames/pathfinding/a-star/implementation.cpp"

int main() {
  GridWithWeights grid = make_diagram4();
  SquareGrid::Location start{1, 4};
  SquareGrid::Location goal{8, 5};
  unordered_map<SquareGrid::Location, SquareGrid::Location> came_from;
  unordered_map<SquareGrid::Location, double> cost_so_far;
  a_star_search(grid, start, goal, came_from, cost_so_far);
  draw_grid(grid, 2, nullptr, &came_from);
  std::cout << std::endl;
  draw_grid(grid, 3, &cost_so_far, nullptr);
  std::cout << std::endl;
  vector<SquareGrid::Location> path = reconstruct_path(start, goal, came_from);
  draw_grid(grid, 3, nullptr, nullptr, &path);
}

```

> 2.4.1 Straighter paths
>
> If you implement this code in your own project you might find that some of the paths aren’t as “straight” as you’d like. This is normal. When using grids, especially grids where every step has the same movement cost, you end up with ties: many paths have exactly the same cost. A\* ends up picking one of the many short paths, and very often it doesn’t look good to you. The quick hack is to break the ties, but it’s not entirely satisfactory. The better approach is to change the map representation, which makes A\* a lot faster, and also produces straighter, better looking paths. However, that only works for mostly-static maps where every step has the same movement cost. For the demos on my page, I’m using a quick hack, but it only works with my slow priority queue. If you switch to a faster priority queue you’ll need a different quick hack.
>
> 2.4.2 TODO Heuristic function should be template parameter
>
> I should make the heuristic into a template parameter instead of being a global function.

Digging around here should help, if you haven't already.

# Answer
> 0 votes
To keep the answer simple as possible, I will use pseudo code:

```
start: findPath {

    openList.push(start)
    While (current != end) {
       if openList is empty
           error: no path found
        get current.neighbours
        for each neighbour {
            //prevents the same cell being looked at twice
            if neighbour is not in closedList {
                if neighbour is wall OR outside maze
                    discard neighbour
                else
                    Add to open list
            }
        }
        sort openList by heuristic (lowest to front)
        current = openlist.front
        openList.pop_front
    }

    path = closedlist
End: findPath

```

This algorithm will ensure you always find the shortest path.

Further improvements can be performed such as jump points, but I think you should wrap your head around the simple version first.

To do the sorting, it's pretty simple you store the nodes in a vector, like so:

```
std::vector<node> OpenList;

```

Then simply call:

```
std::sort(OpenList.begin(), OpenList.end(), [](node a, node b) {
    return b.h < a.h;
});

```

Once all neighbours are inserted.

This way, all you need is a data representation of your maze (walkable/unwalkable areas and boundaries, and any modifiers to f/g scores). You will use this representation to compute your H score for each neighbour, and if the node is walkable.

Due to this, you do not want to parse from file directly into the open list, as it's size is important.

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


title: How can i check when rotation is ended?

text:
# Question
Title: How can i check when rotation is ended?
At the top of script:

```
public Quaternion _lookRotation;

```

In Update:

```
void Update()
{
 transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation,
 Time.deltaTime * RotationSpeed);
}

```

I want to know when the transform rotation ended and is at \_lookRotation Maybe using some flag ?

This is my code:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour
{
    public UnityStandardAssets.ImageEffects.Blur blur;
    public UnityStandardAssets.ImageEffects.BlurOptimized blurOptimized;
    public FirstPersonController fpc;
    public float fadeDuration = 5;
    public float startAcceleration = 0.6f;
    public float endAcceleration = 0.6f;
    public float maxSpeed = 1.0f;
    public float rotationSpeed = 0.6f;

    private Material material;
    private float targetAlpha = 0;
    private float lerpParam;
    private float startAlpha = 1;
    private bool rotated = false;
    private Quaternion clampedTargetRotation;

    void Start()
    {
        material = GetComponent<Renderer>().material;
        SetMaterialAlpha(1);

        fpc.enabled = false;
    }

    void Update()
    {
        lerpParam += Time.deltaTime;

        float alpha = Mathf.Lerp(startAlpha, targetAlpha, lerpParam / fadeDuration);
        SetMaterialAlpha(alpha);

        if (alpha == 0)
        {
            fpc.enabled = true;

            if (rotated == false)
            {
                fpc.GetComponent<FirstPersonController>().enabled = false;
                rotationSpeed += Mathf.Clamp(rotationSpeed + startAcceleration * Time.deltaTime, 0, maxSpeed);
            }

            if (fpc.transform.localRotation == Quaternion.Euler(0,0,0))
            {
                fpc.GetComponent<FirstPersonController>().enabled = true;
                rotationSpeed = Mathf.Clamp(rotationSpeed - endAcceleration * Time.deltaTime, 0, maxSpeed);
                blur.enabled = false;
                blurOptimized.enabled = false;

                rotated = true;
            }

            clampedTargetRotation = Quaternion.RotateTowards(fpc.transform.localRotation, Quaternion.Euler(0, 0, 0), rotationSpeed * Time.deltaTime);
            fpc.transform.localRotation = clampedTargetRotation;
        }
    }

    public void FadeTo(float alpha, float duration)
    {
        startAlpha = material.color.a;
        targetAlpha = alpha;
        fadeDuration = duration;
        lerpParam = 0;
    }

    private void SetMaterialAlpha(float alpha)
    {
        Color color = material.color;
        color.a = alpha;
        material.color = color;
    }
}

```

What i want in the rotation part is to start the rotation slowly and then accelerate a bit and then in the end when it's getting "close enough" to 0,0,0 so start accelerate down until complete stop. Complete stop not must be at 0,0,0 but close to it. Th way i'm doing it now is wrong i'm not using the t 0/1 solution and not courtine.

The rotation now in my script is almost working as i want. It start slowly and accelerate but in the end it stop at once without smoothly accelerate down.

# Answer
All Lerp functions (Mathf, Vector3, Quaternion) utilize the same base formula:

> **P = P0 + (t * (P1 - P0)), 0 \< t \< 1**

Which means that the interpolation depends on t, a normalized value between 0 and 1. So, what you can do, is interpolate your rotation with a t variable as reference, and "End" your rotation once t reaches 1.

Quick example:

```
    [SerializeField] Quaternion targetRotation;    /// <summary>Rotation you want to achieve.</summary>
    [SerializeField] private float s;       /// <summary>Rotation duration.</summary>
    private Quaternion initialRotation;     /// <summary>Your GameObject's initial rotation.</summary>
    private float t;                        /// <summary>Your 't' reference.</summary>

    void Awake()
    {
        initialRotation = transform.rotation;
    }

    void Update()
    {
        if(t < 1.0f)
        {
            transform.rotation = Quaternion.Lerp(initialRotation, targetRotation, t);
            t += (Time.deltaTime / s); /// Each 60 frames [optimally] t reaches 1, divided by your duration, it will reach 1 on 'x' seconds.
        }
        else /// Your rotation ends here:
        { /// reset 't' [if you please], and reset 'initialRotation'
            initialRotation = transform.rotation;
        }

    }

```

Hope it gives you a foundation basis to solve your problem.
> 1 votes

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


# Question
Title: Could you create a game for an older system (say, SNES) and sell it with an emulator as well as the game?
I was looking into development for the SNES in assembly, as programming in assembly is my hobby. I then had the thought: what if I could sell my native SNES games for modern use (on steam, bundled with an emulator for example)?

# Answer
Yes there should be nothing illegal about emulation in itself (any virtual machines such as Java VM would similarly be illegal, if unsure ask a lawyer) and in this instance the SNES has no BIOS so that isn't an issue either but you'll need to license the rights to the emulator (if it does not permit commercial use freely already) or write the emulator yourself.

And you'll likely have to add some custom features to make the emulator and emulated game more user-friendly for the computer user experience, for example:

* Auto-boot your game with the emulator locked to your game.
* Allow the game to give achievements?
* Cloud saves?

It certainly has been done before with other platforms. For example Castlevania: Symphony of the Night for XBox 360, and classic games released on Steam already use bundled emulators such as those by Sega.
> 1 votes

---
Tags: legal, monetization, sales
---


# Question
Title: How to throw sprites at random direction in unity
I have 2 Questions;

1.How do i throw square in different directions on every click while maintaining cyan border restriction

2.How to keep rotating square after i click in z-axis

Check This Video For Hint

# Answer
> 1 votes
If you want to pick a random direction in a cone defined by two angles, then you simply create a random angle between those values (`minAngle + random * (maxAngle - minAngle)`), then you use trigonometric equations to convert it into a vector:

```
x = cos(angle)
y = sin(angle)

```

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


# Question
Title: When a sprite is rotating to follow an angle, how to prevent it from reversing direction after a point?
Below is a section of my code which handles a player's sprite rotating towards an angle after a user touches the screen:

```
touchState = TouchPanel.GetState();
Vector2 touchPosition;

if (touchState.Count > 0)
{
   touchPosition = new Vector2(touchState[0].Position.X, touchState[0].Position.Y);
   targetPosition = Math.Atan2(player.Position.X - touchPosition.X, player.Position.Y - touchPosition.Y);

if (angle_radians < targetPosition)
{
    angle_radians += 2 * fps;
}

if(angle_radians > targetPosition)
{
    angle_radians -= 2 * fps;
}

player.Angle = angle_radians * -1;
}

```

The problem I'm having is that when the angle goes past a certain point (I believe 3.15 radians?), the logic no longer functions correctly and the sprite reverses direction in a 360 circle until it meets the target position again.

I know there is something I'm missing from this logic, and I can see the problem, but I'm not sure how to approach handling it.

How would I prevent the sprite from reversing direction?

Thanks

**EDIT: I tried the solution below but I only receive a positive number from 0-6 for angle\_distance, what have I done wrong?**

```
            if (touchState.Count > 0)
            {
                touchPosition = new Vector2(touchState[0].Position.X, touchState[0].Position.Y);
                targetPosition = Math.Atan2(player.Position.X - touchPosition.X, player.Position.Y - touchPosition.Y);
                angle_distance = targetPosition - angle_radians + Math.PI;
                angle_distance = angle_distance - Math.Floor(angle_distance / 2 / Math.PI) * 2 * Math.PI;

                if (angle_distance < 0)
                {
                    angle_radians -= 2 * fps;
                }

                if (angle_distance > 0)
                {
                    angle_radians += 2 * fps;
                }

                player.Angle = angle_radians * -1;
            }

```

**EDIT: I now realise my mistake, correct solution is below**

```
if (touchState.Count > 0)
                {
                    touchPosition = new Vector2(touchState[0].Position.X, touchState[0].Position.Y);
                    targetPosition = Math.Atan2(player.Position.X - touchPosition.X, player.Position.Y - touchPosition.Y);

                    angle_distance = targetPosition - angle_radians + Math.PI;
                    angle_distance = angle_distance - Math.Floor(angle_distance / 2 / Math.PI) * 2 * Math.PI;

                    if (angle_distance < Math.PI)
                    {
                        angle_radians -= 2 * fps;
                    }

                    if (angle_distance > Math.PI)
                    {
                        angle_radians += 2 * fps;
                    }

                    player.Angle = angle_radians * -1;
                }

```

# Answer
> 0 votes
First, find the signed distance between the two angles:

```
dist = targetAngle - currentAngle + pi
dist = dist - floor(dist / 2 / pi) * 2 * pi - pi

```

If it's negative, then subtract from the current angle to reach the other angle in the shortest time, if it's positive, then add to it.

---
Tags: c#, 2d
---


# Question
Title: How to always land a square box in 90 degree
How can i Always Land a box in 90 degree

Here What i want

Here what i don't want

```
{
public Rigidbody2D boxRb;
public float jumpSpeed;
 public Vector3 rotation;
public float rotationSpeed;
public bool rotationEnabled;
public float gravityMultiplier;
void FixedUpdate()
{
    if (Input.GetMouseButtonDown(0))
    {
        boxRb.velocity = jumpSpeed * Vector2.up;
    }
    if (rotationEnabled = true)
    {
        transform.Rotate(rotation * rotationSpeed * Time.deltaTime);
    }
    if (Input.GetMouseButtonDown(1))
    {
        boxRb.velocity += Vector2.up * Physics2D.gravity.y * (gravityMultiplier - 1) * Time.deltaTime;
    }

}
void OnCollisionEnter2D(Collision2D collision)
{
    rotationEnabled = false;
    Debug.Log("Collided");
    rotationSpeed = 0f;
    boxRb.constraints = RigidbodyConstraints2D.FreezePositionX;
    transform.Rotate(0, 0, 90f);

}
void OnCollisionStay2D(Collision2D collision)
{
    rotationEnabled = false;
    Debug.Log("In collison");
    rotationSpeed = 0f;
    boxRb.constraints = RigidbodyConstraints2D.FreezePositionX;
}
void OnCollisionExit2D(Collision2D collision)
{
    rotationEnabled = true;
    Debug.Log("Free");
    rotationSpeed = 10f;
}

```

}

# Answer
## If you have a fixed speed:

If you know the starting speed (the speed you launch the box at) and the gravity, then the time the square spends in the air is `v / g`, where `v` is the speed and `g` is the gravitation. The square has to rotate At least `n * 90°` in this time frame, where `n` is an integer. This means, that the angular velocity must be `n * 90 / time`, where `n` is an integer and `time` is the time the square spends in the air.

## If you have a fixed angular velocity:

Similarily, he square must rotate at least `n * 90°`, where `n` is an integer. Pick a random `n` and divide `n * 90°` by the angular velocity to get the time the square needs to spend in the air. The velocity must be `g * time`, where `g` is the gravitational acceleration.
> 2 votes

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


# Question
Title: Custom List Editor dependent on data from separate class's data
I want to make a custom inspector that I'm not really sure how to approach. The idea is I have a quest framework with a class that holds onto the quest data and another class that is intended to hold onto dialogue data. The quest system is agnostic of my dialogue system.

I want to be able to display the quest and dialogue data this way:

QuestName0

* DialogueGiveQuest (TextAsset field)
* DialogueQuestIsActive (TextAsset field)
* DialogueQuestIsComplete (TextAsset field)

QuestName1

* DialogueGiveQuest (TextAsset field)
* DialogueQuestIsActive (TextAsset field)
* DialogueQuestIsComplete (TextAsset field)

etc...

Here's a pseudocode class layout

```
public class QuestData : MonoBehaviour
{
    List<Quest> quests;
}

public class DialogueData : MonoBehaviour
{
    public TextAsset dialogueGiveQuest;
    public TextAsset dialogueQuestIsActive;
    public TextAsset dialogueQuestIsComplete;
}

public class Interaction : MonoBehaviour
{
    QuestData questData;
    List<DialogueData> dialogueData;
}

[CustomEditor(typeof(Interaction))]
public class InteractionEditor : Editor
{
    public override void OnInspectorGUI()
    {
        var interactionData = (InteractionData)target;
        //foreach interactionData.questData.quests
          // draw quest name
          // make sure there's a dialogueData element for each quest
          // draw field for each DialogueData
    }
}

```

An obvious issue is dialogueData doesn't care about what's going on with questData.quests so if the inspector were to draw normally it would display 2 lists. I'd like the dialogue data to add and remove elements to itself depending on the quest data but that sounds like it be a real challenge to serialize.

# Answer
You should check EditorGUILAyout's API to check the drawing field functions. To get the classes's properties (or GameObject's for that matter) you will need to use reflection to get their data, so you can know which EditorGUILayout fields to draw. A vague example (haven't tested it, but it goes sorta this way):

```
    public MonoBehaviour mono;
    FieldInfo[] fieldsInfo;
    BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; /// You should check .NET's documentation to get detailed info about it.

    void Awake()
    {
        fieldsInfo = mono.GetType().GetFields(flags);
        foreach(FiendInfo field in fieldsInfo)
        {
            Debug.Log("Field is called: " + field.Name);
        }
    }

    void OnInspectorGUI()
    {
        fieldsInfo = mono.GetType().GetFields(flags);
        foreach(FiendInfo field in fieldsInfo)
        {
            if(field.GetType == typeof(UnityEngine.Object))
            {
                Unity.Object obj = null;
                EditorGUILayout.ObjectField(obj, typeof(UnityEngine.Object), true);
            }
        }
    }

```

That seems kinda complex, so what you can do is to have classes, like DialogueData, don't inherit from monobehaviour, and give it the \[System.Serializable\] attribute, so in a controller GameObject, you can have a list of those classes so they show on that GameObject's inspector, exmaple:

```
    [System.Serializable]
    public class DialogueSentence
    {
        [SerializeField] private String _actor;
        [SerializeField] private string _sentence;

        public string Actor
        {
            get { return _actor; }
            set { _actor = value; }
        }

        public string Sentence
        {
            get { return _sentence; }
            set { _sentence = value; }
        }
    }

    public class DialogueController : MonoBehaviour
    {
        public List<DialogueSentence> sentences; /// Now you have your Senence class's list on the inspector.
    }

```

Sorry if I didn't use examples directly from your classes.

As a side note, I suggest you explore Text Area's Attribute to stylize your dialogue boxes on the inspector.

**Edit:** I forgot to give \[SerializeField\] attributes to the DialogueSentence fields, so they appear on your public list. Also, I changed the class's names for the sake of avoiding ambiguity.
> 1 votes

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


# Question
Title: Why i'm not getting the FPSController Rotation values?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class RotateObject : MonoBehaviour
{
    public UnityStandardAssets.ImageEffects.Blur blur;
    public UnityStandardAssets.ImageEffects.BlurOptimized blurOptimized;
    public FadeScript fadescript;
    [SerializeField] Quaternion targetRotation;    /// <summary>Rotation you want to achieve.</summary>
    [SerializeField] private float s;       /// <summary>Rotation duration.</summary>
    private Quaternion initialRotation;     /// <summary>Your GameObject's initial rotation.</summary>
    private float t;                        /// <summary>Your 't' reference.</summary>
    private FirstPersonController fpcscript;

    void Awake()
    {
        fpcscript.enabled = false;
        fpcscript = transform.GetComponent<FirstPersonController>();
        initialRotation = transform.localRotation;
    }

    void Update()
    {
        if (fadescript.alphaZero == true)
        {
            if (t < 1.0f)
            {
                transform.rotation = Quaternion.Lerp(initialRotation, targetRotation, t);
                t += (Time.deltaTime / s); /// Each 60 frames [optimally] t reaches 1, divided by your duration, it will reach 1 on 'x' seconds.
            }
            else /// Your rotation ends here:
            { /// reset 't' [if you please], and reset 'initialRotation'
                initialRotation = transform.rotation;

                blur.enabled = false;
                blurOptimized.enabled = false;
                fpcscript.enabled = true;
            }
        }
    }
}

```

The script is attached to FPSController. In the Inspector the Rotation of the FPSController is: X = 7 Y = 112 Z = -31

But when i'm using a break point on the line in the Awake:

```
initialRotation = transform.localRotation;

```

I see that initialRotation values are: (-0.2, 0.8, -0.2, 0.5)

What i want to do is to rotate the transofrm from X = 7 Y = 112 Z = -31 to rotation 0,0,0 That is why i also didn't set any values to targetRotation since i want it to rotate to 0,0,0

# Answer
> 2 votes
The values that the Log throws you are of a Quaternion, which is a matrix of 4 components **{ x, y, z, w }**, if you would like to Log your Quaternion in an Euler (x, y, z) format, Log **transform.eulerAngles** instead.

For the next point, if you want to set the rotation to Euler(0, 0, 0) you can either:

* Use Quaternion.Euler(0f, 0f, 0f);
* Use Quaternion.identity

And assign that rotation to the Lerp.

```
    void Awake()
    {
        fpcscript.enabled = false;
        fpcscript = transform.GetComponent<FirstPersonController>();
        initialRotation = transform.localRotation;

        Debug.Log("Rotation on Euler format is: " + transform.eulerAngles);
    }

    void Update()
    {
        if (fadescript.alphaZero == true)
        {
            if (t < 1.0f)
            {
                transform.rotation = Quaternion.Lerp(initialRotation, Quaternion.identity, t);
                t += (Time.deltaTime / s); /// Each 60 frames [optimally] t reaches 1, divided by your duration, it will reach 1 on 'x' seconds.
            }
            else /// Your rotation ends here, so you reached Euler(0, 0, 0).
            { /// reset 't' [if you please], and reset 'initialRotation'
                initialRotation = transform.rotation;

                blur.enabled = false;
                blurOptimized.enabled = false;
                fpcscript.enabled = true;
            }
        }
    }

```

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


title: Platformer AI Jump Calculation

text:
# Question
Title: Platformer AI Jump Calculation
Thank you for taking the time to read my question, I will try to keep it as concise as I can.

I am making a 2D-platformer game. I am in the process of programming AI that can intelligently traverse their terrain. AI are able to jump, in a fashion similar to many other 2D-platformers:

* When the AI jumps, it is given a fixed initial Y-Velocity.
* The AI has a flexible time where it may ignore gravity to give it a variable jump height/air time. (This mimics the way that the player is able to jump, where the player character may jump higher if the player holds down the jump-button longer.)
* After this time expires, or the AI "releases the jump button", gravity begins to affect the jump arc. The acceleration rate of gravity is also constant.
* The velocity on the X-axis is constant.

**Question:** How would an AI find the minimum amount of time that it will have to "hold down its jump button" to clear an expanse between a starting jump point, and a desired target?

# Answer
If you fix the point you jump from and the point you want to land at you can divide the movements into two parts (t1 & t2 in the equautions) and get a system of 2 equations, which you can solve (under the assumption that all length have the right sign).

I chose the smaller of the two roots, because the second should discribe jumping past the point and then falling backwards with negative t2, which doesn't make sense.

You might have to pad the solution a bit, since your physic system is probably not continuous and thus you probably cannot start and stop jumping at the exact moment (or collide with the second platform, if your landing isn't right on the edge)
> 2 votes

# Answer
The order in which you compute values in this problem can create different edge cases.

The above answer assumes knowledge of s\_x and s\_y, the x and y distances you want to travel in the air during your jump. You do know s\_y based on the vertical distance between platforms (assuming your platforms are flat). *This is just a word of warning that the optimal s\_x may be trickier to determine.*

You cannot necessarily assume that you will jump from the very edge of the ledge you are on. If the platform is narrow and low you may jump over it and into a gap on the opposite side of it. You also cannot necessarily assume that you will land on the near side of the destination platform. Supposing the platform you are on is also very small, you may not be able to jump from far enough back to land on the front of the destination platform. There is also the case where you have to jump over a wall (the platforms have almost no x gap and a wide y gap). In this case, if you need to maintain your horizontal velocity, you'll need to jump significantly earlier than required by the gap.

Additional information about your problem might make these issues simpler to handle. Do you know that either platform is particularly large? Can you stop moving forward in midair? Do you want to maintain maximum x velocity whenever possible (for speed-running, say)?

In the most general case if the two platforms cover x-values in segments \[x\_0,x\_1\] and \[x\_2,x\_3\], then you at least have bounds for s\_x. (x\_3 - x\_0) \>= s\_x \>= (x\_2 - x\_1).

In general, you want to pick the smallest s\_x possible, it just might be the case that there's such a thing as an s\_x that is too small.
> 1 votes

---
Tags: 2d, ai, platformer
---


title: Multiplayer Testing with Steam Accounts

text:
# Question
Title: Multiplayer Testing with Steam Accounts
I'm build a multiplayer first person shooter, that supports 32 players.

What is the best way to test large quantities of players?

I'll need 32 steam accounts, with 32 machines to run on. Less, if I can switch to virtual machines.

# Answer
> 1 votes
You either need to hire and pay for actual testers, like how most AAA companies do it, or release the game in early access, like how most indie game developers do it. Choosing the right option depends on your budget and the current state of the game.

---
Tags: multiplayer, online, steam
---


# Question
Title: What kind of work is usually done by scheduled tasks
I was reading about how task schedulers work in game engines. What is unclear to me is what kind of work is usually scheduled inside these tasks.

Do engines usually tick an actor inside a separate task? And if that actor triggers a pathfinding request, would that be a subtask? Should a pathfinding task allocate its own memory or access a global navmesh data for example?

I guess what I would like are real life examples on how such parallel systems can and are used in practice. Maybe some best practices based on examples would be nice. Most literature I found was quite theoretical and left me with so many questions.

# Answer
Parallelism is still a hotly debated subject in game engine design, and yes, is very heavily based in theory. I'll try to keep this as non-technical as I can.

Here are some (but not all) general rules about parallel computing:

1. No two or more tasks can modify the same data at the same time.
2. Tasks should complete before any dependent tasks are executed.
3. Two or more tasks running in parallel should not block each other.
4. The cost of starting a task should not outweigh that of executing the task itself.

It's definitely worth trying to wrap your head around Amdahl's Law, as it is extremely important when considering parallel design.

Following is the typical game engine update cycle:

1. Update positions (motion)
2. Collision detection (collisions following motion)
3. Game logic (scripts, event handling etc)
4. AI/Path-finding
5. Physics (physical collision response)
6. Animation (state changes based on game logic and collisions)
7. Rendering

Some of these tasks are dependent on preceding stages.

E.g. Physics is useless, unless collisions are detected.

Rendering, however, only cares about objects **current** state. Any state changes can be picked up on the next render cycle. This is achieved through the use of *proxies* and *observer* types.

Animation is the same, as is motion, AI and path-finding.

So, we can say that a single repeating task should be to detect collisions and perform physics.

This is thread #1

Next, we run the rendering system on the main thread (there are compelling technical reasons for this). Let's call this thread #0.

AI and rendering, in some cases is not independent, so we add a task to perform animation on thread #0, preceding rendering.

Game logic can go on thread #2, and respond to game events being generated

Path-finding and AI operations can go on thread #3

These tasks are more or less independent of one another, and so can be said to run in ***free step***

If you find yourself in a situation where inter-thread synchronisation is necessary, you can block execution, until a task on another thread is complete, but typically this points to bad architecture or data design and is commonly known as ***lock step***.

Another way is to run through the update cycle, and parallelise the individual jobs to do, so as to divide updating the positions and orientations of 100 objects between N tasks. This is known as ***data parallelism*** and is how modern graphics cards work.

With regards to **task scheduling**, see the above rules: If the tasks are ***embarrassingly parallel*** i.e. the nature of the task lends itself well to being assigned time on a thread, and does not interfere with other tasks, then do so.

But consider rule #4: if you have 4 threads and 100 objects, do you:

* (a) create 100 small tasks and split them between the threads(4x 25 tasks), or
* (b) create 4 tasks to process 25 objects each?

If the cost of creating and scheduling the task is comparable to executing it, then Amdahl's Law comes into effect, and you end up *losing* performance, if you choose (a). Therefore you choose (b), and cut down as much overhead as possible. Creation of threads are not free, and neither is locking down the scheduler/thread pool to assign or retrieve tasks. Therefore the task cost must be greater than the cost of scheduling. In most cases, this will be true, not it is not by any means guaranteed.

So, the tl;dr of the matter is: Schedule jobs, which are independent(if possible), and consist of a high enough computational cost to justify it's own task. In the case where the task set up cost is too high to justify a set of single tasks, group the jobs together into a larger task, and have that executed on it's own thread in parallel with with similar tasks of the same workload.
> 1 votes

---
Tags: architecture, multithreading
---


# Question
Title: How to make Unity Layout switch while in Play mode
I'm looking for a way to auto switch the `Unity` layout when I go to play mode.

*I want to `Unity Editor` layout automatically changes to **my preset layout** when I click on `Play` button and When I `stop` the game, It goes back to the default layout.*

# Answer
> 5 votes
After reading Unity API, I found the solution! It's absolutely possible to change the `Unity` layout during the `Play Mode`. We can use `Unity Utility` class in `UnityEditor` namespace.

*The code below will be run in Editor and change the layout if we click on play button.*

> **Update:** Amended code, Thanks to *@Ed Marty*

```
using UnityEngine;
using UnityEditor;

namespace Assets.Editor {
    [InitializeOnLoad]
    public class AutoLayoutChanger {
        static AutoLayoutChanger() {
            EditorApplication.playmodeStateChanged = HandleOnPlayModeChanged;
        }

        static void HandleOnPlayModeChanged() {
            // This method is run whenever the playmode state is changed.
            if (EditorApplication.isPlaying) {
                EditorUtility.LoadWindowLayout("Preset Layout");
                // do stuff when the editor is played.
            } else if (!EditorApplication.isPaused) {
                EditorUtility.LoadWindowLayout("Default Layout");
                // other than playmode
            }
        }
    }
}

```

# Answer
> 1 votes
So going around the interwebs I came up with this solution.

You can save your custom layout by clicking the layout button in the top right of the editor and the selecting save layout.

Now we need a `[ExecuteInEditMode]` scripted place inside the scene we want to change layout when entering playmode.

```
using UnityEditor;
using UnityEngine;
[ExecuteInEditMode]
public class ChangeLayoutInPlayMode : MonoBehaviour  {
    void OnEnable()
    {
#if UNITY_EDITOR
        EditorApplication.playModeStateChanged += StateChange;
#endif
    }
#if UNITY_EDITOR
    void StateChange(PlayModeStateChange state)
    {
        if (EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying)
        {
            LayoutTool.LoadLayoutFromAsset("C:/Users/Uri/AppData/Roaming/Unity/Editor-5.x/Preferences/Layouts/custom.wlt");
        }
        if ( !EditorApplication.isPlaying)
        {
            LayoutTool.LoadLayoutFromAsset("C:/Users/Uri/AppData/Roaming/Unity/Editor-5.x/Preferences/Layouts/Default.wlt");
        }
    }
#endif

```

Note that you would have to change the path to the default layout and the custom one to fit your instalation of unity. It is generally in User/usernama etc.

Finaly the thing that does the magic of saving the custom layout and loading it is this utility class ( not mine got it from the web)

```
using UnityEngine;
using UnityEditor;

using System.IO;
using System.Reflection;

using Type = System.Type;

public static class LayoutTool
{

    private static MethodInfo _miLoadWindowLayout;
    private static MethodInfo _miSaveWindowLayout;
    private static MethodInfo _miReloadWindowLayoutMenu;

    private static bool _available;
    private static string _layoutsPath;

    static LayoutTool()
    {
        Type tyWindowLayout = Type.GetType("UnityEditor.WindowLayout,UnityEditor");
        Type tyEditorUtility = Type.GetType("UnityEditor.EditorUtility,UnityEditor");
        Type tyInternalEditorUtility = Type.GetType("UnityEditorInternal.InternalEditorUtility,UnityEditor");

        if (tyWindowLayout != null && tyEditorUtility != null && tyInternalEditorUtility != null)
        {
            MethodInfo miGetLayoutsPath = tyWindowLayout.GetMethod("GetLayoutsPath", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
            _miLoadWindowLayout = tyWindowLayout.GetMethod("LoadWindowLayout", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string), typeof(bool)  }, null);
            _miSaveWindowLayout = tyWindowLayout.GetMethod("SaveWindowLayout", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
            _miReloadWindowLayoutMenu = tyInternalEditorUtility.GetMethod("ReloadWindowLayoutMenu", BindingFlags.Public | BindingFlags.Static);

            if (miGetLayoutsPath == null || _miLoadWindowLayout == null || _miSaveWindowLayout == null || _miReloadWindowLayoutMenu == null)
                return;

            _layoutsPath = (string)miGetLayoutsPath.Invoke(null, null);
            if (string.IsNullOrEmpty(_layoutsPath))
                return;

            _available = true;
        }
    }

    // Gets a value indicating whether all required Unity API
    // functionality is available for usage.
    public static bool IsAvailable
    {
        get { return _available; }
    }

    // Gets absolute path of layouts directory.
    // Returns `null` when not available.
    public static string LayoutsPath
    {
        get { return _layoutsPath; }
    }

    // Save current window layout to asset file.
    // `assetPath` must be relative to project directory.
    public static void SaveLayoutToAsset(string assetPath)
    {
        SaveLayout(Path.Combine(Directory.GetCurrentDirectory(), assetPath));
    }

    // Load window layout from asset file.
    // `assetPath` must be relative to project directory.
    public static void LoadLayoutFromAsset(string assetPath)
    {
        if (_miLoadWindowLayout != null)
        {
            string path = Path.Combine(Directory.GetCurrentDirectory(), assetPath);
            _miLoadWindowLayout.Invoke(null, new object[] { path,true });
        }
    }

    // Save current window layout to file.
    // `path` must be absolute.
    public static void SaveLayout(string path)
    {
        if (_miSaveWindowLayout != null)
            _miSaveWindowLayout.Invoke(null, new object[] { path });
    }

}

```

# Answer
> 0 votes
Unchecking Maximize on Play might be helpful. Additionally, pressing pause button changes the layout while playing.

---
Tags: unity, editors
---


# Question
Title: Can an unmodifiable 3D map be one large model or many small models?
Unmodifiable meaning that any ingame actions have no result on the terrain.
Like in Source games.

Question: Should I export one large model of the map, or should I split it into smaller chunks? If so, how?

# Answer
Given that you have tagged the question as "rendering", I will say it depends on the poly count of the terrain.

If rendering the entire terrain causes problems due to high poly count, then chunk it, and perform visibility checks on each chunk. This may, in turn, allow you to increase the poly count of each chunk, thereby improving how it looks.

However, given that you have also tagged the question as "physics" engine, you may want to keep the poly count of each chunk down, in order to make collision detection cheaper.

Coincidentally, chunking is how open world, voxel based games (like Minecraft) work.
> 1 votes

---
Tags: rendering, physics-engine
---


# Question
Title: Why do my character's feet slide when I auto-configure a humanoid rig in Unity3D?
I've downloaded an FBX animation of someone walking from the "Walking" section here.

I imported that and also a humanoid character and specified the Rig for both as Humanoid (auto-create).

The original animation has very solid foot placement, but whenever I apply it to any character in Unity the feet slide around as if it were walking on ice.

Here is a video demonstrating my issue. Is there something about the way I am getting Unity to auto-rig my character that would cause this problem? It happens no matter which 3D character I use.

Thanks

# Answer
Open the Animator window for your controller, click the animation in question, tick "Foot IK" in the animation
> 1 votes

---
Tags: unity, skeletal-animation, rigging
---


# Question
Title: Unity - 3D Sound sounds weird if audio listener is moving fast
If you place 3D Sound which is set to logarithmic falloff and move very fast, then it sounds extremly weird and plays way faster than normal. How can I prevent this?

I made a short video: https://www.youtube.com/watch?v=-bZJ7YS775E&feature=youtu.be

# Answer
> 6 votes
I found the reason for this. It is a setting called `Doppler Level`. After setting it to `0` it sounds normal even if the audio listener is moving very fast.

---
Tags: unity, sound
---


title: Why doesn't my simple HLSL shader work?

text:
# Question
Title: Why doesn't my simple HLSL shader work?
I'm using Monogame to draw 2D primitives to the screen. To do that, rather than use included structures like `VertexPositionColor`, I wrote my own vertex class for 2D.

```
public struct VertexColor : IPositionable, IVertexType
{
    private static readonly VertexDeclaration Declaration = new VertexDeclaration
    (
        new VertexElement(0, VertexElementFormat.Vector2, VertexElementUsage.Position, 0),
        new VertexElement(8, VertexElementFormat.Color, VertexElementUsage.Color, 0)
    );

    public VertexColor(Vector2 position, Color color)
    {
        Position = position;
        Color = color;
    }

    public Vector2 Position { get; set; }
    public Color Color { get; set; }
    public VertexDeclaration VertexDeclaration => Declaration;
}

```

Here's my associated HLSL shader, meant to simply translate vertices from normalized space to screen space.

```
#define VShaderModel vs_4_0_level_9_1
#define PShaderModel ps_4_0_level_9_1

matrix Projection;

struct VertexShaderInput
{
    float4 Position : SV_Position0;
    float4 Color : Color0;
};

struct VertexShaderOutput
{
    float4 Position : SV_Position0;
    float4 Color : Color0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output = (VertexShaderOutput)0;

    output.Position = mul(input.Position, Projection);
    output.Color = input.Color;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : Color
{
    return input.Color;
}

technique Technique0
{
    pass Pass0
    {
        VertexShader = compile VShaderModel VertexShaderFunction();
        PixelShader = compile PShaderModel PixelShaderFunction();
    }
};

```

Where `Projection` is an orthographic matrix computed in code and passed to the shader based on current window size. However, when I attempt to draw primitives, I receive the following exception:

`An error occurred while preparing to draw. This is probably because the current vertex declaration does not include all the elements required by the current vertex shader. The current vertex declaration includes these elements: SV_Position0, COLOR0.`

Now, I'm familiar with this exception and I understand what it means. The exception is telling me that my shader does not include all required elements based on the current vertex declaration. However, as you can see, my shader **does** include those two elements (`SV_Position0` and `Color0`).

What am I missing here?

# Answer
> 1 votes
I actually solved this problem in a way I didn't expect. Before, I had been starting my `SpriteBatch` and passing in the HLSL effect shown above, then attempting to draw primitives using `GraphicsDevice`. That was a mistake, and simply applying the effect before drawing primitives (without starting `SpriteBatch`) fixed the problem.

To emphasize: **I changed nothing** about my shader or the vertex class. Apparently the interaction with `SpriteBatch` was causing problems. I'll mark this as accepted (since it did fix the problem), but thank you to everyone who answered.

# Answer
> 2 votes
I'm not an expert on semantics (I usually work from templates that have everything I need), so I may be barking up the wrong tree...

But I notice that, for instance, Unity's unlit shader defaults to using the `POSITION` semantic for vertex input:

```
struct appdata
{
    float4 vertex : POSITION;
    float2 uv : TEXCOORD0;
};

```

And `SV_POSITION` for vertex output / interpolator & fragment input:

```
struct v2f
{
    float2 uv : TEXCOORD0;
    UNITY_FOG_COORDS(1)
    float4 vertex : SV_POSITION;
};

```

And switching the former from `POSITION` to `SV_Position` prevents the shader from compiling.

Microsoft's documentation for the `SV_Position` semantic says:

> When used in a shader, SV\_Position describes the pixel location.

While the `POSITION[n]` semantic is defined as "Vertex position in object space."

So this suggests to me that the `SV_Position` semantic is reserved for post-projection coordinates, and this is recognized as a different information channel than object space vertex positions. So this input in your shader fails to match your vertex declaration's `VertexElementFormat.Vector2, VertexElementUsage.Position` and is treated as a third stream of information that's missing from the vertex buffer provided, leading to the error.

If this is correct, changing `VertexShaderInput` to use `POSITION0` instead of `SV_Position0` should resolve the issue.

---
Tags: shaders, monogame, hlsl
---


# Question
Title: Create borders and clickable areas from image
Crusader Kings, Europa Universalis and several other strategy games use provice based maps where "tiles" are not squares nor hexagons. Border style indicates different ranks/owner.

---

I've done some research and this is what I found from modding guides: they seem to use a source image to dynamically generate the borders which are used to separate the provices but also to indicate currently selected areas (border changes color or flashes *etc*) and Im pretty sure that same file is used for "clickable areas" (click on provice to get province details screen).

Source image contains all the provinces painted with solid colors. This image is same size as height map (water bodies and land masses) to align geographical shapes with provinces.

Then there's some sort of dictionary file (text, JSON *etc*) that has all the province colors that maps these colors to meta data about the province. It also makes provinces "loopable" for game engine in order to add them to in-game database and to use colors to find the correct shapes from image.

Example in JSON:

```
// "key" is RGB color that points to correct province in previous image
"253:28:37": {
  "name": "Kent",
  "otherStuff": 13
},
"142:133:150": {
  "name": "Oxford",
  "otherStuff": 54
}

```

---

How to create referenceable borders and clickable areas from source image?

# Answer
> 2 votes
What I would suggest is reading the provincemap pixel-by-pixel, and matching the color values (use Color32 for simplicity) you get from the pixels with the color values defined in the JSON file. That way, each province has a list of pixels (tiles) that it controls.

At this point, when clicking on the map, if you use raycasting you can figure out the tile coordinates, and thus find out which province has been clicked.

As for the borders, I do belive LineRenderers (or some optimized form of it) is the way to go for borders. If you actually look closely in the reference image you posted, (for example, where The Solent, Winchester, and Dorset meet) you can see that the borders don't match up perfectly, leaving these jagged edges, which is typical for linerenderers.

To achieve this, some semi-mad algorithms have to be run. If you take every "tile" in the memory and ask if their neighbouring tiles belong to the same province, you can figure out which tiles are "border tiles". You can also keep track of which province they are bordering with, which is useful if you want different styles of borders later on.

Once you have the border tiles, you basically have the points you need to input into the linerenderer. You want to sort the points clockwise/counter clockwise first though, but that's another issue.

At this point you have one big "chain" of points, that create a line around the whole province. You could split the chain up into smaller parts (one part per neighbouring province) if you want thinner/fatter border types for different province neighbours. If you treat the ocean as a province, your border mesh should match up with the coastline aswell.

If you're using 3D terrain, you also probably want to offet the Y value of the line points to reflect the height of the terrain. That could be done by raycasting or just reading straight from the heightmap.

This should take you 90% there. The rest really depends on what kind of terrain you're using. At first you're gonna get blocky (and possibly unaligned) borders, just becuase of how you straight up converted a 2D tile pos to a 3D world pos. But by using some fancy spline curves you could probably get a decent looking result. Furthermore, you might wanna consider "sharing" border meshes between provinces, for the sake of optimization and general prettyness.

# Answer
> 0 votes
Here is how I would do it:

You will need two textures, one with your "real" world, and an other one, where each country is represented by one color (the image you provided is perfect). The latter texture must be marked as "Read/Write" in the Importer options.

Then, create a script and find the country according to the color you are hovering / clicking:

```
private Camera cam;

void Start()
{
    cam = Camera.main;
}

void Update()
{
    RaycastHit hit;
    if (!Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
        return;

    Renderer rend = hit.transform.GetComponent<Renderer>();
    MeshCollider meshCollider = hit.collider as MeshCollider;

    if (rend == null || rend.sharedMaterial == null || rend.sharedMaterial.mainTexture == null || meshCollider == null)
        return;

    Texture2D tex = rend.material.mainTexture as Texture2D;
    Color countryColor = tex.GetPixel(hit.textureCoord * tex.width, pixelUV.y * tex.height);

    // Then, find the country based on the color.
    // You can use ColorUtility.TryParseHtmlString if you want to store an hexadecimal representation of your color in your data file (JSON / Database)
    // https://docs.unity3d.com/ScriptReference/ColorUtility.TryParseHtmlString.html

   // Highlight the real texture with a custom shader
   // This shader would take two textures : the displayed one and the colored one, and a color
   // The color would help you highlight the correct texel. Something like :
   /*
         fixed4 frag (v2f i):SV_Target{
             fixed4 mainCol=tex2D(_MainTex,i.uv);
             fixed4 countryCol=tex2D(_ColoredTex,i.uv);
             // if( countryCol == _HighlightCol )
             //    Make mainCol brighter
             return mainCol;
         }
   */
}

```

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


# Question
Title: What is the difference between body transform and root transform
I am learning about **Root** animation and here come two terms, one is **root transform** and **Body transform**. As name suggests that body transform is the character body but what is root transform? and what is the **Root transform rotation** based upon *body orientation*, *Feet*, *center of mass* or *original*.

# Answer
> 1 votes
Taken from the link you've provided:

> The Body Transform is the mass center of the character.

So, when you animate a character slipping and falling to the ground, if you don't modify their Body Transform and only change the Root Transform, the animation will be played and the character will fall on the ground. The problem is, the body's center of mass is a feet or two above its body now, and if it interacts with and other physics object, it will act as if it's body mass is in the air.

Let's keep going in this example, your character is on the ground, but it's center of mass is still in the same place:

Now, in this situation, the car will still hit the body, and the body will still react, but it will spin around its center of mass, because of the force applied on it:

Now, we should see the body spin around its center of mass. I haven't tried this exact scenario, but it should be how it works. Just try it out in Unity (I will do the same and update the answer with results as soon as possible).

---
Tags: unity, c#, animation, mecanim
---


# Question
Title: How can you detect object/s using raycast from mouse cursor?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraRaycast : MonoBehaviour
{
    public Camera cam;

    void Start()
    {

    }

    void Update()
    {
        Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 1000))
            if (hit.transform.tag == "Interactable")
            {
                print("I'm looking at " + hit.transform.name);
            }
            else
                print("I'm looking at nothing!");
    }
}

```

This is working fine but this send raycast hit from the camera. I want to send the raycast from the mouse cursor so if the mouse cursor is moving over object it will detect it. Just instead the camera the mouse cursor.

# Answer
You could use `Camera.ScreenToViewportPoint` https://docs.unity3d.com/ScriptReference/Camera.ScreenToViewportPoint.html

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
   void Update() {
       transform.position = Camera.main.ScreenToViewportPoint(Input.mousePosition);
   }
}

```

I could change your code as this.

```
void Update()
{
    Ray ray = cam.ViewportPointToRay(cam.ScreenToViewportPoint(Input.mousePosition));
    RaycastHit hit;
    ...
}

```
> 2 votes

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


# Question
Title: How are photorealistic models' textures created?
I've been learning Blender and have made some decent progress. I've made some neat models, but so far, they haven't been textured. I understand how to unwrap a model so as to get the UV coordinates, but how do I actually create a texture to fit this coordinates? I've looked around and so far, it seems like a lot of people spend time hand-painting their models. Then I look at games like Counterstrike: Source, Call of Duty, etc., and I'm wondering how their models look photorealistic. It's all a bit of a mystery to me, but I'm hoping somebody could clarify. So, how exactly are photorealistic models created?

# Answer
> 6 votes
I can picture three common routes for creating a photo-realistic texture. Either:

1. You're a talented artist who can paint photo-realism and has no problem making it from scratch.
2. You use a camera to take a photo of a surface that looks similar to what you need.
3. You have enough artistic skills to start from a photo and modify it.

But that's concerning *textures only*.

As for the factors that contribute most to the *overall* photo-realistic look of a scene - besides having great assets - I'd boil it down to **lighting** and **detail** (links for reference, not as definition, but worth reading).

# Answer
> 1 votes
Game makers use something called bump mapping and normal mapping.. You can create those in a program called awesome bump, and then add some ambience and occlusion. It helps if you darken your areas in your texturing. In blender, you can now use nodes in cycles render to create edge wear with a new feature in the geometry node called pointiness.. This is to be used with color ramps, two or more then input the color into the factor of a mix shader, you can then use glossy and diffuse / PBR shaders, your choice :)

# Answer
> 0 votes
textures are just a layer drawn on top of the object. which is technically called `texture map`. most games usually use other maps such as `normal map`, `bump map`, `reflection map`, ... which makes objects rendering more realistic. and there are some applications like ZBrush which allow user to paint over 3D objects instead of working on a 2D texture.

# Answer
> -2 votes
There are only two ways to create textures:

1. Use a high quality camera to take high resolution images of the textured object in the real world.
2. Use Photoshop to combine different images found online to make a texture.

---
Tags: 3d, models
---


title: Unity2D Isometric layering

text:
# Question
Title: Unity2D Isometric layering
I'm developing an Isometric Game but I have problem apply the right layer for make, for example, a wall behind or in front of the Player depending on the Player position.

I'm able of getting works in an orthogonal map relating the y-axis value of an object with his layer but in an isometric map, the y-axis is not aligned with the editor one.

Anyone can help me understand how to manage this?

# Answer
> 0 votes
One solution is to build your world in 3D, then set the specific camera angle you want to look down on the level (isometric or any flavour thereof), and set the camera angle to orthographic.

# Answer
> 1 votes
There are two methods that can work.

**Method I**

1. Go To Graphics Settings
> Edit \> Project Settings \> Graphics
2. Under Camera Settings Change *Transparency Sort Mode* from *default* to *Custom Axis*.
3. Now Change *Transparency Sort Axis* Z value to 0 and Y value to 1.
4. Now it will take care of you Sprite Renderer's layering (according to Y axis value).
5. You can also use Sorting Group Component to group multiple sprites to together.

**Method II**

1. You can define multiple sorting layers in unity e.g. player, walls, tile map etc.
> Edit \> Project Settings \> Tags & Layers
2. Inspector you can find Sorting Layers Menu
3. You can find your defined sorting layers in each Sprite Renders Component or in case you are using UGUI Canvas component.
4. If you are using Tile Map Make you on grid and change you sorting order of player according to grid cell index.
5. You can define any function to calculate your sorting index.

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


# Question
Title: How to make text appear when standing over a box collider?
So I have a box collider and I want it so when im standing over it, it shows text. Like telling you what button to press to enter. How do I do that?

# Answer
> 1 votes
You Can use OnTriggerEnter2D. For Example

```
public class TrigerArea : MonoBehaviour {
    public Text bubbleMessageText;
    void OnTriggerEnter2D(Collider2D other) {
        bubbleMessageText.text = "ENTER YOU MESSAGE HERE";
    }
}

```

---
Tags: unity, c#, 2d
---


# Question
Title: Is there a method to add partial scorch marks or decals on top of existing sprites?
Let's say what I have is a planet like so:

What I want to do is to add a scorch mark like this:

Now, if this was a one time thing, it wouldn't be a problem. I'd make a sprite for this specific occasion and move on. The problem is however, I want the scorch marks to look different and to not use all that much memory (because there might be too many of them on screen and this is for mobile).

The scorch marks will almost always be the same size but the planets will be different sizes, so one sprite that is scaled is not what I want (it would look too big on bigger planets and too small on smaller ones). Also, I want to be able to rotate the sprite to make it look different.

I've thought about adding another sprite on top of the planet (a border-like hack) to hide this but there can be other planets that are really close by to this one and they would be hidden too.

I've looked at a lot of stuff but nothing like this exists.

I've managed to create some stuff with a stencil shader and the use of a sphere with zero Z scale. This does create the problem of showing the sprite on other planets and I haven't been able to push forward on this.

This is what I can currently make:

This is what I need to make:

# Answer
IMO You can use Alpha Blending for this. After reading your planet texture and the spot texture alpha blend them, you can find multiple script for alpha blending.for example : You can read texture of any image using Sprite.texture.

```
 public RawImage ResultantImage;
 public Texture2D planetTexture, spotTexture; // you can get these from Image or make it public and assign in inspector.

 public void Merge(){

        Texture2D resultantTexture = new Texture2D(texWidth,texHeight, TextureFormat.RGBA32, false);
        resultantTexture.SetPixels (AlphaBlend(planetTexture,spotTexture).GetPixels());
        resultantTexture.Apply ();
        ResultantImage.texture =  resultantTexture; // to show resultant image or replace with existing image
 }

 public  Texture2D AlphaBlend(Texture2D aBottom, Texture2D aTop)
    {
        if (aBottom.width != aTop.width || aBottom.height != aTop.height)
            throw new System.InvalidOperationException("AlphaBlend only works with two equal sized images");
        var bData = aBottom.GetPixels();
        var tData = aTop.GetPixels();
        int count = tData.Length;
        var rData = new Color[count];
        for(int i = 0; i < count; i++)
        {
            Color B = bData[i];
            Color T = tData[i];
            float srcF = T.a;
            float destF = 1f - T.a;
            float alpha = srcF + destF * B.a;
            Color R = (T * srcF + B * B.a * destF)/alpha;
            R.a = alpha;
            rData[i] = R;
        }
        var res = new Texture2D(aTop.width, aTop.height);
        res.SetPixels(rData);
        res.Apply();
        return res;
    }

```

This code isn't tested. You can use this idea to move forward.
> -1 votes

---
Tags: unity, c#, 2d, rendering, sprites
---


# Question
Title: Unity launches both Visual Studio and Monodevelop simultaneously
When I open a script for editing from Unity, both Visual Studio and Monodevelop are launched, resulting in two instances of the same solution to be open in two different script editors.

I am presently running the latest version of Unity 5.50fs (though I also experienced this issue in the previous build prior to installing Unity's latest update), in conjunction with Visual Studio Community Edition 2015, and Visual Studio Tools For Unity 2.3.0.

I also have my external script editor set to VS in the preferences window of Unity.

While investigating this issue I came across a forum thread of someone experiencing a similar problem, where MD opens *instead* of VS. This seemed to be a result of a hard coded reference to MD for redundancy in cases where VS might fail to load, which I thought sounds like a plausible explanation for my situation as well.

The general consensus was that when VS takes a little too long to open, Unity reverts to MD under the assumption that their is a problem with VS. This explanation seems even more likely in my case because this issue only occurs when I first open Unity for the day- if I have had VS open recently MD does not open, and VS opens quite quickly, likely a result of being cached in my computers memory.

The work around offered to avoid MD launching instead of VS in that thread, was to change the name of the MD executable, so that Unity would be unable to launch MD, giving VS time to finish loading. I was however hoping to find a better solution. I like the fact that Unity has that redundancy in place and would rather keep it intact, and I don't know why but changing the executable solely for that purpose makes me feel a little OCD.

Other ideas I have tried include reinstalling Unity, running both Unity and VS as an administrator, and launching VS prior to opening the script in Unity (in this case Unity opens a second instance of VS).

Has anybody else experienced both script editors being launched simultaneously and/or have any other ideas on how to resolve it? It's obviously not a critical issue or anything, but it is a bit annoying.

# Answer
You may have them both selected somehow in your preferences so definitely check there first again. It is under

> Edit -\> Preferences -\> External Tools -\> External Script Editor
>
> Set to MonoDevelop or Browse.

If they both aren't set and it's still trying to open both, other solutions include opening up VS while you are working so that it isn't taking longer to load which you are saying leads to MD opening instead. Another solution would be reinstalling Unity because sometimes it gets messed up if VS is installed after Unity. Here are some places you can try for more information. Unity Answers & Unity Forums
> 2 votes

# Answer
I suggest a simple solution: rename MonoDevelop.exe to MonoDevelop.exe.stop

have fun.
> -1 votes

---
Tags: unity, visual-studio, monodevelop
---


# Question
Title: 2D procedural veins/cumps of weighted ores/rocks
I'm evaluating methods for generating "clumps" or "veins" of rocks in a 2D top-down procedural game. Obviously the most common suggestion is to use various types of *noise*, but I feel like noise (alone) won't achieve what I'm after.

I've used a combination of voronoi and perlin noise because it's easier to generate "regions" of different noise. I can more easily turn these areas into "veins" of rocks or something than I could be using a "heightmap" alone - heightmaps tend to be more swirly/cloud-like.

With a high threshold and some rounding, I can turn this into a mask that works well for veins:

Changing the spacing and scale is as simple as toying with the math/threshold.

The difficulty lies with choosing which "rock" (or "ore") will fill each vein. Primarily, this is thanks to the fact that my rocks are weighted. Veins of rare rocks should not be common.

I currently map the original voronoi cell value to a specific rock, which forces each vein to be a single type, but can't be weighted. As you can see in picture #1, there's a fairly even distribution of each shaded area.

So either, I need a new way to choose a weighted random rock type for each vein, or I need a new way to place veins.

Minecraft is a good well-known example of what I need, except I work in 2D:

* Regularly distributed ore veins
* Veins of common ores are found more often and are typically larger veins
* Veins of rare ores are harder to find, and are smaller in size

Noise alone just can't seem to produce these values. What else can I try?

# Answer
Once you've identified a particular voronoi cell that should be a vein, take the coordinates of its generating point and pump them into a hash function. Interpret the result as a number between 0 and 1, and use it to look up into a probability table of your ore types.

This way you can control the probability of each ore type completely independently from the number, size, & distribution of your veins.

You can even pick out these ore types early in the process - when you've seeded your points but not yet generated the voronoi regions from them - and use the ore type to decide on a distance scaler to apply when comparing points against this seed. That way you can make some ores naturally occur in fatter or smaller veins, or even make some ores more narrow and wispy if you use a non-isotropic scale.
> 2 votes

# Answer
What if you try this:

* Adjust your threshold and rounding logic to increase the number of "levels" or "colors" in your output noise-image
* Instead of one level/color representing one type of rock, assign multiple levels to one type of rock

If you control the "amount" of levels going to each type of rock, does it help give the control you need?
> 1 votes

# Answer
Seeing other answers I'll suggest a little different approach. This will work better if you want have an ability to make the veins (material in them) more (or arbitrarily) dense.

1. Determine an origin of a vein node (by hash of a position being above a threshold for example, just like you generate random numbers but it has have hash semantics, you can vary generation density here). If you have a chunk based generation process then you can sample points uniformly in a chunk (number of points using for example a poisson distribution).
2. Generate a pseudo-random polygon and rasterize it (for small veins you can do a brute with an algorithm to check polygon-point intersection). Before generation you can choose the vein type and parameters for it's appearence.

2.1. When rasterizing you can vary density with noise/hashing function for example.

Note that this method may generate overlapping veins, which may not be desired.

The way you generate a polygon is first you determine number of vertices, and radius (you can do it however you want). Then put the vertices on the circle boundary (I found best results with uniformly distributed points, constant spacings work well too). Then for each point sample a corresponding noise value in range \<-1, 1\> (it doesn't have to be strictly that place, the only requirement is that the sampled points create a closed curve) and displace them perpendicularly to the circle boundary by a contiuous function (of your choice) of that sampled value. You are free to choose whatever function you want (you have to choose it empirically. Linear scaling will gives ok results), as long as it is continuous.

If you want to get fancier you can distribute the points in a different way, and change a displacing function to be aware of the angle of the point being displaced (so you could hold circle origin for example) to achieve other, not necesserly round shapes. For example lines of ore.

Even if you have a world that can dynamically expand you can use this method. Say your max vein size is R. Then you have to check if in radius R (outside of the part being generated) there is a vein generated and if there is then generate it for the part of the world that is actually there (generation is based on noise/hash so you get persistent results for duplicated generation, therefore you don't have to worry about it). If your world is chunk based then while generating a chunk you can just generate veins from neighbouring chunks (but save only region you're generating, the rest is discarded).
> 0 votes

---
Tags: unity, c#, procedural-generation
---


title: show hide button in unity using c#

text:
# Question
Title: show hide button in unity using c#
I have 15 buttons on my screen at onClick event am fetching the button and hiding that button using

```
EventSystem.current.currentSelectedGameObject.SetActive(false);

```

now at the end i have to show buttons again so i am using

```
for (int i = 0; i < 15; i++)
 {
     tag1 = "Button" + (i + 1);
     GameObject.FindGameObjectWithTag(tag1).SetActive(true);
     Debug.Log("done");
 }

```

Loop is giving error becuase it is not able to find object which has been hidden or setActive(false) from other references unity forum i see same solution but i don't know why it is not working in my case

> i know issue is with "FindGameObjectWithTag" function i will have to replace it with some other

any help will be appreciated
Thanks

# Answer
> 1 votes
You can try this.

```
// in void Start
objs = GameObject.FindGameObjectsWithTag (tag);

// void Update()
foreach (GameObject objs in obj) {
    obj.SetActive(true);
}

```

# Answer
> 1 votes
`Find` operation are costly operations: try to avoid them.

Make a public `List` and assign your buttons to that `List` and then iterate the `List`.

```
   public List<GameObject> allButton; // it will show in your inspector assign (Drag and
                                      // Drop) all your buttons to this list.

   public void ShowAllButtons(){

      for(int index=0; index < allButton.Count; index++ ){
         allButton..SetActive(true);
      }

   }

```

---
Tags: unity, c#, 2d
---


# Question
Title: Game Object will NOT stretch across entire content area
I'm loading prefabs into a content area using a content size fitter and vertical layout group. I've tried multiple things to get the loaded prefabs to stretch across the entire content size (including the Unity Manual for this issue), but I'm at an impass. I'll post a screenshot below to show what I'm working with:

Here's how I'm loading in the prefabs in case this is where i'm screwing up:

```
void CreateRaceSelect() {

 for (int i = 0; i < races.races.Count; i++) {
     raceButton = (GameObject)Instantiate(raceButtonPrefab);
     raceText = raceButton.transform.FindChild("Text").GetComponent<Text>();

     raceButton.name = i.ToString();
     raceButton.transform.SetParent(content.transform);
     raceButton.GetComponent<RectTransform>().localPosition = new Vector3(xPos, yPos, 0);
     raceText.text = races.races[i].ToString();
     yPos -= (int)raceButton.GetComponent<RectTransform>().rect.height;
    }
 }

```

I'm sure this is a minor screw up but at this point I have no other ideas.

# Answer
Check the Child Force Expand Width/Height According to your requirement.And set value of spacing in vertical layout component to zero instead of -6. I guess this will solve your issue.
> 1 votes

---
Tags: unity, c#, 2d, gui, ui-design
---


# Question
Title: How can I draw a line of the raycast hit in game view while the game is running?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraRaycast : MonoBehaviour
{
    public Camera cam;

    public LineRenderer laserLineRenderer;
    public float laserWidth = 0.1f;
    public float laserMaxLength = 5f;

    void Start()
    {
        Vector3[] initLaserPositions = new Vector3[2] { Vector3.zero, Vector3.zero };
        laserLineRenderer.SetPositions(initLaserPositions);
        laserLineRenderer.startWidth = laserWidth;
        laserLineRenderer.endWidth = laserWidth;
    }

    void Update()
    {
        Ray ray = cam.ViewportPointToRay(cam.ScreenToViewportPoint(Input.mousePosition));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 100))
            if (hit.transform.tag == "Interactable")
            {
                //print("I'm looking at " + hit.transform.name);
                laserLineRenderer.enabled = true;

                laserLineRenderer.SetPosition(0, ray.direction);
                laserLineRenderer.SetPosition(1, hit.transform.position);
            }
            else
            {
                //print("I'm looking at nothing!");
                laserLineRenderer.enabled = false;
            }
    }
}

```

When it detect a "Interactable" object i want it to draw green line from the mouse cursor to the point where the raycast is hitting.

Now it's not drawing anything.

# Answer
1. Create a Render Texture or Image.
2. Take hit points from raycast and change the pixels of Image/Render Texture using Texture2D.SetPixel
3. To make line visible you can change pixels around the hit point. It will be line width functionality (Commonly used brush size).
4. You can use GL.Lines
5. You can use already available unity assets like Easy 2D Lines, Mobile Paint
> 1 votes

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


title: How to make a sprite blink with Libgdx?

text:
# Question
Title: How to make a sprite blink with Libgdx?
I want to make a sprite blinking like this:

```
float alpha = .0f;

public void draw(SpriteBatch batch, float delta){
    alpha += delta;
    sprite.draw(batch, (float)Math.sin(alpha));
}

```

Well, it is blinking, but in a very irregular way. It should go from transparent to non-transparent to transparent and so on. But with that code it is more like non-transparent to transparent - then it almost instantly skips back to non-transparent and goes back to non-transparent.

How can I optimize this?

# Answer
> 2 votes
The blinking requires an alpha value that swings 0 and 1. The Sinus function swings between 1 and -1. So to solve the problem, the function has to be multiplied by 0.5 and be added to 0.5, so that the value swings between 0 and 1, like this:

```
sprite.draw(batch, +5f*(float)Math.sin(alpha) + .5f);

```

# Answer
> 0 votes
I have tried using 3 methods to create a blinking effect.

1. The value shifting from @purpule +5f\*(float)Math.sin(alpha) + .5f
2. My suggestion using Math.abs(Math.sin(alpha));
3. Alternate modulus method.

The Code used to test:

```
        long startTime = System.currentTimeMillis();
        System.out.println(startTime);
        for(int i = 0; i < 10000000; i++){
            float val = +5f*(float)Math.sin(i/1000) + 0.5f;
        }
        long endtime = System.currentTimeMillis();
        System.out.println("Total time:"+(endtime - startTime));

        startTime = System.currentTimeMillis();
        System.out.println(startTime);
        for(int i = 0; i < 10000000; i++){
            float val = (float) Math.abs(Math.sin(i/1000));
        }
        endtime = System.currentTimeMillis();
        System.out.println("Total time:"+(endtime - startTime));

        startTime = System.currentTimeMillis();
        System.out.println(startTime);
        for(int i = 1; i < 10000001; i++){
            float val = i%2;
            float alpha = val>1?1-(val-1):val;
        }
        endtime = System.currentTimeMillis();
        System.out.println("Total time:"+(endtime - startTime));

```

The outcome of the tests show that the first 2 methods take about 550-570ms and achive the same sinus wave alpha.

The 3rd method using module takes about 9-15ms which is a lot faster but is not a sine wave, instead it is a saw wave and still achieves the blinking affect.

I suggest you try these and see which one suits you needs the best.

---
Tags: java, libgdx, mathematics, trigonometry
---


title: Is the Windows 10 Game Bar extensible?

text:
# Question
Title: Is the Windows 10 Game Bar extensible?
Does the Windows 10 Game Bar have an an API that I, as a developer, can hook into and as such make a product that starts alongside all games that support the game bar (say, a parental control interface)?

# Answer
> make a product that starts alongside all games that support the game bar

If you try to the open the Game Bar on somehting Windows doesn't recognize as a game, Windows will ask you if it is a game and if you say yes, you get the Game Bar. From that point on, Windows will recognize that process as a Game.

How does Windows know that it is a game? It will match it against a list... Where is the list stored? You can find it at `%userprofile%\AppData\Local\Microsoft\GameDVR\KnownGameList.bin`. You can read more about how it works from Renaming a Win32 executable to main.exe launch the Xbox DVR popup by lucasg.

In the linked article the following 010 template is provided to parse the file - which hopefully it is useful to write the relevant code in whatever langauge you are using - (**note: this is a template for 010 Editor, I have not tested this**):

```
typedef struct  {
   BYTE Reserved[0x300];
}HEADER;

typedef struct  {
    WORD ByteLen;
    BYTE RawString[ByteLen];
    //local string sName=ReadWString(RawString);
} GAME_WSTR <read=ReadGame>;

typedef struct {
    DWORD Reserved;
    DWORD ByteLen;
    BYTE RawString[ByteLen] <fgcolor=cLtRed>;
} OPTION_STR  <read=ReadOption>;

typedef struct  {
   local int StartAddr = FTell();
   DWORD EntrySize;

   // Executable game name
   GAME_WSTR GameName <fgcolor=cLtBlue>;

   // Optional magic
   if (ReadUShort() == 0xca54)
        WORD OptReserved;

   // Optional structs based on switch values
   WORD AdditionalNamesCount;
   WORD SwitchOption2;

   // Additional names (probably like a hint).
   local int i =0;
   for (i = 0; i <  AdditionalNamesCount; i++){
        OPTION_STR Option;
        if (ReadUShort() == 0xca54)
            WORD OptReserved;
   }

   // Look for a magic
   local int Find20h = 0;
   while(!Find20h){
        Find20h = (0x20 == ReadByte());
        BYTE Res;
   }

   GAME_WSTR GameId;
   WORD Reserved;

   // Sometimes there is an additionnal name
   // sometimes not. I check the current entry
   // is less than the EntrySize declared.
   if (FTell()-StartAddr < EntrySize)
   {
       switch (SwitchOption2)
       {
       case 3:
            OPTION_STR Option3;
            break;
       case 2:

            OPTION_STR Option2;
       case 1:
            break;
       }
    }

} ENTRY <read=ReadGameName>;

string ReadOption(OPTION_STR &Game)
{
    local wstring GameName = L"";
    local int i ;
    for (i= 0; 2*i < Game.ByteLen; i++){
        WStrcat(GameName, Game.RawString[2*i]);
    }
    return WStringToString(GameName);
}

string ReadGame(GAME_WSTR &Game)
{
    local wstring GameName = L"";
    local int i ;
    for (i= 0; 2*i < Game.ByteLen; i++){
        WStrcat(GameName, Game.RawString[2*i]);
    }
    return WStringToString(GameName);
}

string ReadGameName(ENTRY &Entry)
{
    local string GameName = ReadGame(Entry.GameName);
    local string OptionGameName = "";
    if (Entry.AdditionalNamesCount)
        OptionGameName = " : "+ReadOption(Entry.Option);

    return GameName + OptionGameName;
}

//------------------------------------------
LittleEndian();
Printf("Parse KnownGameList.bin Begin.\n");
HEADER UnkwownHeader <bgcolor=cLtGray>;
while(1)
{
    ENTRY Entry <bgcolor=cLtPurple>;
    //Printf("Entry : %s -> %d.\n",ReadGameName(Entry) ,Entry.AdditionalNamesCount);
}
Printf("Parse KnownGameList.bin End.\n");

```

The article was based on lucasg's answer to Windows 10 : naming programs main.exe cause them to show pop up.

---

Or you can handle your own list. Perhaps keep a database in an online server that clients can download... or simply provide an UI where users can add items.

---

Ok, that is half the problem. Once you decide how you will define "all games that support the game bar", the next thing is to hook the process start. I suggest to get a notification of process start from Win32\_ProcessStartTrace, then see if the started process is in your list and open your UI or whatever it is you want to do next.
> 3 votes

# Answer
Just to preface, I have no experience with any windows API. However after a little googling I found this:

https://docs.microsoft.com/en-us/uwp/api/windows.gaming.ui.gamebar

Which the website makes out to be part of the API for Universal Windows Platform applications. It is probably worth noting that this is under Windows.gaming.UI and that looking around the API for the whole of Windows.gaming (as opposed to the UI only) may provide you with more exact information.

Hope this helps and good luck.
> 0 votes

---
Tags: windows
---


# Question
Title: How to get samsung gear vr controller rotation & position in unity
I am trying to get Samsung Gear VR(Oculus) rotation & position so when I turn the samsung controller left or right(like a magic wand)...it should give me rotation(Quaternion) & position(Vector3) readings?

How can I do that? I'm using Mobile version of Oculus Gear VR not the PC one. Also, `GetLocalControllerRotation()` returns void and doesn't return me a Quaternion

Does the controller come with a Gyroscope with the help of which I can the rotation or position readings?

# Answer
> 0 votes
There are two ways of doing it:

**1. Using OVRCameraRig:** it comes bundled with OVRManager and also transform components, here you can just place your mesh object into the RHandAnchor or LHandAnchor (depending on handedness) and rotational tracking will function as intended with no line of code needed.

**2. Manualy:** Here you should first place OVRManager Component in your scene, it is a singleton and required for tracking and also OVRInput class to function. Then you can set LocalPosition and LocalRotation of your wand object with

```
if (OVRInput.IsControllerConnected(OVRInput.Controller.RTrackedRemote))
            {
                wandObject.transform.rotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTrackedRemote);
                wandObject.transform.position = OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTrackedRemote);

            }

```

---
Tags: unity, oculus
---


# Question
Title: How to adapt pathfinding algorithms to restricted movement?
Imagine car-like movement where entities cannot turn on a dime. Say, for the sake of discussion, that when at-speed they can turn 90 degrees per second. This would in many cases change the optimal path and therefore the pathfinding. It may even make 'usual' paths entirely impossible to traverse.

Are there any pathfinding algorithms or movement planning algorithms that can keep this in mind, or are there simple ways to adapt the popular ones?

# Answer
Welcome to the wonderful world of non-holonomic motion planning. I recommend doing this using a lattice grid path planner. Other alternatives include the kinodynamic RRT, and trajectory optimization. Non-holonomic systems include cars, boats, unicycles, or really anything where the vehicle can't travel in any direction it wants. Planning for these systems is much harder than holonomic systems and until ~2000 was on the edge of academic research. Nowadays there are lots of algorithms to choose from which work decently.

Here's how it works.

**State**

Your car's configuration *q* is actually a 3D state containing the car's x, y position *and* its orientation *t*. The nodes in your A\* algorithm are actually 3D vectors.

```
class Node
{
    // The position and orientation of the car.
    float x, y, theta;
}

```

**Actions**

So what about the edges?

That's slightly harder, because your car could actually choose an *infinite* number of ways to turn the wheel. So, we can make this accessible to a lattice grid planner by restricting the number of actions the car can take to a discrete set, *A*. For the sake of simplicity lets assume that the car doesn't accelerate but rather can change its velocity instantaneously. In our case, *A* can be as follows:

```
class Action
{
    // The direction of the steering wheel.
    float wheelDirection;

    // The speed to go at in m/s.
    float speed;

    // The time that it takes to complete an action in seconds.
    float dt;
}

```

Now, we can create a discrete set of actions that the car can take at any time. For example, a hard right while pressing the gas at full for 0.5 seconds would look like this:

```
Action turnRight;
turnRight.speed = 1;
turnRight.wheelDirection = 1;
turnRight.dt = 0.5;

```

Putting the car into reverse and backing up would look like this:

```
Action reverse;
reverse.speed = -1;
reverse.wheelDirection = 0;
reverse.dt = 0.5;

```

And your list of actions would look like this:

```
List<Action> actions = { turnRight, turnLeft, goStraight, reverse ...}

```

You also need a way of defining how an action taken at a node results in a new node. This is called the *forward dynamics* of the system.

```
// These forward dynamics are for a dubin's car that can change its
// course instantaneously.
Node forwardIntegrate(Node start, Action action)
{
    // the speed of the car in theta, x and y.
    float thetaDot = action.wheelDirection * TURNING_RADIUS;

    // the discrete timestep in seconds that we integrate at.
    float timestep = 0.001;

    float x = start.x;
    float y = start.y;
    float theta = start.theta;

    // Discrete Euler integration over the length of the action.
    for (float t = 0; t < action.dt; t += timestep)
    {
       theta += timestep * thetaDot;
       float xDot = action.speed * cos(theta);
       float yDot = action.speed * sin(theta);
       x += timestep * xDot;
       y += timestep * yDot;
    }

    return Node(x, y, theta);
}

```

**Discrete Grid Cells**

Now, to construct the lattice grid, all we need to do is *hash* the states of the car into discrete grid cells. This turns them into discrete nodes that can be followed by A\*. This is super-important because otherwise A\* would have no way of knowing whether two car states are actually the same in order to compare them. By hashing to integer grid cell values, this becomes trivial.

```
GridCell hashNode(Node node)
{
    GridCell cell;
    cell.x = round(node.x / X_RESOLUTION);
    cell.y = round(node.y / Y_RESOLUTION);
    cell.theta = round(node.theta / THETA_RESOLUTION);
    return cell;
}

```

Now, we can do an A\* plan where GridCells are the nodes, Actions are the edges between nodes, and the Start and Goal are expressed in terms of GridCells. The Heuristic between two GridCells is the distance in x and y plus the angular distance in theta.

**Following the Path**

Now that we have a path in terms of GridCells and Actions between them, we can write a path follower for the car. Since the grid cells are discrete, the car would jump inbetween cells. So we will have to smooth out the motion of the car along the path. If your game is using a physics engine, this can be accomplished by writing a steering controller that tries to keep the car as close as possible to the path. Otherwise, you can animate the path using bezier curves or simply by averaging the nearest few points in the path.
> 10 votes

# Answer
Most path finding algorithms work on a arbitrary graph without restriction of geometry.

So what you need to do is add orientation of the car to each explored node and restrict which nodes are actually connected.
> 4 votes

# Answer
My thoughts, havent tested them!

1. Run A\* from start to destination, return the path.
2. Loop through the path, when you detect a turn, use a bezier algorithm (or any like it) which uses the seekers current speed to predict the nodes that will create a smooth turn. Make sure it tries to go back to the closest path-node.
3. If the turn can be done, great, if not, repeat with slower speed, making for a sharper turn.
4. Once the correct path is created, go back through the path adjusting the speed of the seeker before the turn is made so it slows down to the correct speed before it initiates the turn.
5. If the turn cannot be made at all, run the whole thing again. Just ensure all the handled nodes of the turn that cannot be made are in the closed list, so they are ignored. And you could start with the point where the turn is initiated so you can skip the succesfull part of the path, however, in some cases this could possibly result in a less than optimal path.

You should also be able to do this without having to complete the path first, ergo: handling turns during A\*, which will probably be much better optimized, but it might also prove to be problematic and glitchy, i really wouldnt know and unfortunatly i dont have the time to test it myself.
> 1 votes

# Answer
If your agent has full control of the car, do it the other way around. Connect a line from start to finish first, then figure out at what speed you can navigate each turn, similar to Dennis's answer.

Don't draw Bezier curves from fixed points though. To minimize speed loss you need to move the entire line around, so start by inserting extra nodes at more or less even distance and then move then for energy minimization or similar strategies. For details you need to look into AI line generation in (preferably sim or semi-sim) racing games.

Once you have the AI line system running, run your A\* search and for each path go at least one corner forward, then calculate the AI line which gives you a time estimation. This would be your cost function.
> 0 votes

---
Tags: path-finding, car
---