title: How to create a character selection?

text:
# Question
Title: How to create a character selection?
I'm creating a spaceshooter clone and I like to achieve the following.

In the menu the player can choose between 3+ ships(characters). When the player hits the "Start Game" Button the game starts in a different scene and is flying the selected ship.

Therefore I have done the following:

I have 2 scenes. "MainMenu" and "Game". In "MainMenu" I have a few buttons and a GameControl Object. The GameControl object will not be destroyed on load. I followed this tutorial to have this.

```
    using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class GameControl : MonoBehaviour
{

    public static GameControl instance;
    public static int WIDTH = 800;
    public static int HEIGHT = 600;
    public static bool FULLSCREEN = true;
    public static int REFRESHRATE = 60;

    public GameObject playerShip;

    public float health;
    public float experience;
    public float score;

    void Awake()
    {
        if (instance == null)
        {
            Screen.SetResolution(WIDTH, HEIGHT, FULLSCREEN, REFRESHRATE);
            DontDestroyOnLoad(gameObject);
            instance = this;
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    void OnGUI()
    {
        GUI.Label(new Rect(10, 10, 100, 30), "Health: " + health);
        GUI.Label(new Rect(10, 40, 100, 30), "XP: " + experience);
        GUI.Label(new Rect(10, 70, 100, 30), "Score: " + score);
    }

    // Use this for initialization
    void Start()
    {

    }
    // Update is called once per frame
    void Update()
    {

    }

    public void loadScene(string sceneName)
    {
        SceneManager.LoadScene(sceneName);
    }

    public void quitGame()
    {
        Application.Quit();
    }

    public void setShip(GameObject ship)
    {
        Destroy(playerShip);
        playerShip = Instantiate<GameObject>(ship);
        playerShip.SetActive(false);
    }
}

```

I also followed this tutorial about character selection. But in the video it is done a little bit different than I need it. All my ships are prefabs like it is done in the tutorial. So in "MainMenu" I have a ShipSelection that looks like that:

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

public class ShipSelection : MonoBehaviour {

    private int selectionIndex = 0;

    public List<GameObject> availableShips;

    // Use this for initialization
    void Start () {
        availableShips = new List<GameObject>();
        foreach(Transform t in transform)
        {
            availableShips.Add(t.gameObject);
        }

        foreach(GameObject ship in availableShips)
        {
            ship.SetActive(false);
        }
        nextShip();
    }

    // Update is called once per frame
    void Update () {

    }

    void OnGUI()
    {
    }

public void nextShip()
{
    availableShips[selectionIndex].SetActive(false);
    selectionIndex++;

    if(selectionIndex >= availableShips.Count)
    {
        selectionIndex = 0;
    }
    availableShips[selectionIndex].SetActive(true);

    GameControl.instance.setShip(availableShips[selectionIndex]);
}

public void previousShip()
{
    availableShips[selectionIndex].SetActive(false);
    selectionIndex--;
    if(selectionIndex < 0)
    {
        selectionIndex = availableShips.Count - 1;
    }

    availableShips[selectionIndex].SetActive(true);

    GameControl.instance.setShip(availableShips[selectionIndex]);
}

```

}

I thought that when I call `GameControl.instance.setShip(availableShips[selectionIndex]);` I could pass an instance of the selected ship to the next scene. But when I change the scene the value is `null`. I think this is because the objects from the "MainMenu" are all destroyed and so is the reference to the selected ship...

**But how can I achieve to pass a "selected Ship" to the next or another scene, so that this scene knows which ship should be spawned/instantiated?**

If you need to look into the project you can find it at
github.com/Naxos84/SpaceShooterGame
If something is unclear please do not hesitate to request more information.

Apparently I don't have enough reputation to post more than 2 links. So sorry for the plain repo link.

**EDIT:** I found another tutorial on character selection.
youtube.com/watch?v=ERuxfU8ArqA
But this video is using all "player object" in the game scene too. Is this really the only way of doing a character selection? Or is there an even better way?

# Answer
To create prefabs, take the gameObject (the ship) and drag it to the project window and go.

in the game scene, inside the script that controls the load creates 3 variables publishes GameObject and you assign to each one, one of the prefabs ships.

```
public GameObject ship01;
public GameObject ship02;
public GameObject ship03;

```

In the Menu Scene, you save a reference of the chosen ship by the player, for example the name, you do something like:

```
PlayerPrefs.SetString ("ShipSelected", availableShips [selectionIndex] .name);

```

it will persist even if the game is closed.

Then in loading the game scene, you do something like:

```
string shipSelected = PlayerPrefs.GetString ("ShipSelected");

Swich (shipSelected)
{
case "Ship01":
playerShip = Instantiate (ship01);
break;
case "Ship02":
playerShip = Instantiate (ship02);
break;
case "Ship03":
playerShip = Instantiate (ship03);
break;
}

```
> 1 votes

---
Tags: unity, character
---


title: App Store Optimisation-Package Name

text:
# Question
Title: App Store Optimisation-Package Name
I have a game in play store and trying to get it to the upper places on the search engine. As I read, the package name should be similar to the game title. What is the effect of it in the searches?

I also made a lot of keyword research and added the relevant keywords to the title and description. Hovewer, I still can not see my game in a good place when I make a search.

What other things are necessary for my game to be at a better point in search results?

Thank you very much for your answers and suggestions.

# Answer
> 1 votes
Here's an official `Google` talk about getting discovered on `Play`.

As far as I know, the only thing with package name is that you get higher rankings in direct google searches (cause the package name becomes the game's URL address).

If you're trying to find best-suited keywords, app-names and trends, you should try AppAnnie, from this tutorial.

---
Tags: google-play, search
---


# Question
Title: Unity - Inaccurate rotation if object is rotated on two axis at once
I have an object which i want to rotate relative to world space. I have three variables (one for every axis) which store the rotation. By pressing buttons on my controller I add or subtract 90 to these variables (rotX, rotY, rotZ). Then I rotate my Object like this:

```
transform.Rotate (rotX * delta, rotY * delta, rotZ * delta, Space.World);

```

As this is called every frame the object would spin forever so i subtract the ammount I've allready rotated afterwards:

```
rotX -= rotX * delta;
rotY -= rotY * delta;
rotZ -= rotZ * delta;

```

This works fine as long as I don't rotate two axis at once. Then the object rotates rotates only partially to the desired position (e.g. 83 if I want to rotate to 90).

I can't see what I've done wrong. It actually seems like the moment I start an rotation around an axis all other axis get canceled. But if I monitor the variables they look exactly as they should.

Thank you in advance and have a amazing day!

# Answer
> 1 votes
Rotations don't work the same as translations. They're order-dependent and their axes are not globally orthogonal - a small rotation on one axis begins to affect the results of subsequent rotations, even when you're compounding rotations in world space (since the orientation of the object relative to the rotation axis changes). See this answer for some animated examples.

To fix this, it often works better to separate your destination from your current rotation. Then you can change your destination in discrete steps, while your current rotation plays catch-up at a controllable speed. As a bonus, this also makes it easier to introduce easing curves for a smoother/juicier feel. :)

```
// Measured in turns per second for ease of use.
public float rotationSpeed = 1f;

Quaternion _targetRotation = Quaternion.identity;

void Update() {
   if(Input.GetButtonDown("PitchPlus"))
     _targetRotation = Quaternion.Euler(90, 0, 0) * _targetRotation;
   if(Input.GetButtonDown("PitchMinus"))
     _targetRotation = Quaternion.Euler(-90, 0, 0) * _targetRotation;
   if(Input.GetButtonDown("YawPlus"))
     _targetRotation = Quaternion.Euler(0, 90, 0) * _targetRotation;
   if(Input.GetButtonDown("YawMinus"))
     _targetRotation = Quaternion.Euler(0, -90, 0) * _targetRotation;
   if(Input.GetButtonDown("RollPlus"))
     _targetRotation = Quaternion.Euler(0, 0, 90) * _targetRotation;
   if(Input.GetButtonDown("RollMinus"))
     _targetRotation = Quaternion.Euler(0, 0, -90) * _targetRotation;

   transform.rotation = Quaternion.RotateTowards(
                          transform.rotation,
                          _targetRotation,
                          rotationSpeed * 360f * Time.deltaTime);
}

```

This could hypothetically still accumulate small errors over many rotations due to floating point rounding (though with pure 90-degree rotations it should be OK as long as Unity's internal methods are numerically stable). If that turns out to be a problem, you can replace the `_targetRotation` with something like an orientation struct that models just the 24 orientations you care about.

---
Tags: unity, rotation, axis
---


# Question
Title: Using DirectX(SharpDX) what is the best way to create a single large image from smaller images?
I'm looking for the best way to combine several images (1060 x 1060)each into on large image. I'm looking to create one texture to apply to a single Quad. I was thinking multiple quads and then just use a Shader in 3D. However, I cannot seem to figure out how to get this to work correctly. I have 16 quads in a 4 x 4 arrangement. However, I can only see 4 of 16. I'm trying to get the 16 to fit like a single quad would without a camera.

# Answer
if your goal is to create a mega bitmap, why don't you do it programatically and write all of it into 1 target bitmap.

Create a 4 x 4 array, for each row, read each line and write them 1 after the other sequentially. Ala, texture 1, line 1, texture 2 line 1 etc. I think that will give you a more lossless version of the bitmap without any issues with seaming etc.

You are basically limited to the amount of physical memory on your pc (unless really silly size).

I assume these are bitmaps assume 32bit, you are only creating a 90MB file or so.

Ie, 1060 x 1060 is approx 4.5mb file
> 0 votes

---
Tags: c#, directx, sharpdx
---


# Question
Title: How can I split my terrain into quads so that each quad would have a renderable vertex/index buffer? (DirectX11, C++)
I am creating a quad tree to store my terrain in chunks and currently have the implementation working to an extent.

I am currently starting with a grid of triangle pairs that make squares and splitting this down into quads. I have my vertices split into quads, but I'm struggling with the indices.

**Here is how I generate the plane**

```
snip

```

This gives me one list of indices, and one list of vertices. This is taken by the quadtree and split into different vertex lists and stored in different nodes. This works fine and the vertices seem to be correct, however I'm not sure how to create the indices for each vertex list as before I was doing it based on the height and width of the whole terrain. How would I create an indices list for each node in the quadtree or is there a better way to do this?

If I just use the whole list of indices for each node, I get weird results

**Edit**: There is an issue generating my plane, I am fixing this and seeing if it resolves my problem.

**Edit**: I have edited the topic title to something more suitable.

I have fixed my issue with the grid generation and I am using a smaller grid to make the issues more clear. I am using a 2x2 grid (9 verts, 24 indices, 8 tris) which is split into 4 quads (4 verts per quad, 2 tris per quad) and it's almost working, just a small issue with one of the sides.

I know this is potentially duplicating verts on a small scale, but on a larger scale with culling, this should actually save performance. Can anyone spot what's going on? Vertex issue? When splitting the quads, should it be by triangle, vertices, or indices? What happens if we split by triangle and a triangle overlaps 2 quads (although this shouldn't happen)

# Answer
> 1 votes
As I have done what you are trying to do, ala quad tree and splitting into chunks. A couple of things.

For optimal performance, I have found that keep the vertex list as one buffer. Do your quadtree split on the indices. What this does is your indices dont have to be rebuilt and reflect the true index of the vertex in your mega buffer.

NOW, if you decide to split at a vertex level also, that is both index and vertex buffers per leaf in your quad, you will need to reindex.

This gets more complex if you dont have shared vertices at each grid point, but share the same vertex (that is, your neighboring quads share the same grid point), you will need to then split this up each time you split your node.

2nd Easiest way to go - and slowest.

Generate your grid with individual vertices per quad, that is 6 (3 per triangle).

Treat your vertices as triples, so when you do your quad tree subdivision you move the triples into the relevant node. Build your vertex list and then eliminate duplicate vertices sharing the same point and create your index list.

Easiest way I have found ...so far...

Build your Vertex list and associated index list.

Do your quad tree, reference the vertices via the index list (naturally), and split only the index buffer in triples (that is, split them on the central point of the triple). As this is a uniform grid, your triples should split evenly among your nodes.

From the screenshot, I am assuming you are splitting in your quadtree per vertex rather than per triple. My guess, please dont shoot me!

My game uses this -\> https://www.facebook.com/InsaneSoftware.com.au/

the game uses quad trees (not as efficiently with index buffers at the moment!) but you can see the quad tree in action by playing with the f1 - f3 keys if you feel like seeing what I did.

Enjoy.

---
Tags: directx11, terrain, quadtree, index-buffer
---


# Question
Title: Transformation movement by using Accelerometer data
Is It possible to make transformation movement by using Accelerometer data or Accel + Gyro ? as we know, we can make rotation by using Accel or Gyro data. However, how can we make transformation movement? I know this is still problematic and experimental. but there must be some ways to reach.

Is there any algorithm or math formula solving this problem?

# Answer
The accelerometer is very imprecise, in fact all of them are. That's the main reason you need to combine 3 or more sensors to get something that even remotely resembles the actual rotation.

The other big problem with the accelerometer is that it's in m/s², that means to get a position from this you'll need to first multiply it with the time difference to get the velocity, add that to the total velocity, then once again to get the position that you add to the total position. This means that even a small drift will mean multiple meters in a second.

For example, if the accelerometer outputs 0.1m/s² more, then it should and with 60fps you'll get a drift of around 3 meters in the position at the end.

If you need to measure large distances, then stick to the GPS instead.
> 1 votes

---
Tags: transformation, accelerometer, gyroscope
---


title: Shader Resource Binding

text:
# Question
Title: Shader Resource Binding
Im trying to set a constant buffer in my shader with a value. But getting nothing, no results.

Code in shader

```
cbuffer MatrixBuffer : register(b0)
{
    float4 test;
};

----------------------------------------------------------------
In main part

#pragma pack(push,1)
struct CB_GBUFFER_UNPACK
{
    D3DXVECTOR4 test;

};
#pragma pack(pop)

            D3D11_BUFFER_DESC cbDesc;
        ZeroMemory( &cbDesc, sizeof(cbDesc) );
        cbDesc.Usage = D3D11_USAGE_DYNAMIC;
        cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
        cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
        cbDesc.ByteWidth = sizeof( CB_GBUFFER_UNPACK );
        device->CreateBuffer( &cbDesc, NULL, &m_pGBufferUnpackCB  );

            D3D11_MAPPED_SUBRESOURCE MappedResource;
            ic->Map( m_pGBufferUnpackCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource  );
            CB_GBUFFER_UNPACK* pGBufferUnpackCB = ( CB_GBUFFER_UNPACK* )MappedResource.pData;

            pGBufferUnpackCB->test.x = 10.0f;
            pGBufferUnpackCB->test.y = 10.0f;
            pGBufferUnpackCB->test.z = 10.0f;
            pGBufferUnpackCB->test.w = 0.0f;

            ic->Unmap( m_pGBufferUnpackCB, 0 );
            ic->PSSetConstantBuffers( 0, 1, &m_pGBufferUnpackCB );

```

What seems to be my problem?

# Answer
> 1 votes
I think you want to set the Vertex Shader. But you write:

`ic->PSSetConstantBuffers( 0, 1, &m_pGBufferUnpackCB );`

It sets the PixelShader ("PSSetConstantBuffers"). Change "PS" to "VS" (VertexShader)

`ic->VSSetConstantBuffers( 0, 1, &m_pGBufferUnpackCB );`

---
Tags: shaders, directx11, hlsl
---


# Question
Title: Managing game progress - states, stages, or flags
I am creating an rpg. So far I've used a global game stage as well as individual npc stages (increased when completing a quest for example) to control the "stage" the game is in. I.e if I have a log blocking a road, If game stage is \> 10 then the log should not be there anymore.

This worked fine for basics but I want more control. And was considering a system with flags. For example a static class with booleans like "isLogRemoved", that I can use on top of stages to get more control. Plus it would be easy to save/load.

Before I make my own system along these lines I wanted to ask you more experienced people if there is a "proper" approach to this problem. Take a game like Zelda for example, where there are so many things that act differently depending on the stage (or state) of other objects in the world. Does anyone have a clue what a system like that looks like or how it works?

Hope I'm making sense. Having a hard time formulating this one.

# Answer
While I can't speak to any game specifically, my first instinct would be to approach this using a graph. It sounds like something you have started doing, by your use of "stages", though maybe only linearly.

For anyone unfamiliar with graphs as a mathematical and programming concept: https://en.wikipedia.org/wiki/Graph\_theory
https://en.wikipedia.org/wiki/Directed\_graph

Conceptually, each node in your graph could have a set of flags like you were thinking. And each edge is some condition of the current game state.

To use an example from Zelda Link to the Past, you're supposed to collect all three pendants before being able to carry on. And for each pendants you collect, it should no longer be shown on the map as a current objective.

So we have 4 nodes in our graph of this simplified example:

* A: New Game
* B: Has Pendant 1
* C: Has Pendant 2
* D: Has Pendant 3
* E: Has All 3 Pendants

Then we create our edges between the states, with the conditions for moving along that edge.

* A -\> B requires getting Pendant 1
* A -\> C requires getting Pendant 2
* A -\> D requires getting Pendant 3

---

* B -\> E requires getting All Pendant
* C -\> E requires getting All Pendant
* D -\> E requires getting All Pendant

So with this, we have a branching structure, allowing the player to get the pendants in any order. But they won't reach the final state E without getting all pendants.

Then we attach our flags to each state:

A:

* isPendant1Showing = true
* isPendant2Showing = true
* isPendant3Showing = true
* canProgress = false

B:

* isPendant1Showing = false

C:

* isPendant2Showing = false

D:

* isPendant3Showing = false

E:

* canProgress = true

To figure out then what state our game is:

* Start at A
* Set flags as they are in A
* Evaluate each connection
* If condition is true evaluate the connected node the same way, overwriting any flags

For save files then you just need to save the data that is relevant to the conditions for the edges.

For added complexity to a game, this method can be applied recursively or to individual elements of the game. The condition for an edge could be based on the result of another graph. Or the graph could exist per NPC, and the conditions are based only on the state of a specific NPC. Programming wise, I'd recommend that any graphs that are identical (same states, same conditions, same flags) exist once, and you simply pass the NPC to the graph to get a list of flags back.
> 3 votes

# Answer
When you just have one integer variable which tells you the current story progress, then you are limited to a completely linear story progression. There is no way to implement branching story routes, multiple objectives which can be completed in any order or optional sidequests.

If you don't need those, you can get away with just one stage-variable. But if you want any of that, then you will need multiple story flags.

One problem you might run into when you use story flags is that you might accidently run into situations where the player runs into a flag combination which doesn't allow them to progress at all. Or that you hide some content behind a flag combination which isn't actually possible to achieve anymore after you reorganized your story a few times. So it is important that you keep track of what story flags you have, where and when they are set and what they are used for. A good way to document this is by drawing a flowchart where you label each arrow with the corresponding story flag.

Many open world RPGs (like the Elder Scrolls or the Mass Effect series) allow story variables to act both as Boolean flags (to check simply if something did or did not happen) or to carry an integer value (like the current stage of a linear sidequest). If you want to keep it simple, you could implement your story variables with an associative array mapping `String` to `Integer`.
> 2 votes

---
Tags: game-design, algorithm, data-structure
---


# Question
Title: How to calculate a normalized direction of two rotations?
In Vector math and translations we can do:

```
dir = (v1 - v2).norm

```

and then `v1.translate(dir * 50)` so `v1` moves to the `v2`'s direction.

What about `rotation` and `eulerAngles`?

Here's my attempt, but it doesn't work, probably from some obvious reasons.

```
Vector3 initial = ob1.transform.rotation.eulerAngles; // get it's initial rotation
ob1.Rotate(new Vector3(0,0,90)); // rotate
Vector3 after = ob1.transform.rotation.eulerAngles; // store new rotation
ob1.Rotate(new Vector3(0,0,-90)); // rotate back to initial

// here I need to calculate the direction so I can do rotate(dir * 50); or something similar

```

I need to get the rotation direction, so I can rotate the object continously with direction, not with a fixed desired angle value.

To be super clear, I need to get this blue line direction:

The object is initially rotated by `(0,0,57)`. I need to rotate it around it's center (green axis).

I know I can do `logo1.transform.RotateAround(logo1.transform.position, logo1.transform.up, 80);` and it works, but I need the direction from this, so I can use it in Tweening.

# Answer
Here's a snippet of code that will do the trick:

```
Vector3 AxisBetween(Quaternion start, Quaternion end) {
    // Here we form a rotation that "undoes" the start orientation,
    // then applies the end orientation on top.
    Quaternion travel = end * Quaternion.Inverse(start);

    // By construction: end = (travel * start)
    // So travel serves as the "quaternion difference" between the two.

    // Now we just extract its axis of rotation.
    Vector3 axis;
    float angle;
    travel.ToAngleAxis(out angle, out axis);

    // I can't recall what the range of these angles is, so this might not be required:
    if(angle < 0f)
        axis *= -1f;

    return axis;
}

```

Note that if `start` = `end` you'll get an axis full of infinities back, since a zero degree rotation around any & every axis maps `start` to `end`. ;) So be sure to check for infinities before using.
> 1 votes

---
Tags: unity, rotation, quaternion, linear-algebra
---


# Question
Title: Why doesn't TriangleTests::Intersects from DirectXMath work correctly?
I am currently looking through the Introduction to 3D Game Programming with Direct X 11 by Frank Luna and I'm trying to implement the ray-triangle intersections. I already have a ray firing when the mouse is clicked and from what I can tell it is the correct direction as I have made the camera move to the direction I click. The book uses XNA math which from what I can tell got replaced by DirectXMath? The equivalent functions in the book are TriangleTests::Intersects found here https://msdn.microsoft.com/en-us/library/windows/desktop/hh855922(v=vs.85).aspx

But it doesn't seem to work in my application and it doesn't find any intersection.

Does anyone know why? Here is my attempt

```
for (int i = 0; i < terrain->terrainIndices.size() / 3; i++) {
    //indices
    int i0 = terrain->terrainIndices[i * 3 + 0];
    int i1 = terrain->terrainIndices[i * 3 + 1];
    int i2 = terrain->terrainIndices[i * 3 + 2];

    //vertices for single tri
    XMVECTOR v0 = XMVectorSet(terrain->terrainVertices[i0].Pos.x, terrain->terrainVertices[i0].Pos.y, terrain->terrainVertices[i0].Pos.z, 0.0f);
    XMVECTOR v1 = XMVectorSet(terrain->terrainVertices[i1].Pos.x, terrain->terrainVertices[i1].Pos.y, terrain->terrainVertices[i1].Pos.z, 0.0f);
    XMVECTOR v2 = XMVectorSet(terrain->terrainVertices[i2].Pos.x, terrain->terrainVertices[i2].Pos.y, terrain->terrainVertices[i2].Pos.z, 0.0f);

    //if ray intersects this triangle
    if (TriangleTests::Intersects(rayOrigin, rayDirection, v0, v1, v2, dist) || TriangleTests::Intersects(rayOrigin, rayDirection,
        v0, v2, v1, dist)) {
        stringstream ss;
        ss << "INTERSECTION FOUND" << endl;
        OutputDebugStringA(ss.str().c_str());
        return true;
    }
    else {
        stringstream ss;
        ss << "NO INTERSECTION" << endl;
        OutputDebugStringA(ss.str().c_str());
    }
}

```

**Edit**: I have also tried this. The loop is the same when I loop over my terrain triangles for calculating normals.

```
for (int i = 0; i < 512; i++) {

        for (int j = 0; j < 512; j++) {

            int index1 = (j * 512) + i;
            int index2 = (j * 512) + (i + 1);
            int index3 = ((j + 1) * 512) + i;

            int index4 = ((j + 1) * 512 + i);
            int index5 = ((j * 512 + (i + 1)));
            int index6 = ((j + 1) * 512 + (i + 1));

            //vertices of triangle
            Vertex vertex1 = terrain->terrainVertices.at(index1);
            Vertex vertex2 = terrain->terrainVertices.at(index2);
            Vertex vertex3 = terrain->terrainVertices.at(index3);

            Vertex vertex4 = terrain->terrainVertices.at(index4);
            Vertex vertex5 = terrain->terrainVertices.at(index5);
            Vertex vertex6 = terrain->terrainVertices.at(index6);

            //each vertex as XMVECTOR
            XMVECTOR point1 = XMVectorSet(vertex1.Pos.x, vertex1.Pos.y, vertex1.Pos.z, 0.0f);
            XMVECTOR point2 = XMVectorSet(vertex2.Pos.x, vertex2.Pos.y, vertex2.Pos.z, 0.0f);
            XMVECTOR point3 = XMVectorSet(vertex3.Pos.x, vertex3.Pos.y, vertex3.Pos.z, 0.0f);

            XMVECTOR point4 = XMVectorSet(vertex4.Pos.x, vertex4.Pos.y, vertex4.Pos.z, 0.0f);
            XMVECTOR point5 = XMVectorSet(vertex5.Pos.x, vertex5.Pos.y, vertex5.Pos.z, 0.0f);
            XMVECTOR point6 = XMVectorSet(vertex6.Pos.x, vertex6.Pos.y, vertex6.Pos.z, 0.0f);
            //if ray intersects this triangle
            if (TriangleTests::Intersects(rayOrigin, rayDirection, point1, point2, point3, dist) || TriangleTests::Intersects(rayOrigin, rayDirection,
                point1, point3, point2, dist)
                || TriangleTests::Intersects(rayOrigin, rayDirection, point4, point5, point6, dist)
                || TriangleTests::Intersects(rayOrigin, rayDirection, point4, point6, point5, dist)) {
                stringstream ss;
                ss << "INTERSECTION FOUND" << endl;
                OutputDebugStringA(ss.str().c_str());
                return true;
            }
        }
    }

```

**Edit**: The ray I'm firing is normalized, is this a problem for this function? Am I even using it correctly?

**Edit**: Nvm the function only works when the vector is normalized. Still can't seem to get any intersection. The rayOrigin and rayDirection seem to be fine. The origin is the cameras position when I click and the direction is a normalized vector of the direction i click in.

**Edit**: *TriangleTests::Intersects is new for DirectXMath. This functionality is not available in XNAMath 2.x. Similar functionality for XNAMath can be found in the DirectX SDK Collision sample.*

Does this have anything to do with the fact I'm not translating the object or rays into a different space? I.e. World space/object space

**Edit**: This is how I am getting calculating the ray direction

```
float pointX, pointY;
    XMMATRIX projectionMatrix, viewMatrix, inverseViewMatrix, worldMatrix, translateMatrix, inverseWorldMatrix;
    XMVECTOR direction, origin, rayOrigin, rayDirection;
    bool intersect, result;

    projectionMatrix = XMLoadFloat4x4(this->projectionMatrix);
    viewMatrix = XMLoadFloat4x4(this->viewMatrix);

    // Move the mouse cursor coordinates into the -1 to +1 range.
    pointX = ((2.0f * (float)mouseX) / (float)screenWidth) - 1.0f;
    pointY = (((2.0f * (float)mouseY) / (float)screenHeight) - 1.0f) * -1.0f;

    pointX = pointX / XMVectorGetX(projectionMatrix.r[0]);
    pointY = pointY / XMVectorGetY(projectionMatrix.r[1]);

    // Get the inverse of the view matrix.
    inverseViewMatrix = XMMatrixInverse(nullptr, viewMatrix);

    //click on screen and camera will rotate on the world Y axis to the clicked point.
    direction =
        XMVectorSet((pointX * XMVectorGetX(inverseViewMatrix.r[0])) + (pointY * XMVectorGetX(inverseViewMatrix.r[1])) + XMVectorGetX(inverseViewMatrix.r[2]),
                    (pointX * XMVectorGetY(inverseViewMatrix.r[0])) + (pointY * XMVectorGetY(inverseViewMatrix.r[1])) + XMVectorGetY(inverseViewMatrix.r[2]),
                    (pointX * XMVectorGetZ(inverseViewMatrix.r[0])) + (pointY * XMVectorGetZ(inverseViewMatrix.r[1])) + XMVectorGetZ(inverseViewMatrix.r[2]), 0.0f);

    camera->turnCameraToPoint(XMFLOAT3(camera->getPosition().x + XMVectorGetX(direction),
        camera->getPosition().y + XMVectorGetY(direction),
        camera->getPosition().z + XMVectorGetZ(direction)));

    std::stringstream ss;

    // Get the origin of the picking ray which is the position of the camera.
    origin = XMVectorSet(camera->getPosition().x, camera->getPosition().y, camera->getPosition().z, 0.0f);

    // Get the world matrix and translate to the location of the sphere.
    worldMatrix = XMLoadFloat4x4(this->worldMatrix);
    //translateMatrix = terrain->getObjectWorld();
    //worldMatrix = XMMatrixMultiply(worldMatrix, translateMatrix);

    // Now get the inverse of the translated world matrix.
    //inverseWorldMatrix = XMMatrixInverse(nullptr, worldMatrix);

    // Now transform the ray origin and the ray direction from view space to world space.
    rayOrigin = XMVectorSet(camera->getPosition().x, camera->getPosition().y, camera->getPosition().z, 0.0f);
    //rayOrigin = XMVector3TransformCoord(origin, worldMatrix);
    //rayDirection = XMVector3TransformCoord(direction, worldMatrix);
    rayDirection = direction;

    // Normalize the ray direction.
    rayDirection = XMVector3Normalize(rayDirection);

    ss << " clicked direction: " << XMVectorGetX(rayDirection) << " y: " << XMVectorGetY(rayDirection) << " z: " << XMVectorGetZ(rayDirection) << endl;

    OutputDebugStringA(ss.str().c_str());

    // Now perform the ray-triangle intersection test.
    float distance = 0.0f;
    intersect = terrainIntersection(rayOrigin, rayDirection, distance);

    if (intersect == true)
    {
        // If it does intersect then set the intersection to "yes" in the text string that is displayed to the screen.
        std::stringstream ss5;

        ss5 << "INTERSECTION!! - " << "dist: " << distance << endl;
        OutputDebugStringA(ss5.str().c_str());
    }
    else
    {
        // If not then set the intersection to "No".
        std::stringstream ss5;
        ss5 << "NO INTERSECTION..." << endl;
        OutputDebugStringA(ss5.str().c_str());
    }

    return;

```

---

**Edit**: I have managed to get a valid intersection from the method, but there is something incorrect as it is now returning a valid intersection for anywhere I click on the screen, and the direction of the ray is producing incorrect results. I have tried to make sure that the ray, ray origin and the vertices of the triangle are all in the same space by doing

```
XMMATRIX translationMatrix = XMMatrixTranslation(camera->getPosition().x, camera->getPosition().y, camera->getPosition().z);
XMMATRIX finalWorld = translationMatrix * worldMatrix * viewMatrix * projectionMatrix;
rayOrigin = XMVector3TransformCoord(origin, finalWorld);

```

Each vertex is also in the same space

```
        finalWorld = XMMatrixIdentity();
        translationMatrix = XMMatrixTranslation(vertex3.Pos.x, vertex3.Pos.y, vertex3.Pos.z);
        finalWorld = translationMatrix * world * view * projection;
        point3 = XMVector3TransformCoord(point3, finalWorld);

```

This now produces a valid intersection

**clicked direction: -0.799399 y: -0.0989474 z: -0.592597 INTERSECTION FOUND INTERSECTION!! - dist: -0**

Although this allows me to click anywhere on the screen and the intersection is deemed valid, even when I am not clicking anywhere on the terrain. Does anyone have any idea why this is happening? The distance returned from the TriangleTests::Intersects method is always 0 or -0

# Answer
I have actually fixed the issue I was having. I needed to transform the vectors into the same spaces using

```
XMVector3Transform(origin, ray->getObjectWorld());

```
> 0 votes

---
Tags: directx, directx11, raycasting, directxmath
---


# Question
Title: How can i move the characters in random speed and generate random speed numbers not the same?
```
using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class SquadFormation : MonoBehaviour
 {
     enum Formation
     {
         Square, Circle, Triangle
     }

     public Transform squadMemeber;
     public int columns = 4;
     public int squareSpace = 10;
     public int circleSpace = 40;
     public int numberOfObjects = 20;
     public float yOffset = 0;
     [Range(3,50)]
     public float moveSpeed = 3;
     public bool randomSpeed = false;
     public float rotateSpeed = 1;
     public float threshold = 0.1f;
     public bool destroySquad = false;

     private Formation formation;
     private List<Quaternion> qua = new List<Quaternion>();
     private List<Vector3> newpos = new List<Vector3>();
     private bool move = false;
     private bool squareFormation = false;
     private List<GameObject> squadMembers = new List<GameObject>();
     private int[] randomSpeeds = new int[30];

     // Use this for initialization
     void Start()
     {
         CreateRandomSpeedArray();

         formation = Formation.Square;
         ChangeFormation();

         foreach (Transform child in gameObject.transform)
         {
             if (child.tag == "Squad Member")
                 squadMembers.Add(child.gameObject);
         }
     }

     // Update is called once per frame
     void Update()
     {
         if (Input.GetKeyDown(KeyCode.F))
         {
             if (destroySquad == true)
             {
                 GameObject[] objects = GameObject.FindGameObjectsWithTag("Squad Member");
                 if (objects.Length > 0)
                 {
                     foreach (GameObject obj in objects)
                         Destroy(obj);
                 }
             }

             ChangeFormation();
         }

         if (move == true)
             MoveToNextFormation();
     }

     private void ChangeFormation()
     {
         switch (formation)
         {
             case Formation.Square:

                 FormationSquare();

                 break;

             case Formation.Circle:

                 FormationCircle();

                 break;
         }
     }

     private Vector3 FormationSquarePositionCalculation(int index) // call this func for all your objects
     {
         float posX = (index % columns) * squareSpace;
         float posY = (index / columns) * squareSpace;
         return new Vector3(posX, posY);
     }

     private void FormationSquare()
     {
         newpos = new List<Vector3>();
         qua = new List<Quaternion>();
         Transform go = squadMemeber;

         for (int i = 0; i < numberOfObjects; i++)
         {
             if (squadMembers.Count == 0)
                 go = Instantiate(squadMemeber);
             Vector3 pos = FormationSquarePositionCalculation(i);
             go.position = new Vector3(transform.position.x + pos.x, 0, transform.position.y + pos.y);
             go.Rotate(new Vector3(0, -90, 0));
             go.tag = "Squad Member";
             go.transform.parent = gameObject.transform;
             newpos.Add(go.transform.position);
         }
         //}
         move = true;
         squareFormation = true;
         formation = Formation.Circle;
     }

     private Vector3 FormationCirclePositionCalculation(Vector3 center, float radius, int index, float angleIncrement)
     {
         float ang = index * angleIncrement;
         Vector3 pos;
         pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
         pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
         pos.y = center.y;
         return pos;
     }

     private void FormationCircle()
     {
         newpos = new List<Vector3>();
         qua = new List<Quaternion>();

         Vector3 center = transform.position;
         float radius = (float)circleSpace / 2;
         float angleIncrement = 360 / (float)numberOfObjects;
         for (int i = 0; i < numberOfObjects; i++)
         {
             Vector3 pos = FormationCirclePositionCalculation(center, radius, i, angleIncrement);

             var rot = Quaternion.LookRotation(center - pos);
             pos.y = Terrain.activeTerrain.SampleHeight(pos);
             pos.y = pos.y + yOffset;
             newpos.Add(pos);
             qua.Add(rot);
         }
         move = true;
         squareFormation = false;
         formation = Formation.Square;
     }

     private void MoveToNextFormation()
     {
         CreateRandomSpeedArray();
         float step = moveSpeed * Time.deltaTime;
         for (int i = 0; i < squadMembers.Count; i++)
         {
             squadMembers[i].transform.LookAt(newpos[i]);
             if (randomSpeed == true)
             {
                 squadMembers[i].transform.position =
             Vector3.MoveTowards(squadMembers[i].transform.position, newpos[i], randomSpeeds[i] * Time.deltaTime);
             }
             else
             {
                 squadMembers[i].transform.position =
                 Vector3.MoveTowards(squadMembers[i].transform.position, newpos[i], step);
             }
             if (Vector3.Distance(squadMembers[i].transform.position, newpos[i]) < threshold)
             {
                 if (squareFormation == true)
                 {
                     Vector3 degrees = new Vector3(0, -90f, 0);
                     Quaternion quaternion = Quaternion.Euler(degrees);
                     squadMembers[i].transform.rotation = Quaternion.Slerp(squadMembers[i].transform.rotation, quaternion, rotateSpeed * Time.deltaTime);
                 }
                 else
                 {
                     squadMembers[i].transform.rotation = Quaternion.Slerp(squadMembers[i].transform.rotation, qua[i], rotateSpeed * Time.deltaTime);
                 }
             }
         }
     }

     private void CreateRandomSpeedArray()
     {
         for (int arrayIndex = 0; arrayIndex < randomSpeeds.Length; arrayIndex++)
         {
             randomSpeeds[arrayIndex] = Random.Range(0, 30);
         }
     }
 }

```

I have some problems.

First i create array of random numbers each number is a movement speed value. But in the array there are some numbers that are the same some numbers are 0. I want that there will be no same numbers in the array no 0.

Another problem is when i'm using the speed values in the method MoveToNextFormation on the line:

```
squadMembers[i].transform.position =
                 Vector3.MoveTowards(squadMembers[i].transform.position, newpos[i], randomSpeeds[i] * Time.deltaTime);

```

I don't see the characters are moving in random speed they are all moving the same speed and slow. I want each character to move in another speed.

Another problem is in the Update in this part:

```
if (move == true)
             MoveToNextFormation();

```

I need to call MoveToNextFormation from inside the Update to make the characters move but then move variable will be all the time true and it will keep calling the method MoveToNextFormation over and over again. How can i make that each time the characters finished moving and rotating to stop calling MoveToNextFormation until the next time ? Making move = false; in the bottom of MoveToNextFormation is not working.

I can't even debug the MoveToNextFormation since it's being called every frame in the Update even if the characters are not moving. I want it to be called only when i click on F the problem is that then it will be called once and the character won't move.

# Answer
For no 0 values: `Random.range(1, 30)`

For no double values:

```
private void CreateRandomSpeedArray()
{
     for (int arrayIndex = 0; arrayIndex < randomSpeeds.Length; arrayIndex++)
    {
        bool double = false;
        int number;
        do
        {
            number = Random.Range(1, 30);
            for(int i = arrayIndex - 1; i >= 0; i--)
            {
                double = (double | (randomSpeeds[i] == number));
            }
        } while(double);
        randomSpeeds[arrayIndex] = number;
    }
}

```

For the usage problem I have no idea (sorry).

For the MoveToNextFormation: Check out Unitys Coroutines. I guess they will fit your needs.
> 1 votes

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


title: DirectX11 bind all textures at once?

text:
# Question
Title: DirectX11 bind all textures at once?
If my game will use say 100mb of raw memory for textures, would it be a good idea to put all of them in srv array, bind once and leave it for the rest of the program so that I won't have to bind them ever again and thus save some processing power? I'm targeting gpus with at least 2gb of vram.

# Answer
It is usually a good idea to avoid most graphics state setup. The term texture array however, can be somewhat confusing, because it might mean this:

```
Texture2D myTextures[12] : register(t0)

```

Which means, that each texture consumes a texture slot, so t0, t1, ... t11 are consumed. But it can also mean this:

```
Texture2DArray myTextures : register(t0)

```

This consumes a single texture slot t0. But all textures in the array must share the same properties (resolution, format, etc.).

An other option is that you can pack all your textures into a texture atlas. This somewhat complicates updating the textures and sampling mip levels.

In DirectX 12, Vulkan and console specific graphics APIs, you can use bindless textures which decouples texture bind slots from the resources and allows dynamically selecting the texture from a global set in the shader.

That said, we don't know if any of this would be a benefit to you without further profiling data for your application. Maybe the more complicated resource management won't pay off for your specific case.
> 0 votes

---
Tags: c++, textures, directx11, optimization, memory-efficiency
---


# Question
Title: Correcting projection of 360° content onto a sphere - distortion at the poles
I'm using the Autopano Giga 4.4 and Autopano Video Pro 2.6 to stitch and create spherical content, but I've recently moved into wanting to create 360° tours via Unity. I know this is partly a developers question, but if anyone out there can help me with the right specs for exporting a spherical image or video from Giga to use to create the image for the inside of the sphere on Unity, I'd appreciate it!

Experimenting with Premiere and FCPX to edit highlight reels of spherical content, I've had seamless experiences created. For some reason in Unity, the images appear to be stretched around the sphere wrong and it's creates issues on the top and bottom of the image:

The image shown is the bottom of the sphere. I'm using the Android platform to hopefully turn these tours into apps when completed. Thank you for any help!

# Answer
This isn't a matter of codecs and resolution, you just need to match the texture mapping onto the sphere geometry to the mapping used in the video format - in this case equirectangular.

Equirectangular mapping (also called latitude/longitude or spherical coordinates) is non-linear. That means normal UV mapping can only approximate it - quite badly at the poles, in fact.

To fix this, we can calculate our own texture coordinate per fragment using the direction to the fragment being drawn, resulting in a perfect match. Here's an example shader that does this:

```
Shader "Unlit/PanoramaShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType" = "Opaque" }
        LOD 100

        // Render the object inside-out.
        Cull Front

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                // Pass a view direction instead of a UV coordinate.
                float3 direction : TEXCOORD0;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                // Compute worldspace direction from the camera to this vertex.
                o.direction = mul(unity_ObjectToWorld, v.vertex).xyz
                               - _WorldSpaceCameraPos;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // Convert the direction to the fragment into latitude & longitude.
                float3 pos = normalize(i.direction);
                float2 uv;
                uv.x = atan2(pos.z, pos.x)* 0.5f;
                uv.y = asin(pos.y);

                // Scale and shift into the 0...1 texture coordinate range.
                uv = uv / 3.141592653589f + 0.5f;

                // Used directly, we'll get a texture filtering seam
                // where the longitude wraps around from 1 to 0.
                // This fixes that (you can skip this if your videos don't mipmap)
                float2 dx = ddx(uv);
                float2 dy = ddy(uv);
                float2 du = float2(dx.x, dy.x);
                du -= (abs(du) > 0.5f) * sign(du);
                dx.x = du.x;
                dy.x = du.y;

                // In case you want to rotate your view using the texture x-offset.
                uv.x += _MainTex_ST.z;

                // Sample the texture with our calculated UV & seam fixup.
                fixed4 col = tex2Dgrad(_MainTex, uv, dx, dy);

                return col;
            }
            ENDCG
        }
    }
}

```

As a bonus, since we're just using the direction to the vertex, your object doesn't need to be a sphere - you can render this on a box or even a singe quad parented in front of the camera and it will act as a "magic window" into the 360 scene.
> 4 votes

---
Tags: virtual-reality, gearvr, 360-video
---


title: Why calculate A* Pathfinding F Cost?

text:
# Question
Title: Why calculate A* Pathfinding F Cost?
I just made an A\* Pathfinding system in unity that doesn't calculate the f cost (g cost + h cost) and I wondering why do u actually have to calculate the f cost? I mean my pathfinding system that works perfectly fine. Any ideas?

# Answer
Calculating the F cost allows you to proximate the shortest path and reach your goal faster. Any tile with the lowest F cost should be evaluated first and sorted accordingly, preventing A\* from visiting tiles that lead to a worst cost case scenario ( in some cases there is no resolution so that will be the case anyway).
> 4 votes

# Answer
If you didn't calculate the f-cost value, then your path finding implementation is probably slow and isn't actually an A\* algorithm.

The f-cost is a heuristic estimate for a visited node, that tells you around how long the path is going to be including the exact length of the path to that node and the guessed length of the path from that node to the end. When you choose the next node you'll need to choose the one with the lowest f-cost.
> 4 votes

# Answer
The F cost is an underestimate of the cost from going from the current location to the goal. It is used to decrease the amount of exploration required to find the right answer.

A\* earns its "\*" from being "optimal." What that means is that it accomplishes its goal in the lowest amount of work possible given the information. It is provable that no algorithm given the same information can do better than A\*. If you have information that can be used to calculate a heuristic underestimate of this cost, and you aren't using it, your algorithm is being inefficient (though it can still work). On the other hand, if you have more information, then it is possible to write an algorithm that is more efficient than A\*.
> 1 votes

---
Tags: path-finding
---


# Question
Title: Why is my Mesh reference being marked (Clone) after I add a new component?
I have a script that creates a quad mesh, saves the mesh as an asset, and assembles a game object based on some parameters. If I add another component to the GameObject after, the mesh is marked "(Clone)".

gif for reference. This all happens in code but results are the same when doing it manually.

## -

When I drag the object to the project view to make it a prefab, the **Mesh Filter** loses it's Mesh reference. It's fine if I manually assign the mesh afterwards but that defeats the purpose of doing it this way. To be clear, if I *don't* add this (or any) component, it works fine and can be made into a prefab without issue.

# Answer
> 0 votes
It sounds like your UV adjuster script might be accessing

```
GetComponent<MeshFilter>().mesh

```

As with `renderer.material`, accessing this getter creates a local copy of the asset, so any changes you make will be local to this instance and not spill over into other instances using the asset, or your asset source file itself.

If you want to modify the mesh dynamically, this is probably the behaviour you want.

If you want to access the original, uncopied mesh, then you'd use the `.sharedMesh` getter instead.

---
Tags: unity, mesh
---


# Question
Title: fading from one scene to another not working
I am using the following code to fade from one scene to another, but it doesn't fade. It just loads the next scene without fading. I suspect there's something wrong with the image I'm using. I used a black .png image with dimensions 425×344 that I downloaded from Google. How can I solve this issue?

Fading.cs (I added this to an empty game object)

```
public Texture2D fadeOutTexture;
public float fadeSpeed = 0.8f;

private int drawDepth = -1000;
private float alpha = 1.0f;
private int fadeDir = -1;

void onGUI () {

    alpha += fadeDir * fadeSpeed * Time.deltaTime;
    alpha = Mathf.Clamp01(alpha);
    GUI.color = new Color (GUI.color.g, GUI.color.b, alpha);
    GUI.depth = drawDepth;
    GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), fadeOutTexture); }

public float BeginFade (int direction) {
    fadeDir = direction;
    return (fadeSpeed); }

void onLevelWasLoaded() {
    BeginFade (-1);

}

```

In the script of the trigger object:

```
IEnumerator gameScene2() {
    float fadeTime = GameObject.Find ("FadeObject").GetComponent<Fading>().BeginFade(1);
    yield return new WaitForSeconds(fadeTime);
    Application.LoadLevel("Scene2");
}

```

These are the image settings for the black .png image

# Answer
> 1 votes
Some things I noticed:

* onGUI and onLevelWasLoaded should be **OnGUI/OnLevelWasLoaded**
* You forgot to set the red component here, so you are not setting the alpha value of the color

> GUI.color = new Color (GUI.color.g, GUI.color.b, alpha);
* Try to set the *alphaBlend* parameter to true on the DrawTexture function (I think it's true by default, but I didn't test it, so give it a try):

> GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), fadeOutTexture, ScaleMode.StretchToFill, true);
* You shouldn't change the alpha value in the OnGUI function, it's better to do in the Update
* I don't know how you are using the code, but remember that Unity will destroy the object you attached the script on when you load a new scene. I suggest you to write a static class to switch levels, or use DontDestroyOnLoad on your GameObject

---
Tags: unity
---


# Question
Title: Why is my sliding AABB collision acting strange?
I'm working on a Minecraft like game engine and recently I've been trying to add good collision response which I have kind of. The collision response is perfect when I try and go through the right side or front side of this cube.

I'm doing a dot product between my player's velocity vector and the normals for each side of the cube (ex: `new Vector3f(0.0f,1.0f,0.0f) //Up`) and seeing which normal gives the dot product which is the greatest and then I multiply my velocity vector by that normal vector in order to create this cool sliding effect.

This sliding effect only works for the right and front sides of the cube and the rest of the sides have a weird effect which is not sliding at all. Anyway if anyone can help with this it would be very much appreciated :). This is my method for detecting collision which works efficiently. Then there's the method for detecting which way the player should slide which is called **velocityDirection**. **Update:** Whenever I try and touch ANY side of the cube (I am printing out the variable BestMatch from the velocityDirection class which is one of the normals from the array of normals) it returns a value of Vector3f(0,1,0) and when I try and move and go through the right side like a ghost it returns Vector3f(-1,0,0) and for the front side it returns Vector3f(0,0,-1), and remember the right and front sides both have perfect collision.

**Collision Detection Method:**

```
public static boolean IsCollision(AABB player, AABB block)
      {

            boolean x = player.getMaxX() > block.getMinX() && player.getMinX() < block.getMaxX();

            boolean y = player.getMaxY() > block.getMinY() && player.getMinY() < block.getMaxY();

            boolean z = player.getMaxZ() > block.getMinZ() && player.getMinZ() < block.getMaxZ();

            return (x && y && z);
          }

```

**Sliding Response Method :**

```
public static Vector3f velocityDirection(Vector3f velocityDirection){
            Vector3f normalsArray[] = new Vector3f[]{
                    new Vector3f(0.0f,1.0f,0.0f),  // Up
                    new Vector3f(1.0f,0.0f,0.0f),//Right
                    new Vector3f(0.0f,-1.0f,0.0f), // Down
                    new Vector3f(-1.0f,0.0f,0.0f), //Left
                    new Vector3f(0.0f,0.0f,1.0f), //Front
                   new Vector3f(0.0f,0.0f,-1.0f) //Back

            };
            Vector3f BestMatch = new Vector3f();
            Vector3f TrueVelocity = new Vector3f();
            float max = 0;
            for(int i = 0 ; i < normalsArray.length ; i++){
                float dot = Vector3f.dot(velocityDirection, normalsArray[i]);
                if(dot > max){
                    max = dot;
                    BestMatch = normalsArray[i];

                }
            }
            TrueVelocity = new Vector3f(velocityDirection.x  * BestMatch.x, velocityDirection.y  * BestMatch.y, velocityDirection.z  * BestMatch.z );

            return TrueVelocity;
        }

```

**Camera Class:**

```
public class Camera {

    private static Vector3f position = new Vector3f(0,0,0);
    public static float pitch = 20 ;
    public static float rx, ry, rz;

    public static float velocityX;
    public static float velocityY;
    public static float velocityZ;

    public static float yaw;
    public static float roll;
    private  final static float RUN_SPEED = 20;

    private final static float TURN_SPEED = 150;
    private static float JUMP_POWER = 10;
    private static float currentSpeed = 0;
    public static float currentTurnSpeed = 0;
   public static boolean isMovingX = false;
   public static boolean isMovingY = false;

    public float angleAroundPlayer = 0;
    private static final Vector4f Forward = new Vector4f(0,0,-1,0);
    private static final Vector4f Backward = new Vector4f(0,0,1,0);

   public static boolean isColliding = false;

    public static void moveCamera(AABB player,AABB box){
          calculatePitch();
          if(Keyboard.isKeyDown(Keyboard.KEY_W)){
         isMovingX = true;

              currentSpeed = -RUN_SPEED;

              }
          else if(Keyboard.isKeyDown(Keyboard.KEY_S)){
              currentSpeed = RUN_SPEED;
              isMovingX = true;
          }
          else{
              isMovingX = false;
              currentSpeed = 0;
          }

                if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
                    currentTurnSpeed = -TURN_SPEED;

                } else if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
                    currentTurnSpeed = TURN_SPEED;
                } else {
                    currentTurnSpeed = 0;
                }

                if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)){
                 isMovingY = true;
                    velocityY = -JUMP_POWER * DisplayManager.getFrameTimeSeconds();

               }
                else if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
                    isMovingY = true;
                    velocityY = JUMP_POWER * DisplayManager.getFrameTimeSeconds();

                }
                else{
                    isMovingY = false;
                    velocityY = 0;
                }

         yaw -= currentTurnSpeed * DisplayManager.getFrameTimeSeconds();
          Matrix4f rotation = calculateCameraRotationMatrix();
             Vector3f TrueForward = new Vector3f(Matrix4f.transform(rotation,Forward , null));
             Vector3f TrueBackward = new Vector3f(Matrix4f.transform(rotation,Backward , null));
             Vector3f CameraPos = Camera.getPosition();

                    float distance = currentSpeed * DisplayManager.getFrameTimeSeconds();
                velocityX = (float) (distance * Math.sin(Math.toRadians(getRy())));
                velocityZ = (float) (distance * Math.cos(Math.toRadians(getRy())));
                increasePosition(velocityX,velocityY,velocityZ);
                System.out.println(new Vector3f(velocityX, velocityY, velocityZ));
                if(isColliding){
                Vector3f velocityDirection = VectorMath.velocityDirection(new Vector3f(velocityX, velocityY, velocityZ));

                 increasePosition(velocityDirection.x , velocityDirection.y, velocityDirection.z );
          }

         increaseRotation(0, currentTurnSpeed * DisplayManager.getFrameTimeSeconds(), 0);

      yaw %= 360;

    }
    private static Matrix4f calculateCameraRotationMatrix() {
        Matrix4f rotation = new Matrix4f();
        rotation.rotate((float) Math.toRadians(getPitch()), new Vector3f(1, 0, 0));
        rotation.rotate((float) Math.toRadians(getYaw()), new Vector3f(0, 1, 0));
        return rotation;
    }

    public static void increasePosition(float dx, float dy, float dz){
           position.x += dx;
           position.y += dy;
           position.z += dz;
    }
    public static void increaseRotation(float dx, float dy, float dz){
           rx += dx;
           ry += dy;
           rz += dz;

    }

    private static void calculatePitch() {

        float pitchChange = Mouse.getDY() * 0.63f;
        pitch -= pitchChange;
        if (pitch < -40) {
            pitch = -40;
        } else if (pitch > 90) {
            pitch = 90;
        }

}

    public static Vector3f getPosition() {
        return position;
    }

    public static void setPosition(Vector3f position) {
        Camera.position = position;
    }

    public static float getPitch() {
        return pitch;
    }
    public static float getRx() {
        return rx;
    }
    public static float getRy() {
        return ry;
    }
    public static float getRz() {
        return rz;
    }
    public  static float getYaw() {
        return yaw;
    }
    public static float getRoll() {
        return roll;
    }

```

# Answer
> 0 votes
I managed to find the solution, It took me about a week and a half to solve this but I have finally solved it. So what I did is I checked which side of the cube the player is touching to determine where and how the player moved, the collision response is not 100% perfect but it's nearly impossible to go through objects and the sliding is pretty cool so I'm happy about that :)

# Answer
> 0 votes
Before reading the rest of my waffling, try this

```
TrueVelocity = new Vector3f(velocityDirection.x  * Mathf.Abs(BestMatch.x), velocityDirection.y  * Mathf.Abs(BestMatch.y), velocityDirection.z  * Mathf.Abs(BestMatch.z) );

```

You might be multiplying your velocity with negative numbers, which isn't what you want, so take the absolute value with Mathf.Abs()

Anyhow...If I'm reading your code correctly, you're finding the axis that the velocity best aligns with, then "straightening" it. But what if the player is mostly facing the wall, but just rotated just slightly, like this...

In the above diagram we are looking top down on the scene, and the best match for the players direction (or velocity) is the y-axis, but we probably want to slide horizontally.

My first time implementing wall sliding in a FPS was from Mark Overmar's FPS tutorial for GameMaker, it's 10 years old but it's full of great gems. Here's his wall sliding code (modified for clarity).

```
// undo last movement (because collision)
x = xprevious;
y = yprevious;

// if our velocity is more horizontal, wall slide horizontally
if (abs(hspeed) >= abs(vspeed) &&
    not place_meeting(x+hspeed,y,obj_wall_basic)) {
    x += hspeed;
} else if (abs(vspeed) >= abs(hspeed) &&
    not place_meeting(x,y+vspeed,obj_wall_basic)) {
    y += vspeed; exit;
}
// no sliding
speed = 0;

```

Which I now realise doesn't behave as I expect my diagram to...

Also: Are you doing AABB tests against every block in this voxel world? this could get costly. You could improve it by reformulating the ANDs into ORs (with De Morgans theorem) and get early termination (short circuiting), so that when a single comparison is true, the function can return false without having to evaluate all 6 conditions. Since it's more likely that a block is NOT colliding with the player.

```
return !(player.getMaxX() < block.getMinX() ||
         player.getMaxY() < block.getMinY() ||
         player.getMaxZ() < block.getMinZ() ||
         player.getMinX() > block.getMaxX() ||
         player.getMinY() > block.getMaxY() ||
         player.getMinZ() > block.getMaxZ());

```

---
Tags: collision-detection, vector, lwjgl, collision-resolution, aabb
---


title: Finite State Machine Horizontal Jump

text:
# Question
Title: Finite State Machine Horizontal Jump
I'm creating a 2D Sidescrolling Action RPG with MonoGame and I am using a finite state machine. A state consists of an animation and some behavior, only one state can be executed at once, however:

If the player is moving left/right and then jumps, or if he's jumping and then moves left/right I want to play a specific horizontal jumping animation while executing the behavior of both states at once. How is this usually handled? Should I make a completely seperate state for this and copy the behaviors over? That doesn't seem right in accordance to the DRY principle.

BTW I'm going to have a lot of similar merge states, so just making an exception this time won't do.

# Answer
> 1 votes
There is a state machine called "Pushdown automaton". It is basically a Stack structure where you store your states. In your case, you could implement such a state machine, which isnt as hard. If your move state should be able to continue with jumping, you have to implement a dependency check(like in the code below).

This is an pseudocode example implementation in C# style(not tested):

```
Stack<State> states = new Stack<State>();

public bool ApplyState(State state){
    State latestState = states.Peek();
    // Immagine your latest state is STATE_MOVE
    // STATE_MOVE can continue with STATE_JUMP, so you can push STATE_JUMP to the stack
    // WARNING: "latestState" has to check if the parameter "state" alreay is its parent.
    // If you move and jump and move, you would have STATE_MOVE twice, because both can continue with each other.
    if(latestState == null || latestState.CanContinueWith(state))
    {
        states.Push(state);
        return true;
    }
    return false;
}

// This function updates your state.
// Keep in mind that you may have to change the update order
//  of the states because it is Last-in-First-out
public void UpdateStates(){
    foreach(State state in states){
        state.Update();
    }
}

```

This is how my implementation would look like.

Maybe this can give you an idea how to solve the problem.

# Answer
> 0 votes
A good solution example for such a situation is how animations are handled in different engines. Let's take for this example the unity engine and it's mecanim animation framework. The animations in there are also finite state machines. So if you need to play 2 animations at the same time, they introduce **layers**. So you have let's say a layer for the feet and one for the upper body. So if the character has to run and do shooting the feet layer will play the run animation and the upper body layer will play the animation for the shooting. So in your example I would break down the animations and states into different layers. So when you need to add up states, you simply have each layer played. So basically multiple finite state machines that run simoltanious.

---
Tags: fsm
---


# Question
Title: GLSL - skewed parallax occlusion mapping
I'm currently trying to implement Parallax Occlusion Mapping, based off a post on sunandblackcat.com

With my current implementation, I have the following:

```
i.stack.imgur.com/H0c2s.png

```

Notice how the parallax effect is skewed away from the camera? I can't understand what's causing this to happen, so I'm posting here in the hope that someone can help me :)

So first up, I guess I should show what my vertex data looks like:

# Vertex 0

position xyz: (1, 0, -1), normal xyz: (0, 1, 0), tangent xyzw: (1, 0, 0, 1)

# Vertex 1

position xyz: (-1, 0, -1), normal xyz: (0, 1, 0), tangent xyzw: (1, 0, 0, 1)

# Vertex 2

position xyz: (1, 0, 1), normal xyz: (0, 1, 0), tangent xyzw: (1, 0, 0, 1)

# Vertex 3

position xyz: (-1, 0, 1), normal xyz: (0, 1, 0), tangent xyzw: (1, 0, 0, 1)

This vertex data is based off the following scene, as it appears in Blender:

```
i.stack.imgur.com/Y3hE9.png

```

Note that Blender is Z-up, but my vertex data has been converted from Z-up to Y-up, hence my normals point "up" on the Y axis

Given that vertex data, I have the following vertex shader:

```
#version 330

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;
uniform vec3 eyePos;

in vec3 in_Position;
in vec2 in_TextureCoord;
in vec3 in_Normal;
in vec4 in_Tangent;
in float in_ModelOffset;
in float in_TexOffset;

out vec2 pass_TextureCoord;
out float pass_TexOffset;
out vec3 pass_toLightInTangentSpace;
out vec3 pass_toCameraInTangentSpace;

void main(void) {
  mat3 normalMatrix = transpose(inverse(mat3(modelMatrix)));

  pass_TexOffset = in_TexOffset;
  pass_TextureCoord = in_TextureCoord;

  // transform to world space
  vec4 worldPosition = modelMatrix * vec4(in_Position, 1);
  vec3 worldNormal = normalize(normalMatrix * in_Normal);
  vec3 worldTangent = normalize(normalMatrix * in_Tangent.xyz);

  // calculate vectors to the camera and to the light, hardcoded for now
  vec3 worldDirectionToLight = normalize(vec3(0,10,0) - worldPosition.xyz);
  vec3 worldDirectionToCamera = normalize(eyePos - worldPosition.xyz);

  // calculate bitangent from normal and tangent
  vec3 worldBitangnent = cross(worldNormal, worldTangent) * in_Tangent.w;

  // transform direction to the light to tangent space
  pass_toLightInTangentSpace = vec3(
         dot(worldDirectionToLight, worldTangent),
         dot(worldDirectionToLight, worldBitangnent),
         dot(worldDirectionToLight, worldNormal)
      );

  // transform direction to the camera to tangent space
  pass_toCameraInTangentSpace= vec3(
         dot(worldDirectionToCamera, worldTangent),
         dot(worldDirectionToCamera, worldBitangnent),
         dot(worldDirectionToCamera, worldNormal)
      );

  // calculate screen space position of the vertex
  gl_Position = projectionMatrix * viewMatrix * worldPosition;

}

```

And the following fragment shader:

```
#version 330

const int NUM_TEXTURES = 2;

uniform sampler2DArray diffuseTexture;

uniform vec3 ambientColor;

uniform float specularIntensity;
uniform float specularPower;
uniform float renderNormal;
uniform float height_scale;

in vec2 pass_TextureCoord;
in float pass_TexOffset;
in vec3 pass_toLightInTangentSpace;
in vec3 pass_toCameraInTangentSpace;

out vec4 out_Color;

const float parallaxScale = 0.1;

//////////////////////////////////////////////////////
// Implements Parallax Mapping technique
// Returns modified texture coordinates, and last used depth
vec2 parallaxMapping(in vec3 V, in vec2 T, out float parallaxHeight)
{
   // determine optimal number of layers
   const float minLayers = 10;
   const float maxLayers = 15;
   float numLayers = mix(maxLayers, minLayers, abs(dot(vec3(0, 0, 1), V)));

   // height of each layer
   float layerHeight = 1.0 / numLayers;
   // current depth of the layer
   float curLayerHeight = 0;
   // shift of texture coordinates for each layer
   vec2 dtex = parallaxScale * V.xy / V.z / numLayers;

   // current texture coordinates
   vec2 currentTextureCoords = T;

   // depth from heightmap
   float heightFromTexture = texture(diffuseTexture, vec3(currentTextureCoords, pass_TexOffset+1)).a;

   // while point is above the surface
   while(heightFromTexture > curLayerHeight)
   {
      // to the next layer
      curLayerHeight += layerHeight;
      // shift of texture coordinates
      currentTextureCoords -= dtex;
      // new depth from heightmap
      heightFromTexture = texture(diffuseTexture, vec3(currentTextureCoords, pass_TexOffset+1)).a;
   }

   ///////////////////////////////////////////////////////////

   // previous texture coordinates
   vec2 prevTCoords = currentTextureCoords + dtex;

   // heights for linear interpolation
   float nextH = heightFromTexture - curLayerHeight;

   float prevH = texture(diffuseTexture, vec3(prevTCoords, pass_TexOffset+1)).a
                           - curLayerHeight + layerHeight;

   // proportions for linear interpolation
   float weight = nextH / (nextH - prevH);

   // interpolation of texture coordinates
   vec2 finalTexCoords = prevTCoords * weight + currentTextureCoords * (1.0-weight);

   // interpolation of depth values
   parallaxHeight = curLayerHeight + prevH * weight + nextH * (1.0 - weight);

   // return result
   return finalTexCoords;
}

//////////////////////////////////////////////////////
// Implements self-shadowing technique - hard or soft shadows
// Returns shadow factor
float parallaxSoftShadowMultiplier(in vec3 L, in vec2 initialTexCoord,
                                       in float initialHeight)
{
   float shadowMultiplier = 1;

   const float minLayers = 15;
   const float maxLayers = 30;

   // calculate lighting only for surface oriented to the light source
   if(dot(vec3(0, 0, 1), L) > 0)
   {
      // calculate initial parameters
      float numSamplesUnderSurface = 0;
      shadowMultiplier = 0;
      float numLayers = mix(maxLayers, minLayers, abs(dot(vec3(0, 0, 1), L)));
      float layerHeight = initialHeight / numLayers;
      vec2 texStep = parallaxScale * L.xy / L.z / numLayers;

      // current parameters
      float currentLayerHeight = initialHeight - layerHeight;
      vec2 currentTextureCoords = initialTexCoord + texStep;
      float heightFromTexture = texture(diffuseTexture, vec3(currentTextureCoords, pass_TexOffset+1)).a;
      int stepIndex = 1;

      // while point is below depth 0.0 )
      while(currentLayerHeight > 0)
      {
         // if point is under the surface
         if(heightFromTexture < currentLayerHeight)
         {
            // calculate partial shadowing factor
            numSamplesUnderSurface += 1;
            float newShadowMultiplier = (currentLayerHeight - heightFromTexture) *
                                             (1.0 - stepIndex / numLayers);
            shadowMultiplier = max(shadowMultiplier, newShadowMultiplier);
         }

         // offset to the next layer
         stepIndex += 1;
         currentLayerHeight -= layerHeight;
         currentTextureCoords += texStep;
         heightFromTexture = texture(diffuseTexture, vec3(currentTextureCoords, pass_TexOffset+1)).a;
      }

      // Shadowing factor should be 1 if there were no points under the surface
      if(numSamplesUnderSurface < 1)
      {
         shadowMultiplier = 1;
      }
      else
      {
         shadowMultiplier = 1.0 - shadowMultiplier;
      }
   }
   return shadowMultiplier;
}

//////////////////////////////////////////////////////
// Calculates lighting by Blinn-Phong model and Normal Mapping
// Returns color of the fragment
vec4 normalMappingLighting(in vec2 T, in vec3 L, in vec3 V, float shadowMultiplier)
{
   // restore normal from normal map
   vec3 N = normalize(texture(diffuseTexture, vec3(T, pass_TexOffset+1)).xyz * 2 - 1);
   vec3 D = texture(diffuseTexture, vec3(T, pass_TexOffset)).rgb;

   // ambient lighting
   float iamb = 0.2;
   // diffuse lighting
   float idiff = clamp(dot(N, L), 0, 1);
   // specular lighting
   float ispec = 0;
   if(dot(N, L) > 0.2)
   {
      vec3 R = reflect(-L, N);
      ispec = pow(dot(R, V), 32) / 1.5;
   }

   vec4 resColor;
   resColor.rgb = D * (vec3(0.1, 0.1, 0.1) + (idiff + ispec) * pow(shadowMultiplier, 4));
   resColor.a = 1;

   return resColor;
}

/////////////////////////////////////////////
// Entry point for Parallax Mapping shader
void main(void)
{
   // normalize vectors after vertex shader
   vec3 V = normalize(pass_toCameraInTangentSpace);
   vec3 L = normalize(pass_toLightInTangentSpace);

   // get new texture coordinates from Parallax Mapping
   float parallaxHeight;
   vec2 T = parallaxMapping(V, pass_TextureCoord, parallaxHeight);

   // get self-shadowing factor for elements of parallax
   float shadowMultiplier = parallaxSoftShadowMultiplier(L, T, parallaxHeight - 0.05);

   // calculate lighting
   out_Color = normalMappingLighting(T, L, V, shadowMultiplier);
}

```

I think the majority of this lines up with the sunandblackcat implementation, although I load in my textures as a texture array - the first texture being an RGBA diffuse map, and the second texture being a normal map (RGB) and height map (A)

From what I've posted, can anyone tell me where I'm going wrong, and why my parallax effect is skewed away from the camera?

Thanks

## * Update *

So I decided to cut out the middle man (my exporter), and manually tweaked the tangents to see how far it got me. So after some brute forcing, for a simple plane, it seems that a tangent xyzw of (-1, 0, 0, -1) gave me something that looked like parallax occlusion mapping:

But when I move in quite close to the mesh, the effect skews again:

Is this an expected side effect of POM, or does this indicate an issue with how the effect is being calculated?

As for the updated tangents - I'm not sure if I need to update my exporter to negate the xyzw components, or if only x and w need to be negated - but I don't really understand why I need to modify the tangents at all? Given that even with the updated tangents, there are still some strange effects happening up close to the surface, I can't help but feel that there's something going wrong in my shaders...

# Answer
normalMapping should use TBN, Parallax Mapping should use transpose(TBN), and viewDirection should mul transpose(TBN).
> 3 votes

---
Tags: opengl, shaders, glsl, fragment-shader, vertex-shader
---


# Question
Title: Why do my animations need to be marked as "legacy?"
I'm in the beginning of a project and I'm not really using 3D models but rather a hierarchy of primitive shapes. I made a couple of animations that suddenly don't work anymore. I get an error about that I need to mark them 'legacy'.

I came across this suggestion to mark them as legacy in the rig tab via the model, but I'm not using a model so that doesn't help.

I don't understand how the animations that I made in Unity yesterday don't work today? What is this legacy problem?

# Answer
> 5 votes
To make sure this question has an answer on GD:SE to help others when searching I'm posting the link you mentioned:

http://answers.unity3d.com/questions/581261/animations-suddenly-need-to-be-marked-legacy.html

To quote:

> I've recently ran into this exact same problem and I've found 2 ways to solve my issue, so I'm hoping I can help you.
>
> EDIT
>
> ---
>
> This post is becoming aged but keeps popping up so I'll add an edit. Since the original post I've been made aware of an easier way to mark your animation files as Legacy:
>
> Project window, then go to the top right corner of the Inspector window and select Debug from the drop down menu (next to the lock), then change the Animation Type to 1 will mark it as Legacy.
>
> I'm not sure if you did, but when I created my original animation files, I did so inside of the "Project" window. Try adding an animation component to the sprite you want to animate, then open the animation window and select "\[create new animation\]" in the drop down menu. Doing it this way seems to create the new animation with the legacy animation flag set. This way you can completely avoid the warning or need for editing animation files. I hope this solves your issue, I know how frustrating it was for me.

# Answer
> 1 votes
If you don't want to mark your animations as legacy, you can use the new Playables API to play non-legacy AnimationClips:

```
private List<PlayableGraph> graphs = new List<PlayableGraph> ();

// Just call this function when you want to play an AnimationClip on a specific GameObject.
// from https://docs.unity3d.com/Manual/Playables-Examples.html
private PlayableGraph playAnim(AnimationClip clip, GameObject obj) {
    PlayableGraph playableGraph;

    AnimationPlayableUtilities.PlayClip(obj.AddComponent<Animator>(), clip, out playableGraph);

    // save all graphs we create and destroy them at the end of our scene.
    // you might need to optimize this if you make a lot of animations.
    graphs.Add (playableGraph);

    return playableGraph;
}

void OnDisable() {
    foreach (var g in graphs) {
        g.Destroy();
    }
    graphs.Clear ();
}

```

---
Tags: unity, animation
---


# Question
Title: How to achieve an orbit-adjustable rotation?
Here's a script:

```
public float RotationSpeed = 100f;
public float OrbitSpeed = 50f;
public float DesiredMoonDistance;
public Transform target;

public Vector3 axis = Vector3.forward;

void Update () {
    transform.Rotate(Vector3.forward, RotationSpeed * Time.deltaTime);
    transform.RotateAround(target.position, Vector3.forward, OrbitSpeed * Time.deltaTime);

    float currentMoonDistance = Vector3.Distance(target.position, transform.position);
    Vector3 towardsTarget = transform.position - target.position;

    transform.position = transform.position + (DesiredMoonDistance - currentMoonDistance) * towardsTarget.normalized;
}

```

which makes a continous rotation at `DesiredMoonDistance` on a `Z axis`:

The problem with this script is that the rotating object needs a 'tilt' at the start.

If both the objects (the planet and the moon) have the same initial position, the rotation won't start, no matter how big the distance is set, because of this:

```
Vector3 towardsTarget = transform.position - target.position;
transform.position = transform.position + (DesiredMoonDistance - currentMoonDistance) * towardsTarget.normalized;

```

`towardsTarget` becomes `(0,0,0)` and there's no escape from that black hole.

I'm trying to figure out, how to adjust the script with some `if`'s for a situation, when their position is equal, so I don't have to make stupid moves like `moon.transform.translate(.0001f,0f,0f)` so it tilt's at the start.

My real goal is to adjust this, so even if I change the `DesiredMoonDistance` to `0` in the inspector and then increase it, it will unstuck and go to the desired distance.

# Answer
If you want to make minimal changes, a simple if statement will do:

```
void Update () {
  transform.Rotate(Vector3.forward, RotationSpeed * Time.deltaTime);
  transform.RotateAround(target.position, Vector3.forward, OrbitSpeed * Time.deltaTime);

  float currentMoonDistance = Vector3.Distance(target.position, transform.position);
  Vector3 towardsTarget = transform.position - target.position;

  if (currentMoonDistance == 0)
    transform.position += Vector3.right * DesiredMoonDistance;
  else
    transform.position = transform.position + (DesiredMoonDistance - currentMoonDistance) * towardsTarget.normalized;
}

```

But another solution might be to track revolution in a variable separately, and just apply each frame:

```
private float OrbitPhase;
void Update () {
    transform.Rotate(Vector3.forward, RotationSpeed * Time.deltaTime);

    OrbitPhase += OrbitSpeed * Time.deltaTime;
    transform.position = target.position + Quaternion.Euler(0, 0, OrbitPhase) * Vector3.up * DesiredMoonDistance;
}

```
> 1 votes

---
Tags: unity, rotation, transformation, orbit
---


# Question
Title: Calculating real time moment of inertia around arbitrary axis in 3d
I have a 3d rigid body consisting of multiple triangles forming a closed mesh. I know how to calculate the moment of inertia around an arbitrary axis by splitting up the mesh into simpler shapes and using the parallel axis theorem and summarization to calculate the angular mass for the whole thing.

The problem is that in a real time simulation I would have to re-calculate the rotation mass for every impulse applied to the body. In my 2d simulation this is not a problem as there is just one orientation to any rotation axis, so I can calculate the angular mass just once.

Is there a way to pre-calculate the rotation mass for a 3d object, or is there a simplified way of doing this?

# Answer
> 1 votes
Why would you have to re-calculate it? The moment of inertia is a calculate-once feature of the object and persistent as long as you do not modify the object. Adding a force (or impulse) does not affect it's moment of inertia. Even if it rotates around "whatever" axis (of whatever reason), the object's moment of inertia is still always the same, there will just be additional forces in the equation.

Consider a car wheel that isn't attached at it's centerpoint P0 but at a point P1 at it's periphery. And never mind the inconvenient bumpyness when you drive :-). Spinning up that wheel from that silly attachpoint P1 requires a torque that consists of two parts:

1. Rotating a mass around P1, the mass is seen (from P1:s point of view) as a single m(ass) located at P0.
2. Spinning up the wheel. It wheel also rotates. Proof: Consider the attach point is just 1 mm off. It spins around the well placed wheel axis. Then consider it's 10 mm off - spins. The consider it's at the periphery - spins. No matter where P1 is, even if it's 1 km away, the wheel spins. So the 2nd thing to do is spinning up the wheel, and here the moment of inertia is what you work against.

From the wheels' point of view, it has no idea what it rotates around. Those mini-guys that live on the wheel only see their home rotating (eg. by using a compass) and of course there are some odd, inconvenient extra stuff, the centrifugal force around P1, but that has nothing to do with the wheel's moment of inertia.

A torque is always independent of attach point, or "view" point. The only thing that matters is the direction of the rotational axis. It doesn't matter (from the objects point of view) where the axis hits the object, that only introduces calculation for an external system, if the object is part of one such.

Another thing to know: If you lift up your car wheel and (try to) untighten a bolt, the wheel rotates (women do that :-)) and there is a torque "in the wheel". Even if you move the bolt 1 km from the wheel center, and rotate it, the torque will be the same. Or, if the move the wheel axis 1 km away - doesn't matter **provided that both you and the wheel axis are free to move**. If you are not, then you are an external system and the wheel becomes part of that.

If you only look at the object but nothing external, it's moment of inertia is persistent and thus a calc-once feature. Your pre-calc will do for the duration of the object un-modofied to it's shape or mass.

---
Tags: mathematics, rotation, optimization, physics-engine
---


# Question
Title: Unity - How do I make non-convex Meshes collide with physics?
Whenever I add a Rigidbody component to an object with a non-Convex Mesh, Unity throws this error:

> Non-convex MeshCollider with non-kinematic Rigidbody is no longer supported in Unity 5. If you want to use a non-convex mesh either make the Rigidbody kinematic or remove the Rigidbody component. Scene hierarchy path "Ship/BlockHolder/MeshHolder \[0\]", Mesh asset path "" Mesh name "MeshHolderTemplate(Clone)"

https://docs.unity3d.com/Manual/class-MeshCollider.html

After doing some research, it appears that I need to either enable the "Convex" setting for the Mesh Collider (which is NOT what I want - my objects require concavity)

or enable the "Is Kinematic" option for the Rigidbody component (which is NOT what I want either - from what I can see, Kinematic objects cannot be pushed by other objects)

The end goal is this: https://www.youtube.com/watch?v=O\_UXKce9-OY&t=41s

(I can add the destruction later, for now, I just want the objects to be able to move and not intersect with each other)

How do I do this? I am completely lost here. Is this impossible in Unity?

# Answer
This answer applies to anyone who's willing to pay $9 for an asset on the Unity Asset Store.

I found this script which builds "compound colliders" out of `BoxCollider` colliders. These colliders allow me to use a non-Kinematic Rigidbody on my voxel objects.

The example scene needs some tweaking to get working in the latest Unity, but the script works fine.

http://productivity-boost.com/DownloadNonConvexMeshCollider.html

https://www.assetstore.unity3d.com/en/#!/content/84867
> 1 votes

---
Tags: unity, collision-detection, physics, rigidbody, meshcollider
---


title: Combined Mesh and Lightmap

text:
# Question
Title: Combined Mesh and Lightmap
I am using Unity 2017.

The left picture is the original state. Light map applied.

On the right is the state after all meshes are made into Combined Mesh.

Same lightmap settings as left.

As you can see, it is filled with dirty black dots.

What should I do?

# Answer
If you combined your tiny mesh into a big one in code, such as following:

```
    Mesh newMesh = new Mesh();
    newMesh.name = "CombinedBig";
    newMesh.CombineMeshes(combineInstances, false, false);
    Unwrapping.GenerateSecondaryUVSet(newMesh);  // This line is necessary!!
    meshFilterCombine.sharedMesh = newMesh;

```

You need generate the secondary UVs set for the big mesh.
> 1 votes

---
Tags: unity, mesh, lightmap
---


title: Particle system prefab not instantiated

text:
# Question
Title: Particle system prefab not instantiated
I am trying to instantiate my fire particle system during runtime like this:

```
GameObject fire, firePrefab;

void Start()
{
    ...
    firePrefab = Resources.Load("FirePrefab") as GameObject;
}

void FixedUpdate()
{
   if (Input.GetKeyDown(KeyCode.V))
   {
       fire = Instantiate(firePrefab, transform.GetChild(3).position, transform.GetChild(3).rotation);
       Destroy(fire, 5.0f);
   }
}

```

My FirePrefab is just a regular particle system, and the model the above script is attached to looks like this:

> Model
>
> > Default
> >
> > Camera
> >
> > DroneFire

However, my fire prefab isn't instantiated anywhere when I run the game.

# Answer
`GetChild` is zero-based. to get the first object, "Default", you would call `GetChild(0)`. In your case, to get "DroneFire", you should call `GetChild(2)`, *not* `GetChild(3)` which will throw an exception before the instantiation can occur, because no such child exists. This exception should be fairly obvious in the console output. I would recommend looking in the console regularly when things don't work to find where things are failing.

```
fire = Instantiate(firePrefab, transform.GetChild(2).position, transform.GetChild(2).rotation)

```

As a side note, polling for input should generally not be done in `FixedUpdate`. Change to `Update` instead.
> 1 votes

---
Tags: unity, c#, particles, instancing
---


# Question
Title: C++ -- How could I create a list that contains functions, and would either run the top or iterate through and run all?
I'm not sure how to phrase this to be perfectly accurate to my goal implementation

I need a dynamic scene/menu system. I'm going to create a base class and inherit in two other classes specific to either rendering a scene or controlling a menu chain. From here I'll be creating functions with specific draw characteristics (such as a specific menu) and run them into my draw function.

What type of container system would work? I need it to be able to both run only the top and run all of the ones loaded in it (I specify because you cant iterate through a stack, from what I'm told)

# Answer
Using the STL, you can create a `vector` of function pointers.

To do that, as I guess you want to do something like `object->function()` you need all this functions to have the same prototype (parameters type and return type).

Then, you declare a function pointer type like this

```
<return_type> (<class_name>::*<type_name>)(<parameter_list>);

```

So, for example:

```
typedef void (MenuItem::*drawFuncType)();

```

Then, you just `#include <vector>` and then declare a vector like

```
std::vector<drawFuncType> funcVector;

```

And you fill it using `&draw1` for vector's insertion function.

If you had to do it for multiple classes, you can achieve this using templates for the class.

Hope it helps.
> 2 votes

---
Tags: c++, sdl, sdl2
---


# Question
Title: The difference between shading and data interpolation
Using methods like Phong you can make mesh look smooth and real. However you can do the same interpolation at the data level creating a surface (for example B-Spline surface).

What is the difference and when would you use shading over data interpolation?

# Answer
> 1 votes
Consider the fundamental difference between the two: Phong shading makes a mesh look smoother, but doesn't change the mesh itself whereas interpolating the surface with additional vertices does.

Thus, Phong shading allows you to get by with fewer polys, but can lead to certain artifacts. In particular, when you look at the profile, you still see the edges & if the poly count is too low, the profile appears blocky.

Interpolating the mesh will smooth out the profile, but increases the poly count. Also, unless coupled with decent shading, the individual facets may still be noticeable on curve. Because of this, the two are often used together to some degree.

As an example, consider the reference image from wikipedia:

You could add more polys to the image on the left, but it's still going to have something of a disco ball sort of a look due to the flat shading & it would take a lot of subdivisions to overcome that problem. The image on the right has a much smoother looking interior, but you can still see the straight edged outline because Phong shading doesn't change the mesh. Softening the outline would take more polys.

---
Tags: interpolation, shading, splines
---


title: InputField autocomplete

text:
# Question
Title: InputField autocomplete
I'm trying to make an InputField like the one shown below in Unity. I don't see any way I could do this in Unity. I also want to use google places autocomplete API.I am using Unity v5.6.1f1 .Is this possible?.

# Answer
> 1 votes
Here is a little script I made to give you an idea :

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

public class Autocomplete : MonoBehaviour
{
    public InputField inputField;
    public RectTransform resultsParent;
    public RectTransform prefab;

    private void Awake()
    {
        inputField.onValueChanged.AddListener( OnInputValueChanged );
    }

    private void OnInputValueChanged( string newText )
    {
        ClearResults();
        FillResults( GetResults( newText ) );
    }

    private void ClearResults()
    {
        // Reverse loop since you destroy children
        for( int childIndex = resultsParent.childCount - 1 ; childIndex >= 0 ; --childIndex )
        {
            Transform child = resultsParent.GetChild( childIndex );
            child.SetParent( null );
            Destroy( child.gameObject );
        }
    }

    private void FillResults(List<string> results)
    {
        for (int resultIndex = 0 ; resultIndex < results.Count ; resultIndex++)
        {
            RectTransform child = Instantiate( prefab ) as RectTransform;
            child.GetComponentInChildren<Text>().text = results[resultIndex];
            child.SetParent( resultsParent );
        }
    }

    private List<string> GetResults( string input )
    {
        List<string> mockData = new List<string>() { "Paris", "Madrid", "London", "Rome", "Brussels", "Athens", "Dublin", "Lisbon", "Amsterdam", "Luxembourg" };

        return mockData.FindAll( (str) => str.IndexOf( input ) >= 0 );
    }

}

```

Attach this script to the inputfield, drag & drop in the inspector the input field, a RectTransform with a `VerticalLayoutGroup` component (to layout correctly the results), and a Text prefab (or any UI component you want with a child containing a `Text` component).

Currently, you should replace the content of the `GetResults` so as to retrieve the results from your library. Since I don't know this library, you will have to do it on your own ;)

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


title: How to handle mixed input

text:
# Question
Title: How to handle mixed input
I'm aiming for the following design in my app, and I am having a difficulty figuring how this could be achieved.

The purple part will be the main part of the game, which I have actually already written, implementing InputProcessor. It uses touch controls for dragging (mainly) and touching down or up with the finger.

I didn't think of creating a HUD beforehand and now decided that a Stage would work perfectly for that, but it definitely wouldn't work with the above input method. Is there a way to split the screen into areas like in the diagram, and depending on touch location pass the touch events to either main game InputProcessor or to the Stage?

# Answer
> 1 votes
You can use an InputMultiplexer to combine 2 input processors. The multiplexer will accept stage as it is an inputProcessor which would be your GUI. You can then add your game's input processor as the second processor.

The second processor will only be triggered when the first input processor returns false indicating it has not handled the event and should be passed down the processor chain.

```
Stage myStage = new Stage(); // define your stage

// create multiplexer
InputMultiplexer multiplexer = new InputMultiplexer();
multiplexer.addProcessor(myStage); // set stage as first input processor
multiplexer.addProcessor(new MyGameInputProcessor());  // set your game input precessor as second
Gdx.input.setInputProcessor(multiplexer); // set multiplexer as input processor

```

---
Tags: libgdx, input
---