title: Unity block chunk generation pattern

text:
# Question
Title: Unity block chunk generation pattern
I am trying to do something like Minecraft game in Unity. Currently I am trying to generate a chunk of blocks, given dimensions. I can successfully create a chunk of N x 0 x 0 sized chunk, but due to lack of logic, I have no idea on how to make triangles and vertices match for other blocks.

Basically, what I mean is, I can generate something like this:

But can't do this:

My Block vertices and Triangles:

```
Vector3[] cVerts = {
        new Vector3 (0, 0, 0), //0
        new Vector3 (1, 0, 0), //1
        new Vector3 (1, 1, 0), //2
        new Vector3 (0, 1, 0), //3
        new Vector3 (0, 1, 1), //4
        new Vector3 (1, 1, 1), //5
        new Vector3 (1, 0, 1), //6
        new Vector3 (0, 0, 1), //7
    };
int[] cTris = {
        0, 2, 1, //face front
        0, 3, 2,
        2, 3, 4, //face top
        2, 4, 5,
        1, 2, 5, //face right
        1, 5, 6,
        0, 7, 4, //face left
        0, 4, 3,
        5, 4, 7, //face back
        5, 7, 6,
        0, 6, 7, //face bottom
        0, 1, 6
    };

```

Chunk creation method:

```
     void CreateChunk(){
        ...
        for (int x = 0; x < 100; x++)
        {
           for(int y = 0; y < 10; y++){
               for (int z = 0; z < 1; z++)
               {
                  AddBlockAtPosition(new VectorInt(x, y, z), "Grass");
               }
           }
        }

        ChunkMesh.vertices = CurrentChunkVerts.ToArray();
        ChunkMesh.triangles = CurrentChunkTris.ToArray();

        //ChunkMesh.uv = uvs.ToArray();
        ChunkMesh.RecalculateNormals();
   }

```

AddBlockAtPosition() method:

```
    void AddBlockAtPosition(VectorInt pos, string name)
    {
       int x = pos.x, y = pos.y, z = pos.z;

       //create separate cube data
       CubeMesh cube = new CubeMesh(vertices.ToArray(), triangles.ToArray(), uvs.ToArray());
       //I use MoveCube() to change each Block's vertex and triangle numbers, so they will "match" in a Chunk mesh, when they become part of it.
       cube.MoveCube(new Vector3(x, y, z), (x + y + z) * 8);
       //cube.MoveUV(new Vector2(x + y + z, x + y + z));

       CurrentChunkVerts.AddRange(cube.Vertices());
       CurrentChunkTris.AddRange(cube.Triangles());
       //CurrentChunkUV.AddRange(cube.UVs());
    }

```

And most importantly, that's where my problems are, MoveCube();

```
Class Cube{
    private Vector3[] vertices;
    private int[] triangles;
    ...
    public void MoveCube(Vector3 direction, int n)
    {
        for(int i=0; i<vertices.Length; i++)
        {
            vertices[i] += direction;
        }
        for (int i = 0; i < triangles.Length; i++)
        {
            triangles[i] = triangles[i] + n;
        }
    }
}

```

I know that I am not the first to re-create minecraft, I have found this tutorial https://www.blockstory.net/node/56

But for me as a beginner, some "simple" parts like these I have problems with are skipped. And other tutorials just generalize the idea, which isn't enough for me.

# Answer
> 7 votes
Remember, the whole point of using a chunk mesh is to try to render just the outside skin, and hide all the internal detail inside the chunk where we can't see it. If we generate a whole cube (all 12 triangles) at every occupied position, then we might as well spawn it as a separate mesh and at least hope GPU instancing saves us some work - otherwise we're both losing instancing AND rendering stuff we don't need, the worst of both worlds.

So, to minimize redundant geometry, we can do something a bit like this...

(Here I'm going to assume your chunks can be made of multiple materials, whose textures are stored as a texture array so we can use UVs over an arbitrary range and they'll tile correctly for us. This way when four faces of the same material meet, we only need 1 vertex, rather than 4 with different UV coordinates. (We can also do this in the shader math if texture arrays aren't available.)

First we define the characteristics we want to be the same at any shared vertex:

```
struct VertexSignature {
    int3 position,
    CardinalDirection normal,
    BlockMaterial material,
}

```

Now we can use this to de-duplicate vertices, referring back to the same index anytime our code asks for a vertex with the same characteristics:

```
Dictionary<VertexSignature, int> _vertexLookup = new Dictionary...
int _vertexCount = 0;

int GetVertexIndex(VertexSignature signature) {
    int index;
    if(!_vertexLookup.TryGetValue(signature, out index) {
        index = _vertexCount++;
        _vertexLookup.Add(signature, index);
    }
    return index;
}

```

Next we can iterate over all the spots in our chunk, to see which blocks need to produce faces (I'm going to be a bit loose & pseudocode-y for brevity):

```
foreach(int3 position in chunk.Bounds) {
    // I assume ultimately you'll have some type of data structure that records
    // the current block at each position, whether the product of a terrain generator
    // or player mining/building, etc.
    var block = World.GetBlockAt(position);

    // If this block is empty air, we don't need to draw any faces for it.
    if(block.type == BlockType.Empty)
        continue;

    // Otherwise, we check if this block is exposed on any face.
    foreach(CardinalDirection direction in Neighbourhood) {
        var neighbour = World.GetBlockAt(position + direction);

        // If the block is occluded on this side, we don't need to draw
        // the faces in between the two blocks.
        if(neighbour.type != BlockType.Empty)
            continue;

        // Otherwise, we've found an exposed face. Add it to the list.
        AddFace(position, direction, block.type);
    }
}

```

To add each face, we just look up the corresponding position offsets we want for each vertex for a face on that side of the cube, request an index for each resulting vertex, and add those indices to our growing list.

```
List<int> _indices;

void AddFace(int3 position, CardinalDirection direction, BlockMaterial material) {
    // Have a table or map that lets you quickly look up the 4 vertex offsets
    // from the cube's bottom-left-back corner for a given face direction.
    int3[] vertexPositions = GetVertexPositions(direction);

    VertexSignature signature;
    signature.normal = direction;
    signature.material = material;

    signature.position = position + vertexPositions[0];
    int a = GetVertexIndex(signature);

    signature.position = position + vertexPositions[1];
    int b = GetVertexIndex(signature);

    signature.position = position + vertexPositions[2];
    int c = GetVertexIndex(signature);

    signature.position = position + vertexPositions[3];
    int d = GetVertexIndex(signature);

    _indices.Add(a);
    _indices.Add(b);
    _indices.Add(c);

    _indices.Add(a);
    _indices.Add(c);
    _indices.Add(d);
}

```

Lastly, once we've visited every block and added all the indices we need, we can bake down our vertex signatures into the corresponding arrays for positions, normals, and UVs...

```
vertices = new Vector3[_vertexCount];
normals = new Vector3[_vertexCount];
uvs = new Vector3[_vertexCount];

foreach(var pair in _vertexLookup) {
    int index = pair.value;
    vertices[index] = pair.key.position;
    normals[index] = (Vector3)pair.key.normal;

    Vector3 uv = ProjectPositionToUV(pair.key.position, pair.key.normal);
    uv.z = pair.key.material.index;

    uvs[index] = uv;
}

```

From here you've got all the ingredients you need to build a mesh of arbitrary shape & size, with shared vertices and no internal faces. Note that since we've only been using basic types & math above, all of this can be done on a separate thread, leaving only the final assembly of these buffers into the `Mesh` instance and uploading to the GPU for the main thread to handle.

The simple method shown here still produces some redundant faces & vertices: a long rectangular plane of the same material could just be two faces instead of `length * width * 2`, but that's a further optimization we can tackle separately. This Q&A thread and linked article goes into more detail about merging coplanar quads this way.

---

Here's one way you could implement the texture mapping function:

```
Vector2 ProjectPositionToUV(int3 position, CardinalDirection normal) {
    switch(normal) {
        case CardinalDirection.Up:
        case CardinalDirection.Down:
             return new Vector2(position.x, position.z);
        case CardinalDirection.East:
        case CardinalDirection.West:
             return new Vector2(position.z, position.y);
        case CardinalDirection.North:
        case CardinalDirection.South:
             return new Vector2(position.x, position.y);
    }
    // Fallback for an invalid input direction.
    return Vector2.zero;
}

```

---
Tags: unity, voxels, mesh, procedural
---


title: Item functionality with database

text:
# Question
Title: Item functionality with database
So the game i'm making will have items with different functionality such as ammo boxes, med-packs, guns, food, water ect. My problem is i don't know where to put the code for the specific functionality e.g code for eating food.

My item system works by having a database (dictionary with a string and item stats) and an inventory list of strings. When using a item i look up the stats of that item using the string in the inventory list.

One idea i had was to have scrips on the player something like heal, ammo, gun ect, and have methods in those scrips for the functionality. Is this a good way of doing it?

# Answer
> 0 votes
Part of an item's stats can include a reference to the *behavior* of the item when it is consumed or used. This can be represented in the item's structure as a delegate/function pointer/closure/et cetera based on language.

In C#, you could do it with an `Action` delegate. So your item structure would look like:

```
class Item {
  int value;
  int weight;
  // ...other stats...

  Action<Item, Character> onUseEffect;
};

```

`onUseEffect` is a (possibly-null) reference to a function that takes an `Item` and a `Character`, which at runtime will be the item being used and the character using the item, respectively. You can naturally have more (or fewer) parameters as needed.

So now, when using an item you look up it's `Item` object as you do now to get the stats of the item. And if that `Item` has a non-null `onUseEffect`, you call that function:

```
void UseItem(string name) {
  Item item = m_itemDatabase[name]; // look up the item...
  if (item.onUseEffect != null) {
    item.onUseEffect(item, thisCharacter);  // use the item...
  }
}

```

You'd bind these actions when you create each item in the database:

```
Item potionItem = new Item();
// ...other initialization...
potionItem.onUseEffect = (item, user) => {
  // Potions heal 50 HP for the user.
  user.Health += 50;
};

m_itemDatabase.Add("Potion", potionItem);

```

All of this allows you to define your item behavior in code without having to subclass `Item` for each new type or behavior. It's also a useful building block towards allowing your item's behavior to be defined *in scripts* (the `onUseEffect` delegate simply becomes a call to the item's script), as you proposed in your question. Using scripts (e.g., data) to describe the behavioral effects of your items is a good idea in general, although it might be overkill depending on the size of your game and data set. And whether or not you already have a scripting mechanism built.

---
Tags: unity, design-patterns, inventory
---


title: Unity override Coroutine Loop

text:
# Question
Title: Unity override Coroutine Loop
I have problem, when i override a Coroutine loop from the base code. But it seems that it only execute once. While on the base code it does what it suppouse to do and that is execute forever.

```
protected virtual IEnumerator OnThink(float interval)
{
    while (true)
    {
        yield return new WaitForSeconds(interval);
    }
}

protected override IEnumerator OnThink(float interval)
{
    Debug.Log("Execute");
    yield return StartCoroutine(base.OnThink(interval));
}

```

# Answer
> 1 votes
The base method `IEnumerator OnThink`you are overriding, overriding means you want to implement all the logic yourself instead of what the method class provides

```
//base
protected virtual IEnumerator OnThink(float interval)
{

    while (true)
    {
        yield return new WaitForSeconds(interval);
    }
}

//so this function is now overridden meaning it has no logic
//unless you add it or call the base
//to make it work like the base implementation you just add the while loop
protected override IEnumerator OnThink(float interval)
{
    while(true)
    {

    Debug.Log("Execute");
    yield return StartCoroutine(base.OnThink(interval));
    }
}

```

This particular while loop will run forever since true always will equal true.

while(true) is short for hand for while(true == true) so will run forever, if you add your own boolean for example

```
bool canThink = false;

```

then use that instead of true = true like so

```
    private bool canThink = false;

    protected virtual IEnumerator OnThink(float interval)
   {
     while (true)
     {
        yield return new WaitForSeconds(interval);
     }
    }

protected override IEnumerator OnThink(float interval)
{
   //for every X interval if canthink is true run the code inside the loop
   while(canThink == true)
   {
    Debug.Log("Execute");
    //we also just call yield return new WaitForSeconds ourselves
    //in this case there isnt much point in calling the base method.
    yield return new WaitForSeconds(interval);
   }
}

```

This way you control the flow of the logic, you can stop and start it just by changing `canThink` \- **bare in mind you probably don't want to be calling base in your case as a infinite loop inside a infinite loop will either crash or slow things down a fair bit.**

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


# Question
Title: prevent animation from moving the character
As stated in the question I've this problem: I'm using Unity and when playing an animation my character moves from point A to point B without my consent. Here's the code:

```
public class Walk : MonoBehaviour {

    private Animator humanAnimator;
    private iInputProvider input;

    private void Start()
    {
        input = new KeyBoardInput();
        humanAnimator = GetComponent<Animator>();
        walkMe = GetComponent<Rigidbody>();
    }

    private void FixedUpdate()
    {
        walk();
    }

    private void walk()
    {
        InputWrapper inputWrp = input.GetInputValues();

        animateWalk(inputWrp.verticalMove);
    }

    private void animateWalk(float verticalMove)
    {
        if (-0.1 <= verticalMove && verticalMove <= 0.1) //stand still
        {
            humanAnimator.SetBool("Walk", false);
            Debug.Log(humanAnimator.GetBool("Walk"));
        }
        else if (verticalMove > 0.1) // animate walk forward if the player is walking forward
        {
            humanAnimator.SetBool("Walk", true);
            Debug.Log(humanAnimator.GetBool("Walk"));
        }
        else if (verticalMove < -0.1)
        {
            // walk backward animation needed
        }

    }
}

```

Note that nowhere in the code I change the object position, i just start the animation. Here's the result:

https://i.stack.imgur.com/vYDvT.jpg

note that it's not the effect of the gif, the character actually resets its position after the animation is terminated. I was expecting the character to "run on the place". Anybody has some idea how can I fix this?

EDIT: if I uncheck the "Apply root motion" check box I've this result: https://i.stack.imgur.com/ouZxp.jpg . Maybe it could be useful to know that I can't click on "Generate root motion curve" in my animation inspector because it's all uneditable: https://i.stack.imgur.com/Lsd9W.jpg

# Answer
> 3 votes
There is an option on the Animator Component called `"Apply Root Motion"` this basically asks if you want the animation itself to control character motion(true, checked) or handle it yourself (false, unchecked), In your case you likely want it disabled.

for extra information on the Animator Component

If you end up on this question from google and the above doesn't help and you've also got your animations from Mixamo try re-downloading the animation with "In Place" ticked, if not ticked it applies root motion that unity cannot override.

---
Tags: unity, animation, movement
---


# Question
Title: How can I stop rigidbody velocity from being overridden?
I have two behaviors on my player. "Walk" and "Dodge". Individually they work as intended by altering the players Rigidbody.velocity. However trying to dodge while holding left or right will trigger "Dodge" then "Walk" will over ride the change since you're holding left or right.

"Walk Script" within the update loop If you press left or right

```
_body2D.velocity = new Vector2(speed * direction, _body2D.velocity.y);

```

"Dodge Script" within the update loop If you press the dodge input it will move the player the opposite direction their facing.

```
_body2D.velocity = new Vector2( - (speed * direction), _body2D.velocity.y);

```

if you hold left or right while pressing the dodge input it will dodge in the direction you're pressing.

```
_body2D.velocity = new Vector2(speed * direction, _body2D.velocity.y);

```

I've tried changing the script execution order to prioritize the Dodge behavior over Walk. I've tried disabling the walk script during the animation with the following method.

```
ToggleScripts(!_animator.IsInTransition(0));

protected void ToggleScripts(bool value)
{
    foreach (var script in disabledScripts)
        script.enabled = value;
}

```

# Answer
> 2 votes
The Rigidbody.velocity's documentation in Unity specifically does not recommend that you modify the velocity vector, since you may override previous acceleration forces applied. Back then, since I didn't understand how Rigidbodies worked, I had different approaches:

* An approach where I had a VelocityAccumulator component class, where I applied all the accelerations vectors desired to be applied at the end of each frame.
* Have a vector that stores all the applied accelerations and apply it to the velocity at the end of frame.

**Example of the approach 1:**

```
[RequireComponent(typeof(Rigidbody))]
public class VelocityAccumulator : MonoBehaviour
{
    private Rigidbody rigidbody;
    private Vector3 velocity;

    void Awake()
    {
        rigidbody = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        if(rigidbody.useGravity) velocity += Physics.gravity;
        rigidbody.velocity = velocity;
        velocity = Vector3.zero;
    }

    public void AddAcceleration(Vector3 acceleration)
    {
        velocity += acceleration;
    }
}

```

**Example of approach 2:**

```
public class Example : MonoBehaviour
{
    Vector3 currentVelocity, jumpForce, movementForce;
    bool walk, jump;

    void Update()
    {
        if(jump) currentVelocity += jumpForce;
        if(walk) currentVelocity += movementForce;
        GetComponent<Rigidbody>().velocity = currentVelocity;
        currentVelocity = Vector3.zero;
    }
}

```

Which, turns out that at the end, the best solution is to use **Rigidbody.AddForce**, which does the same thing, and its already built-in. Just take note that the movement will be relative to the mass, so you'll have to either tweak the mass or multiply the force by the mass.

Hope it helps.

# Answer
> 1 votes
Best way i can think of doing it would be to have the "Walk" and "Dodge" scrips be one "Movement" scrip.

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

public class Movement : MonoBehaviour {

public bool is_Dodgeing = false;

// Update is called once per frame
void Update () {
    if(Input.GetButtonDown("Walk") && !is_Dodgeing)
    {
        //Walk code
    }

    if(Input.GetButtonDown("Dodge"))
    {
        is_Dodgeing = true;
        //Dodge code
        //Make sure to set is_Dodgeing to false when done with Dodge code
    }
  }
}

```

---
Tags: unity
---


title: Sun model matrix

text:
# Question
Title: Sun model matrix
I'm playing with sun implementation in my engine and I correctly built model matrix using below order of matrix operations:

1. Translate to camera position.
2. Calculate x and y axis of rotation matrix using cross product. Z axis is equal to sun direction.

However I'd like to use function which takes into account two unit vectors and based on them build rotation matrix (explanation here). When I replace 2nd step with function call the sun is in completely different position on the sky (but correctly oriented). As a input vectors I set direction vector and \[0, 1, 0\] vector.

Could someone provide a solution/hint/explanation of that topic?

**Code**

Working solution:

```
Matrix matrix; matrix.setPosition(ActiveCamera.getInversedMatrix().pos);

Vector xaxis = Cross(Vector(0,1,0), direction);
xaxis.normalize();

Vector yaxis = Cross(direction, xaxis);
yaxis.normalize();

matrix.x.x = xaxis.x;
matrix.y.x = yaxis.x;
matrix.z.x = direction.x;

matrix.x.y = xaxis.y;
matrix.y.y = yaxis.y;
matrix.z.y = direction.y;

matrix.x.z = xaxis.z;
matrix.y.z = yaxis.z;
matrix.z.z = direction.z;

```

Not working solution:

```
Matrix matrix; matrix.setPosition(ActiveCamera.getInversedMatrix().pos);
matrix.setRotation(Vector(0, 1, 0), direction);

Matrix3& Matrix3::setRotation(const Vector &u, const Vector &v) {
    Vector cross = Cross(u, v);
    float sin = cross.magnitude(); // sine of angle
    cross.normalize();
    float cos = Dot(u, v); // cosine of angle

    this->x.x = cross.x * cross.x * (1 - cos) + cos;
    this->x.y = cross.x * cross.y * (1 - cos) + sin * cross.z;
    this->x.z = cross.x * cross.z * (1 - cos) - sin * cross.y;

    this->y.x = cross.x * cross.y * (1 - cos) - sin * cross.z;
    this->y.y = cross.y * cross.y * (1 - cos) + cos;
    this->y.z = cross.y * cross.z * (1 - cos) + sin * cross.x;

    this->z.x = cross.x * cross.z * (1 - cos) + sin * cross.y;
    this->z.y = cross.y * cross.z * (1 - cos) - sin * cross.x;
    this->z.z = cross.z * cross.z * (1 - cos) + cos;

    return (*this);
}

```

# Answer
The code was ok. Start direction depends on the sun quad coordinates. I changed it to \[0, 0, 1\] and I got expected result. I also moved the sun quad by its direction. Otherwise I was unable to scale it.
> 1 votes

---
Tags: opengl, rendering, matrix
---


# Question
Title: How do games implement client/server frame rate?
Do games have a frame rate at X fps that updates logic and also renders?

Or do games update logic at a much slower frame rate than rendering? Let's say 20-25 fps for logic, and 60+ fps for rendering.

I am writing a game engine and I am a bit confused on how frame rate is handled.

If I were to run logic slower than rendering, then wouldn't I just be wasting the rendering frames because it is rendering the same thing over and over...? Unless I also interpolate the rendering with a delta.

I have read some game servers run at a much slower frame rate (let's say 20 FPS), so shouldn't the client also run logic at 20 FPS?

# Answer
I have also read the same (that game servers run their logic at a slower frame rate). And Ubisoft was also telling people that if you use 30 fps and add some motion blur we can call our gameplay cinematic.

As you can see from the example below, the 60 fps ball (blue) looks much smoother than the 20 fps ball (red). Even though both balls are rendering at 60 fps, the red ball looks very jerky because it stays in the same position for three frames, then changes position by three times the amount. This results in a jerky, blurred appearance compared to the blue ball.

Here's the simple example talked about earlier:

```
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');

var width = canvas.width;
var height = canvas.height;

function gameObject(color, startY) {
  this.x = 0;
  this.y = startY;
  this.color = color;
  this.update = function() {
    // Reset the ball back to the left if it's over the right edge.
    if (this.x > width) {
      this.x -= width;
      // The blue ball gets a 4-pixel head start each time it crosses, so cheat for red to keep them aligned.
      if (this.color == 'red') {
        this.x += 4;
      }
      // Just increment the position appropriately if the ball is still in the frame.
    } else {
      if (this.color == 'red') {
        this.x += 6;
      } else {
        this.x += 2;
      }
    }
  };
  this.render = function() {
    ctx.fillStyle = this.color;
    ctx.clearRect(this.x - 14, this.y - 14, 28, 28);
    ctx.fillRect(this.x, this.y, 14, 14);
  };
}

// Objects will run at 20 and 60 fps respectively
var ball20 = new gameObject('red', 170);
var ball60 = new gameObject('blue', height - 170);

var counter = 0;
// Runs at 60 fps
function frame60() {
  // Reset the counter every three frames.
  if (counter == 3) {
    counter = 0;
  }

  // Update the 60fps ball every frame.
  ball60.update();

  // Only update the 20fps ball every 3rd frame.
  if (counter == 2) {
    ball20.update();
  }

  // Render both balls each frame.
  // The 20fps ball will render in the same place 3 frames in a row.
  ball20.render();
  ball60.render();
  requestAnimationFrame(frame60);

  // Update the counter at the end so the blue ball doesn't get a 2-frame head start.
  counter++;
}

//physicsFrame();
frame60();
```

```
canvas {
  border: 1px solid black;
  border-width: 0 1px 0 1px;
}
```

```
<canvas id="game" width="340" height="250"></canvas>
```
> 1 votes

---
Tags: game-loop, client-server, frame-rate
---


title: Timestep with multithreading

text:
# Question
Title: Timestep with multithreading
There are several questions and articles which deal with timestep - for example:

Although that last one started to get into it in the comments - I still have an unanswered question about how to architect for a multithreaded system.

Given two threads:

1. State Worker : simply does pure transformations on data.
2. IO Renderer : Deals with input, and renders the latest available State object

Let's say the state-worker thread simply updates the game state in a continuous loop, while the renderer updates the screen on a fixed timestep (e.g. 60fps).

Let's ignore input for now.

The renderer does its job by taking the freshest data it has, which was passed in from the state-worker whenever it was finished (which may have happened dozens of times between renders.)

It seems to me like this would be the smoothest solution and it's extremely simple (no interpolation other than reading the delta time between state updates - irrespective of render updates).

Although very minor - and I said we can ignore input, it also gives a tiny bit more snappyness since it polls the input and syncs it with the game state updates which would happen far more frequently in this case vs. basing it on render ticks (at least for simple games).

What are the flaws with this idea? Or is it solid?

# Answer
> 1 votes
I do see one flaw, your update worker (aka State Worker) will need input information to make the right updates. How can you update the player's position if you do not know that the player has moved. You would then be running collision tests on out-of-date data (See this image from IBM's tutorial on making a web game). Syncing the game state with the input state after updating said state will be difficult.

I think you should have a worker for your game's logic and another for all things to do with rendering. Rendering at a lower frame rate than the update, since rendering usually eats up the most processing time.

---
Tags: game-loop, multithreading, timestep, fixed-timestep
---


# Question
Title: Why I cant change the GUILayout.Button color to green when click on a button?
I used a break point and it's getting to the line:

```
style.normal.textColor = Color.green;

```

But not changing the color of the clicked button. And there are no any errors or exceptions.

```
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEditor;
using UnityEngine;
using System.IO;

public class Manager : EditorWindow
{
    [MenuItem("Tools/Manager")]
    static void Manage()
    {
        EditorWindow.GetWindow<Manager>();
    }

    private void OnGUI()
    {
        var style = new GUIStyle(GUI.skin.button);
        style.normal.textColor = Color.red;
        style.fontSize = 18;

        string[] assetPaths = new string[2];
        string[0] = "Test";
        string[1] = "Test1";

        foreach (string assetPath in assetPaths)
        {
            if (assetPath.Contains(".test")
            {
                var i = assetPath.LastIndexOf("/");
                var t = assetPath.Substring(i + 1);

                if (GUILayout.Button(t, style, GUILayout.Width(1000), GUILayout.Height(50)))
                {
                    style.normal.textColor = Color.green;
                }
            }
        }
    }
}

```

# Answer
> 1 votes
Edit : Removed an incorrect answer updated with hopefully a correct one.

It turns the solution is pretty simple

```
    style = new GUIStyle(EditorStyles.toolbarButton);
    //the color if the button is pressed
    style.active.textColor = Color.red;
    //the default color
    style.normal.textColor = Color.green;

    style.fontSize = 18;

```

The full code

```
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEditor;
using UnityEngine;
using System.IO;

public class Manager : EditorWindow
{
    [MenuItem("Tools/Manager")]
    static void Manage()
    {
        EditorWindow.GetWindow<Manager>();
    }

    private void OnGUI()
    {
        var style = new GUIStyle(GUI.skin.button);
        style.normal.textColor = Color.red;
        style.active.textColor = Color.green;
        style.fontSize = 18;

        string[] assetPaths = new string[2];
        string[0] = "Test";
        string[1] = "Test1";

        foreach (string assetPath in assetPaths)
        {
            if (assetPath.Contains(".test")
            {
                var i = assetPath.LastIndexOf("/");
                var t = assetPath.Substring(i + 1);

                if (GUILayout.Button(t, style, GUILayout.Width(1000), GUILayout.Height(50)))
                {
                                        }
            }
        }
    }
}

```

Also worth noting but not related to answering your question is `EditorStyles` is full of useful Unity styles you can apply to elements.

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


# Question
Title: How to "amplify" a force and physic using AddForceAtPosition?
I have the object in the image.

The red box is kinematic: when an object hit it , i set kinematic to false, so Unity apply normal physic.

But I would like to apply also a force to the point indicated by the violet cross.

So I'm using Rigidbody.AddForceAtPosition

```
_rb.AddForceAtPosition (ForceDirection * ForcePower, PointForcePosition.transform.position, ForceType);

```

PointForcePosition is an empty GameObject child of the red box object, placed where violet cross is pointing.

My question are:

1. Force Position: can I use that approach (an empty gameObject placed where i want to apply force ) ?
2. Force Direction: is it corret a Vector3 ( 0 , -1 , 0 ) to indicate a down force
3. Which ForceMode is the best for my purpose ? Impulse ? Force ?

Thanks

# Answer
> 1 votes
Since the image is not showing I may not be understanding properly what you're asking but here's my best crack at your questions:

> Force Position: can I use that approach (an empty gameObject placed where i want to apply force ) ?

If the purpose of the object is just to store a transformed position there's other options, but your way is fine (especially if you want to tweak its position in the editor).

> Force Direction: is it corret a Vector3 ( 0 , -1 , 0 ) to indicate a down force

That depends on what conventions you're using for your coordinates but down being the negative y axis is very common.

> Which ForceMode is the best for my purpose ? Impulse ? Force ?

The difference between the two can be confusing but `Impulse` is effectively 'per frame' and `Force` is 'per second'. Roughly speaking, `Impulse` is better when you're applying a force over time (e.g. you're adding the effect of a rocket engine every frame) and `Force` is better for 'instant' effects (e.g. an explosion). From what you describe `Force` seems a better fit.

---
Tags: unity, physics
---


# Question
Title: Loading texturecube using DirectXTK DDSTextureLoader
I've been trying to implement a skybox for some time now and there's probably only a tiny problem left to solve. When I load a texture using DirectXTK's CreateDDSTextureFromFileEx with a TEXTURECUBE flag, the resulting shader resource has its view dimension set to Texture2D and not TextureCube, which means I can't treat it as a TextureCube in HLSL. Also the file I'm loading contains all six faces. Here's the code where the texture is loaded:

```
// Loading the texture
HRESULT hr = DirectX::CreateDDSTextureFromFileEx(device, filename, 0, D3D11_USAGE_IMMUTABLE, D3D11_BIND_SHADER_RESOURCE,
    0, D3D11_RESOURCE_MISC_TEXTURECUBE, false, &texture, &mSkyboxSRV);

```

This is the error message being output by DirectX:

D3D11 ERROR: ID3D11DeviceContext::Draw: The Shader Resource View dimension declared in the shader code (TEXTURECUBE) does not match the view type bound to slot 0 of the Pixel Shader unit (TEXTURE2D). This mismatch is invalid if the shader actually uses the view (e.g. it is not skipped due to shader code branching). \[ EXECUTION ERROR #354: DEVICE\_DRAW\_VIEW\_DIMENSION\_MISMATCH\]

I've also tried this:

```
ID3D11Texture2D* texture = nullptr;

HRESULT hr = DirectX::CreateDDSTextureFromFileEx(device, filename, 0, D3D11_USAGE_IMMUTABLE, D3D11_BIND_SHADER_RESOURCE,
0, D3D11_RESOURCE_MISC_TEXTURECUBE, false, (ID3D11Resource**)&texture, nullptr);

D3D11_TEXTURE2D_DESC texDesc;
texture->GetDesc(&texDesc);

D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;

srvDesc.TextureCube.MipLevels = texDesc.MipLevels;
srvDesc.TextureCube.MostDetailedMip = 0;
srvDesc.Format = texDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;

hr = device->CreateShaderResourceView(texture, &srvDesc, &mSkyboxSRV);

```

But that gives me an error message saying the texture's view dimension and the srv's view dimension are not the same:

D3D11 ERROR: ID3D11Device::CreateShaderResourceView: Resources created without D3D11\_RESOURCE\_MISC\_TEXTURECUBE may not be treated as cubemap ShaderResourceViews. \[ STATE\_CREATION ERROR #126: CREATESHADERRESOURCEVIEW\_INVALIDDESC\]

Does anyone have any ideas on what to do? Any help is much appreciated!

# Answer
> 1 votes
When trying to debug failing `DDS` loads, you should do the following:

* Verify the DDS contains what you think it should. See DDSDump.cpp as a useful first-step.
* If you are getting a `SUCCESS` HRESULT back from the loader, then use the `ID3D11Resource**` parameter and use the code on the wiki to validate it is what you think it should be.
* Otherwise, step into the DDSTextureLoader code line-by-line to see where it is failing...

**UPDATE**: As of the August 2018 release of *DirectX Tool Kit*, if you call `CreateDDSTextureFromFileEx` with the `D3D11_RESOURCE_MISC_TEXTURECUBE` flag in the parameters -and- the `DDS` contains a 2D texture array with a multiple of six entries, then I'll pass it along as if it's a cubemap.

See this commit

---
Tags: directx
---


# Question
Title: Can I use information from a science book and mention it in bibliography without copyright problems?
I'm making an educational game to study some science topics. I want the users to know that the information in my game is real. Can I use a science book and mention it in the bibliography? Of course I will not copy / paste, I will only paraphrase some concepts.

# Answer
I Am Not A Lawyer But this is my understanding of how copyright law (in jurisdictions that I'm aware of) generally works here:

Copyright protects a document. It does not protect the factual ideas in a document. Therefore, you can learn the details of some scientific topic from a book, and afterwards write your own explanation of that topic in your game based on your new knowledge.

They may end up looking similar, since both the book and your game are describing the same real-world phenomena. But if the game is truly a separately written description of those scientific concepts rather than a paraphrasing of the contents of the book, then the game will not be a derivative work of the book under copyright law and so you don't need any particular permission from the book's author to distribute it.

If you sit down with the book open and transcribe sections of it into your game, paraphrasing it into your own words, then in my understanding it probably would be considered a derivative work (even though you have changed the words).

Of course, the difference between "these merely look similar because they're explaining the same topics" and "this is a heavily rewritten copy of that" can be quite a fuzzy line, difficult to objectively test. It's always *possible* that the copyright holders of the book think you have violated their copyright and are willing to take you to court over it. I have no idea exactly what standards a court might use to try to rule one way or another, but this would likely be an expensive disaster regardless of whether you really did copy their work (it's also likely to be expensive for them, so who can say how likely a possibility this really is). My personal standard would be to make sure I understand the topic well enough (probably from *more than one* source) that I can write an explanation myself without really needing to refer to the book, and then use the book to double check the details *after* I had fully written my first draft. Also, using more than one source might make it easier to make sure you're relying only on the scientific concepts, not on the particular presentation of those concepts in the one book.

Assuming you manage to make a game that is legally not a derivative work of the book, then listing the book as a source is essentially a courtesy that is unrelated to copyright. As I understand it, naming the book as your source could never make an infringing document okay nor make an otherwise original work count as a derivative.
> 2 votes

# Answer
Imagine if you were making bold statements, about any subject, and people asked for references. Your information would not seem credible if you said:

> I can't say they book, because the book doesn't allow me

I am not a lawyer, but books, articles, papers, etc, are released to the public, therefore you can mention then, as source. It's an obvious YES to me, you can reference the sources without copyright infringement.
> 1 votes

---
Tags: copyright
---


# Question
Title: Efficiently drawing large numbers of small, moving squares to screen in libgdx
I'm trying to make a game which behaves somewhat like The Powder Toy. The world is square and can be filled with particles. Particles are drawn as small squares, constrained to integer positions, and stored in a 2D array, similar to the GOL. Here's what the world looks like:  I've tried a few different approaches of drawing particles to the screen:

* Using a ShapeRenderer by calling setColor and rect for each particle. Seems to have been the slowest of the approaches.
* Using a SpriteBatch to draw a Pixmap for each particle.
* Writing asynchronously to a Pixmap, storing the Pixmap in a Texture, then drawing the Pixmap with a SpriteBatch.

Although these approaches work, I'd be interested in hearing about other, possibly more efficient ways to render the particles. Could VBO be used here? Or is it not accessible from within gdx?

# Answer
After pilfering through some of the information on the LIBGDX documentation pages, I stumbled across something called a mesh, which looked promising. This page provided further information about drawing primitive shapes using meshes. By combining what I had learned from the two above sources, I was able to draw the points much more efficiently using GL\_POINT to draw the mesh. Here's a file that you might copy to test this out and understand the approach:

```
package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.MathUtils;

import static org.lwjgl.opengl.GL11.glEnable;
import static org.lwjgl.opengl.GL32.GL_PROGRAM_POINT_SIZE;

public class MyGdxGame extends ApplicationAdapter {
    private static final int NUM_POINTS = 100_000;
    private OrthographicCamera camera;
    private Mesh mesh;
    private ShaderProgram shader;
    private int values_per_vertex;

    @Override
    public void create() {
        camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        camera.update();

        mesh = new Mesh(true, NUM_POINTS, 0, new VertexAttribute(VertexAttributes.Usage.Position, 2, "a_position"),
                new VertexAttribute(VertexAttributes.Usage.ColorUnpacked, 3, "a_color"));

        values_per_vertex = 2 + 3; // corresponds with the values given to the VertexAttribute constructor for size

        final String vertex_shader = "attribute vec2 a_position;\n" +
                "attribute vec3 a_color;\n" +
                "varying vec3 v_color;\n" +
                "uniform mat4 u_proj;\n" +
                "void main() {\n" +
                "   v_color = a_color;\n" +
                "   gl_Position = u_proj * vec4(a_position, 0.0, 1.0);\n" +
                "   gl_PointSize = abs(sin(a_position / 200)) * 10;" +
                "}\n";
        final String fragment_shader = "varying vec3 v_color;" +
                "void main() {\n" +
                "   gl_FragColor = vec4(v_color, 1.0);\n" +
                "}";

        ShaderProgram.pedantic = true;
        shader = new ShaderProgram(vertex_shader, fragment_shader);
        System.out.println(shader.getLog());

        glEnable(GL_PROGRAM_POINT_SIZE); // allow the vertex shader to specify the size of the point
        // glPointSize(int x); can be used if you don't want to define the size per-point
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        // generate an array of information about each vertex to be passed to the mesh and then the shader
        final float[] vertices = new float[NUM_POINTS * values_per_vertex];

        for (int i = 0; i < NUM_POINTS * values_per_vertex; i += values_per_vertex) {
            // x value should be within the valid x range for the camera
            vertices[i] = (int) MathUtils.random(-Gdx.graphics.getWidth() / 2f, Gdx.graphics.getWidth() / 2f);
            // same idea with the y value
            vertices[i + 1] = (int) MathUtils.random(-Gdx.graphics.getHeight() / 2f, Gdx.graphics.getHeight() / 2f);
            // r component of color
            vertices[i + 2] = MathUtils.random();
            // g component of color
            vertices[i + 3] = MathUtils.random();
            // b component of color
            vertices[i + 4] = MathUtils.random();
        }

        final long start = System.nanoTime();
        mesh.setVertices(vertices); // send our array of vertex information to the mesh

        camera.viewportWidth = Gdx.graphics.getWidth();
        camera.viewportHeight = Gdx.graphics.getHeight();
        camera.update();

        shader.begin();
        shader.setUniformMatrix("u_proj", camera.combined); // use the camera's perspective when drawing
        mesh.render(shader, GL20.GL_POINTS); // draw the points in the mesh
        shader.end();

        System.out.println("transfer and render took: " + (System.nanoTime() - start) / 1e9 + " s");
    }

    @Override
    public void dispose() {
        mesh.dispose();
    }
}

```

Here's an image of the output:

When using this method and changing vertex locations each frame, I've found the majority consumer of time per-render to be the population of the vertex array which is sent to the GPU for rendering. Even for 1,000,000 points, my mid-range graphics card can chug them out in under 16 ms, but the CPU struggles mightily to populate an array of 5,000,000 floats in a short (under 16 ms) amount of time. It seems that any 'optimizations' of this approach would do best to focus on the population of the vertex array.
> 1 votes

# Answer
I've also had the same problem recently and the way I did it, is similar to what you've already listed there. Let's take this as example:

```
final int scale = 4;
final int width = 600 / scale;
final int height = 400 / scale;
// Called only once in the beginning
public void setup()
{
    int[][] arrayOfPixels = new int[width][height];
    for(int x = 0; x < width; x++)
    {
        for(int y = 0; y < height; y++)
        {
            arrayOfPixels[x][y] = -1;
        }
    }
}

// Called every frame
public void render()
{
    for(int x = 0; x < width; x++)
    {
        for(int y = 0; y < height; y++)
        {
            if(arrayOfPixels[x][y] == -1)
                continue;

            shapeRenderer.setColor(arrayOfPixels[x][y]);
            shapeRenderer.rect(x * scale, y * scale, scale, scale);
        }
    }

    // Do whatever updating the pixels need to do.
    // If you want you can also replace the int
    // array with an array of something else that
    // contains the color of the pixel
}

```

What this does is it keeps the pixel type of rendering but keeps it lightweight because of the scale. It'll look as it's single pixel but it'll run `(scale * scale)` times faster.
> 0 votes

# Answer
I've had good luck with using one FrameBuffer per chunk. Then I draw to the FrameBuffer with 1-pixel sprites or ShapeRenderer. That way you can mark chunks as dirty and only update them as needed. Or limit the number of chunks updated per frame.
> 0 votes

---
Tags: java, libgdx, particles
---


# Question
Title: How can I use a redundant axis of rotation to prevent gimbal-lock & calculate a position for that axis?
I have a theodolite-like device that is trying to track a point such that it's "Forward" is always facing that point.

Here is a GIF of it working as of now.

As expected, when the value of the Red Angle is near 90 or 270 it may approach a gimbal-lock situation.

How would I be able to calculate a position for the currently unused Blue axis to prevent the Red/Green axis's from aligning that way?

Main Loop:

```
    public void Main(string argument, UpdateType updateSource)
    {
        float pitch, yaw;
        GetOrientationTo(target, origin, out pitch, out yaw);

        UpdateSteeringVectors();
        // Update yaw to the Green rotor
        UpdateRotor(r_green_inner, yaw);
        // Update pitch to the Red rotor
        UpdateRotor(r_red_middle, pitch);

        float green = GetRotorAngle(r_green_inner);
        if (green == 0) green = 360;
        float red = GetRotorAngle(r_red_middle);
        if (red == 0) red = 360;
        float blue = GetRotorAngle(r_blue_outer);
        if (blue == 0) blue = 360;

        debugText = "Green Angle: " + green.ToString() + "\n";
        debugText += "Red Angle: " + red.ToString() + "\n";
        debugText += "Blue Angle: " + blue.ToString() + "\n";
        debug.WritePublicText(debugText);
        debugText = "";
    }

```

Tracking function:

```
    void GetOrientationTo(Vector3 Target, IMyTerminalBlock Origin, out float Pitch, out float Yaw)
    {

        // Origin point
        Vector3 OV = Origin.GetPosition();
        // Thrusters are two blocks long so we need to make it shorter
        OV = Vector3.Subtract(OV, Origin.WorldMatrix.Forward * 1.25);
        // Target point
        Vector3 TV = Vector3.Subtract(OV, Target);
        // Get reference directional vectors
        Vector3 FV = OV + Origin.WorldMatrix.Forward;
        Vector3 UV = OV + Origin.WorldMatrix.Up;
        Vector3 RV = OV + Origin.WorldMatrix.Right;

        double TVOV = (OV - TV).Length();  // Get magnitudes of vectors

        double TVFV = (FV - TV).Length();
        double TVUV = (UV - TV).Length();
        double TVRV = (RV - TV).Length();

        double OVFV = (FV - OV).Length();
        double OVUV = (UV - OV).Length();
        double OVRV = (RV - OV).Length();

        double ThetaP = Math.Acos((TVUV * TVUV - OVUV * OVUV - TVOV * TVOV) / (-2 * OVUV * TVOV));  //Use law of cosines to determine angles.
        double ThetaY = Math.Acos((TVRV * TVRV - OVRV * OVRV - TVOV * TVOV) / (-2 * OVRV * TVOV));

        double RPitch = 90 - (ThetaP * 180 / Math.PI);  //Convert from radians to degrees.
        double RYaw = 90 - (ThetaY * 180 / Math.PI);

        if (TVOV < TVFV) RPitch = 180 - RPitch;  //Normalize angles to -180 to 180 degrees.
        if (RPitch > 180) RPitch = -1 * (360 - RPitch);

        if (TVOV < TVFV) RYaw = 180 - RYaw;
        if (RYaw > 180) RYaw = -1 * (360 - RYaw);

        Pitch = (float)RPitch;
        Yaw = (float)RYaw;
    }

```

# Answer
My first thought is that we could solve this by gradient descent.

Assuming we did a good job aligning our pointer to the target & minimizing gimbal lock last frame, then this frame we should be very close to a good solution for this frame too.

So, we form a scoring function that prioritizes pointing at the target first, and avoiding problematic alignment between our axes second, eg...

```
Score = 10 * Dot(TargetDirection, PointerDirection)
      - Dot(MiddleGimbalAxis, PointerDirection)^2

```

Then we take gradient of that scoring function as we vary each of the three angles, giving us an incremental change vector we can add to our angles to home-in on a local optimum.

As I was working through this function though, I spotted a simpler method:

The gimbal lock case occurs when we're trying to point parallel to the middle gimbal's rotation axis. If we keep this axis far from the target direction (perpendicular, if we can), then we stay well clear of the danger zone.

So, we can solve the problem like so:

1. Project the target direction into the plane of rotation of the outer gimbal.
2. Rotate the outer gimbal so its arm stays perpendicular to this planar direction.

(Note that there are two possible perpendicular orientations - pick whichever one is closer, to avoid unnecessary spinning when the direction crosses the pole)
3. Transform the target direction into the outer gimbal's local coordinate space
4. Solve the remaining two gimbal axes the same as you did before, with this new transformed target.

As long as your outer gimbal can turn as fast as your target direction does, this will keep the inner transformed target away from the poles of your inner two-gimbal system so it remains well-behaved.

There's still a singularity in this scheme: when the target is directly below / directly overhead, the outer gimbal's rotation is no longer well-defined, and you may see it hesitate or spin here. But in this orientation the inner two gimbals have fully orthogonal degrees of freedom, so we can continue tracking the target without a lock or lurch.
> 1 votes

---
Tags: rotation, quaternion, gimbal-lock, euler-angles
---


title: How to draw a 3D capsule?

text:
# Question
Title: How to draw a 3D capsule?
I want to draw a 3D capsule defined by a **segment** (two points start-\>end) and a **radius**:

Image source: Orionist on Wikimedia Commons

I already have a sphere leaning on this answer: https://stackoverflow.com/a/31326534/1902536. I understand that I can expand the Parametric Equation to an ellipse one but I'm not sure how to do it with the segment (that may have rotation).

what is the best way to draw/model a capsule?

# Answer
> 3 votes
First we can construct a local basis for the space of the capsule.

```
axis = end - start;
length = Length(axis)

localZ = axis/length

localX = GetAnyPerpendicularUnitVector(localZ)

localY = Cross(localZ, localX)

```

Now we can parametrize points on the cylinder segment using two variables `u` & `v` in the range 0...1:

```
shaftPoint = start
      + localX * cos(2 * pi * u) * r
      + localY * sin(2 * pi * u) * r
      + localZ * v * length

```

And points on the hemispheres similarly:

```
latitude = (pi/2) * (v - 1)
startHemispherePoint = start
      + localX * cos(2 * pi * u) * cos(latitude) * r
      + localY * sin(2 * pi * u) * cos(latitude) * r
      + localZ * sin(latitude) * r

latitude = (pi/2) * v
endHemispherePoint = end
      + localX * cos(2 * pi * u) * cos(latitude) * r
      + localY * sin(2 * pi * u) * cos(latitude) * r
      + localZ * sin(latitude) * r

```

Note that the vertices produced for v = 1 in the start hemisphere formula are the same as those made by the shaft formula at v = 0. And likewise the shaft's v = 1 is the end hemisphere's v = 0, ensuring all three parts match up seamlessly. You can generate vertices on just one side of the seam or the other so as not to produce duplicates.

# Answer
> 2 votes
Based on the answer from @DMGregory here is my implementation:

```
glm::vec3 GetAnyPerpendicularUnitVector(const glm::vec3& vec)
{
  if (vec.y != 0.0f || vec.z != 0.0f)
    return glm::vec3(1, 0, 0);
  else
    return glm::vec3(0, 1, 0);
}

void DebugManager::drawCapsule(const Capsule& c, const glm::vec4& color)
{
  const glm::vec3 axis   = c.end - c.start;
  const float     length = glm::length(axis);
  const glm::vec3 localZ = axis / length;
  const glm::vec3 localX = GetAnyPerpendicularUnitVector(localZ);
  const glm::vec3 localY = glm::cross(localZ, localX);

  using glm::cos;
  using glm::sin;
  constexpr float pi = glm::pi<float>();

  const glm::vec3 start(0.0f);
  const glm::vec3 end(1.0f);
  const float     resolution = 16.0f;

  const glm::vec3 step = (end - start) / resolution;

  auto cylinder = [localX, localY, localZ, c, length](const float u,
                                                      const float v) {
    return c.start                                  //
           + localX * cos(2.0f * pi * u) * c.radius //
           + localY * sin(2.0f * pi * u) * c.radius //
           + localZ * v * length;                   //

  };

  auto sphereStart = [localX, localY, localZ, c](const float u,
                                                 const float v) -> glm::vec3 {
    const float latitude = (pi / 2.0f) * (v - 1);

    return c.start                                                  //
           + localX * cos(2.0f * pi * u) * cos(latitude) * c.radius //
           + localY * sin(2.0f * pi * u) * cos(latitude) * c.radius //
           + localZ * sin(latitude) * c.radius;
  };

  auto sphereEnd = [localX, localY, localZ, c](const float u, const float v) {
    const float latitude = (pi / 2.0f) * v;
    return c.end                                                    //
           + localX * cos(2.0f * pi * u) * cos(latitude) * c.radius //
           + localY * sin(2.0f * pi * u) * cos(latitude) * c.radius //
           + localZ * sin(latitude) * c.radius;
  };

  for (float i = 0; i < resolution; ++i) {
    for (float j = 0; j < resolution; ++j) {
      const float u = i * step.x + start.x;
      const float v = j * step.y + start.y;

      const float un =
        (i + 1 == resolution) ? end.x : (i + 1) * step.x + start.x;
      const float vn =
        (j + 1 == resolution) ? end.y : (j + 1) * step.y + start.y;

    // Draw Cylinder
      {
        const glm::vec3 p0 = cylinder(u, v);
        const glm::vec3 p1 = cylinder(u, vn);
        const glm::vec3 p2 = cylinder(un, v);
        const glm::vec3 p3 = cylinder(un, vn);

        drawTriangle(p0, p1, p2, color);
        drawTriangle(p3, p1, p2, color);
      }

    // Draw Sphere start
      {
        const glm::vec3 p0       = sphereStart(u, v);
        const glm::vec3 p1       = sphereStart(u, vn);
        const glm::vec3 p2       = sphereStart(un, v);
        const glm::vec3 p3       = sphereStart(un, vn);
        drawTriangle(p0, p1, p2, color);
        drawTriangle(p3, p1, p2, color);
      }

    // Draw Sphere end
      {
        const glm::vec3 p0       = sphereEnd(u, v);
        const glm::vec3 p1       = sphereEnd(u, vn);
        const glm::vec3 p2       = sphereEnd(un, v);
        const glm::vec3 p3       = sphereEnd(un, vn);
        drawTriangle(p0, p1, p2, color);
        drawTriangle(p3, p1, p2, color);
      }
    }
  }
}

```

---
Tags: opengl, c++, geometry
---


# Question
Title: How can this method to make a text mesh always face the camera be simplified? (Unity c#)
Despite a fairly heafty new years I am back trying to learn a bit more coding :D

This latest feature I am trying to add is a TextMesh that floats above a gameobject when the player is looking at it.

I does all work fine (except it kinda shakes a little but I'll look into that another time). But as I wrote the method to make the textMeshObject look at my camera, I just had a niggling feeling it could be written in less lines of code.

I actually get this a lot where I write several lines and think it must be able to be simplified, and after the code having several parts like this it can look pretty messed up.

Anyways, I thought i'd ask you experts on here if it was possible to do this an simpler (NOTE: I only want it to rotate on Y Axis):

```
  void FaceTextMeshToCamera(){
            Vector3 origRot = textMeshObject.transform.eulerAngles;
        textMeshObject.transform.LookAt(textLookTargetTransform);
        Vector3 desiredRot = textMeshObject.transform.eulerAngles;
        desiredRot.x = origRot.x;
        desiredRot.z = origRot.z;
        textMeshObject.transform.eulerAngles = desiredRot;
  }

```

# Answer
> 2 votes
Eh, not really. You can save about two lines:

By moving the Y value over instead of both X and Z, we save a line:

```
void FaceTextMeshToCamera(){
    Vector3 origRot = textMeshObject.transform.eulerAngles;
    textMeshObject.transform.LookAt(textLookTargetTransform);
    Vector3 desiredRot = textMeshObject.transform.eulerAngles;
    origRot.y = desiredRot.y;
    textMeshObject.transform.eulerAngles = origRot;
}

```

By seeing that we only need the one value we can save another (and avoid creating a local variable, although this saves virtually nothing in terms of RAM, as Vector3s are primitives and exist on the stack instead of the heap and don't need to be garbage collected):

```
void FaceTextMeshToCamera(){
    Vector3 origRot = textMeshObject.transform.eulerAngles;
    textMeshObject.transform.LookAt(textLookTargetTransform);
    origRot.y = textMeshObject.transform.eulerAngles.y;
    textMeshObject.transform.eulerAngles = origRot;
}

```

# Answer
> 0 votes
May be this will help you out..

```
using UnityEngine;
using System.Collections;

    public Camera m_Camera;

    void Update()
    {
        transform.LookAt(transform.position + m_Camera.transform.rotation * Vector3.forward,
            m_Camera.transform.rotation * Vector3.up);
    }
}

```

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


title: Rotate object to always face camera

text:
# Question
Title: Rotate object to always face camera
I'm trying to make a TextMesh appear when ever an enemy prefab is hit.

I currently have this functionality working. However, the text doesn't face the direction the players camera is looking.

At the moment my OnCollisionEnter method contains the following line of code:

```
GameObject _go = (GameObject)Instantiate(_hitPrefab, collision.gameObject.transform.position, Camera.mainCamera.transform.rotation);

```

This line happily creates my TextMesh whenever my enemy is hit. I know my issue has something to do with my rotation quaterion, but I have no idea what pass in so it faces my camera. As you can see, I tried setting it Quaterion.Idenitiy thinking it'll show the same way as the enemy it's associated to, but that doesn't work either.

Each time the textmesh appears, its back to front for the player and at a slight angle.

Could someone please help me in getting it so the score always faces the players camera no matter what way he is facing?

# Answer
You are simply copying the main camera's rotation in your code snippet, try this method:

```
GameObject _go = (GameObject)Instantiate(_hitPrefab,
        collision.gameObject.transform.position, Quaternion.identity);
_go.transform.LookAt(Camera.main.transform);

```

http://docs.unity3d.com/Documentation/ScriptReference/Transform.LookAt.html

You should also have a look into Quaternion.LookRotation.

http://docs.unity3d.com/Documentation/ScriptReference/Quaternion.LookRotation.html

Edit:

This is a very useful community script for camera facing, the results may be slightly better: http://wiki.unity3d.com/index.php?title=CameraFacingBillboard
> 6 votes

# Answer
May be this will help you out

```
public Camera m_Camera;

void Update()
{
    transform.LookAt(transform.position + m_Camera.transform.rotation * Vector3.forward,
        m_Camera.transform.rotation * Vector3.up);
}

```
> 1 votes

# Answer
This helps me:

```
Vector3 fwd = _camera.forward;
fwd.y = 0;
transform.rotation = Quaternion.LookRotation(fwd);

```
> 0 votes

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


# Question
Title: Player customization of entity and handling textures
I'm developing a racing game where you can customize your vehicle with pre-made textures and also user generated ones (players can add assets to the game).

I want to know what you think is the best approach to this type of customization.

* Use pre-packed textures and load the corresponding atlases for every single part (I think this is the easiest, but wastes memory having 3 or 4 atlas in memory and just using one texture of each).
* Check what the user selected and pack those textures into an atlas at runtime and use that until the user changes any part and pack it again, and so on... (more complex, less gargabe in memory).

Take into account that customizable parts include: wheels, spoilers, hoods, decals, exhausts and the user also has the possibility to add content.

I've never implemented something like this so any help would be appreciated.

# Answer
> 2 votes
I think the best way to handle it would be to create an atlas at runtime. Maybe by having it compile once a player saves their customizations in the customizing menu. It would be the easiest in the long run because then players won't have to add an entire atlas to get a custom texture into the game.

---
Tags: libgdx, textures, texture-atlas, user-generated-content
---


# Question
Title: Get the XZ to the right of a rotated point?
I need to do this entirely with math, take a look at this picture:

What I'm doing is building a path finder algorithm that basically looks 30 units ahead, raycasts a few times perpendicular to the future point, finds the midpoint between the min/max vectors that found the dirt road, and puts a green cube in the middle.

I thought this would be rather simple, yet here I am trying to figure out how to plot the exact geometry of a rotated left/right projection.

I hope I explained this well enough! I'm also open to suggestions on how to do this if my approach is silly. Eventually this path will split and the algorithm has to detect the split and have the user decide which direction to go.

EDIT: After applying the math below (I opted to use the trig version) I go this result on my algorithm. THANK YOU!!!

# Answer
A unit vector in the xz plane pointing at a `radianAngle` counter-clockwise from the positive x axis has the formula:

```
Vector3 tiltedRight = new Vector3(
                Mathf.Cos(radianAngle),
                0,
                Mathf.Sin(radianAngle)
);

```

And a unit vector at the same angle counter-clockwise from the positive z axis has the formula:

```
Vector3 tiltedForward = new Vector3(
               -Mathf.Sin(radianAngle),
                0,
                Mathf.Cos(radianAngle)
);

```

So you can compute your points like so:

```
Vector3 projectedPoint = startPoint
                 + titledForward * distanceForward
                 +   tiltedRight * distanceRight;

```

Or you can construct a local basis like so and hide all the trig math:

```
Quaternion turn = Quaternion.Euler(0, degreeAngle, 0);

Vector3 localOffset = new Vector3 (distanceRight, 0, distanceForward);

Vector3 projectedPoint = startPoint + turn * localOffset;

```
> 0 votes

---
Tags: unity, c#, path-finding
---


title: Interesting graphic artifact

text:
# Question
Title: Interesting graphic artifact
I was exploring old Minecraft source code when I encountered this:

I just wanted to know what causes such distortion and how to fix it with OpenGL?

# Answer
> 4 votes
That's usually just due to non-existent mipmapping. Turn it on.

---
Tags: opengl, graphics, minecraft-modding
---


# Question
Title: What to do when a function to return something is null?
I have a generic Items class that keeps track of all items, and when Items are created they are added to this list. The problem is that I have a function that returns the item by its ID, but what do I return in `items[id]` doesn't exist? It won't let me return null...

Should I just use a for loop that iterates through every item and checks if `items[i].id` equals the input ID?

Here's my code

```
public static class Items
{
    public static List<Item> items = new List<Item>();

    public static Item getItemById(Items instance, int id)
    {
        if (items[id] != null)
        {
            return items[id];
        }
        else
        {
            return null;
        }
    }
}

```

# Answer
Not sure what your problem is. you use the id like a position in an array.

try to replace

```
if (items[id] != null)

```

with

```
if (items.Count > id)

```

this way if the id position doesn't exist in the array the function will return null value and the program won't crash.

If you want to use the ID like an ID of an object in a more properly way check the solution given by Spectre.
> 2 votes

# Answer
I recommend the short syntax:

```
public static Item GetItemById(Items instance, int id)
{
    return (items.Count > id) ? items[id] : null;
}

```

Or even shorter:

```
public static Item GetItemById(int id) => (items.Count > id) ? items[id] : null;

```

By the way:
In C# method names should begin with an uppercase letter.
And do you really need the `Items instance` parameter?
> 1 votes

# Answer
> It won't let me return null...

It sounds then like your `Item` type is a `struct` (ie. a value type)

Reference types (including anything defined as a `class`) are stored and passed by reference (ie. if you have a `GameObject myObject` variable that variable holds a kind of pointer to the game object, rather than replicating the whole object inside the variable's storage), and that reference can point at `null` to signify "nothing / not populated / invalid"

But value types (like numbers, or anything defined as `struct`) are stored and passed by value (by default). So each such variable contains a complete and independent copy of the data. Eg. an `int` variable will contain a specific four bytes, and every possible value of those bytes represents a valid integer from `int.MinValue` to `int.MaxValue`. So there's no leftover storage to represent the "nothing / not populated / invalid" message that `null` provides for reference types.

If you're used to working with reference types, you can just change `Item` to be a `class` and you're off to the races. This can save memory in some cases because we can share references to a common instance rather than copying it everywhere, but it also means we're doing heap allocations whenever we create a new instance, which might not be ideal for types you want to create & discard frequently, like vectors.

When we need to, we can augment a value type with an extra bit of storage to track whether it's been populated, by using a `Nullable` type. This is a built-in generic `struct` that wraps an arbitrary value type and adds `null` functionality.

We can declare that our method returns a nullable version of the `Item` type (ie. a `Nullable<Item>`) by writing:

```
 public Item? GetItemById(int id) { ... }

```

This will let us return an `Item` instance *or* `null`, and the `?` advertises to callers "I might fail to find an `Item` for you — I can only promise a 'maybe'"

Calling code should then check to see if it got a null before it tries to work with the returned value:

```
Item? response = myItems.GetItemById(someId);

// Check if we found an item at all.
if(response.HasValue) {
    // if(response != null) also works here

    // Get the actual item value.
    Item item = response.Value;

    // Do something with it...
}

```
> 1 votes

# Answer
> Should I just use a for loop that iterates through every item and checks if items\[i\].id equals the input id?

**Yes, you should** I've edited your code a bit.

```
public static class Items
{
    public static List<Item> items = new List<Item>();

    public static Item getItemById(int id)
    {

        foreach(Item it in items) // iterate through items
            if(it.ID == id) return it; // if one of the items has provided ID, return it

        return null; // if none of the items has the id, return null

    }

}

```

Also, make sure your `Item` class has an `ID` property:

```
public class Item {
    public int ID { get; set; }

    // more logic
}

```
> 0 votes

# Answer
`null` references are dangerous. Every `null` lurking in your data is a landmine waiting to explode in a `NullReferenceException`. These can be hard to debug, because in a more complex program it might not always be obvious when, where and why a reference was set to `null`.

Consider throwing an `Exception` instead. Create an own exception class `UnknownItemIdException` and throw that exception instead of returning `null`.

```
public static Item getItemById(Items instance, int id)
{
    if (items[id] != null)
    {
        return items[id];
    }
    else
    {
        throw new UnknownItemIdException(id);
    }

}

```
> 0 votes

# Answer
So there's a few questions here. What do i return? what if it doesn't exist? should I use a for loop?

Firstly. A couple of good practises when attempting to find something which potentialy cannot be found.

1) Name the function with 'find' instead of 'get' as it implies the function behaviour. 'get' kind of implies that item exists and so the function should just go go and 'get' it. However 'find' implies some work may have to be done. A search maybe. Also the find may not be successful. This is useful when working with a team of programmers as they may not be intimately aware of what your code does. The programmer can read the function name and have an idea of whats going on.

2) The find may fail. This is a valid scenario. Write the code accordingly. Return false if the item is not found. On success output the found item as an output parameter.

So an example which may help your situation may be..

```
    static void Main(string[] args)
    {
        Item[] allItems = new Item[100];

        // make a test item with id of 45 and add it to the list
        Item testItem = new Item(45);
        allItems[testItem.ID] = testItem;

        // find it
        Item foundItem;

        if (findItemById(allItems, 45, out foundItem) == true)
        {
            // Item was found !
        }
    }
    static bool findItemById(Item[] itemStore, int id, out Item foundItem)
    {
        if( itemStore[id] != null )
        {
            foundItem = itemStore[id];
            return true;
        }

        foundItem = null;
        return false;
    }

```

secondly, Should you use a loop to iterate and check?

I would say yes but the reason why and not how is probably more important.

To write the code ..

```
if (findItemById(allItems, 45, out foundItem) == true)

```

This is pretty straight forward. true on success. false on fail. founditem is set if success. You can write this once at the start of the project and it can easily be there at the end with no modifications.

However the findItemById() function offers a simple interface and can hide any implementation intricacies. So you can alter and optimise what it does throughout development. So if you use a list, and check for id's, if the list gets long and this function shows up on the profiler then you can hone in your optimisation time.

hope that helps :)
> 0 votes

---
Tags: c#, monogame
---


title: 2D Grand strategy map

text:
# Question
Title: 2D Grand strategy map
I'm trying to make a 2 dimensional grand strategy type of map, similar to Stronghold Kingdoms:

I've never dealt with these kinds of map before, but I assume this is a vector map (in svg format). I have some GIS experience, specifically openLayers and I know it uses tiles for it's map rendering. Is that an option for me too? Maybe I could use tiles on the most zoomed out levels to make the map look pretty and overlay the vector map with transparency on top.

Sorry for badly written question, I'm really bad at this, if you could point me to some resources to writing better, I'd take those too.

# Answer
I'm not familiar with Stronghold Kingdoms. However, I have done some work with a grand strategy game of my own (though this project, like a lot of my projects, got shelved a while back). Lets talk, instead, about how the kings of grand strategy, Paradox Development Studios do their maps;

First, Paradox seems to have a large number of files that build up their maps. The main one we want to talk about here is the province map, which details what provinces there are and what territory they actually contain. In this file, all provinces have a unique colour. What colour each pixel is indicates which province is where. However, a pixel in this map does not necessarily correspond to a pixel in game, and likely will be multiple in game pixels to a map file pixel.

Next, there is the definitions file, which is a csv file containing the province id, red, green, blue. This links the various province data files to the territory given in the province map.

Each province has its own file, which details the various resources, religion, culture, history and so on.

Then, there are various other maps, which match the other map, but detail other things. For example, a map of all the rivers, a heightmap, a terrain map and so on. For each of these world map images, a pixel maps to the same pixel on another map (I believe). So, rather than try to contain all the data in one file, its contained in several and then used to build things up.

In the game itself, the map is generated at game load (and cached, as this can take some time). As Paradox games are 3d, the heightmap is used to make the heights, then the provinces are overlaid over this. I'm not sure of the technical details.

The Province map is also used to calculate which provinces are next to each other. When I tried my hand at making a Grand Strategy game, the method I used was to iterate through each pixel on each row, and when it changed colour, add this to a list of adjacencies. Then do the same for columns. This can take a while, however, so caching is important to keep load times down.

There is more to it than that, but that's the basics.
> 2 votes

---
Tags: 2d, maps
---


title: Calculate the slope of a 3D triangle?

text:
# Question
Title: Calculate the slope of a 3D triangle?
I have lots of triangles in 3D space. How do I determine the slope/angle of these triangles with respect to a fixed ground plane? I need pseudo code examples at the very least.

# Answer
Based on dnk drone.vs.drones' instructions I created the following JavaScript:

```
function Get_Angle(vertex_1, vertex_2, vertex_3)
{
    // get two vectors in the triangle
    var vector_u =
    [
        vertex_2[0] - vertex_1[0],
        vertex_2[1] - vertex_1[1],
        vertex_2[2] - vertex_1[2]
    ]
    var vector_v =
    [
        vertex_3[0] - vertex_1[0],
        vertex_3[1] - vertex_1[1],
        vertex_3[2] - vertex_1[2]
    ]
    // calculate the cross product to get the normal
    var vector_n =
    [
        vector_u[1] * vector_v[2] - vector_u[2] * vector_v[1],
        vector_u[2] * vector_v[0] - vector_u[0] * vector_v[2],
        vector_u[0] * vector_v[1] - vector_u[1] * vector_v[0]
    ]
    // calculate the magnitude or length of the normal vector
    var magnitude_n = Math.sqrt(vector_n[0] * vector_n[0] + vector_n[1] * vector_n[1] + vector_n[2] * vector_n[2])
    // normalize the normal vector
    vector_n =
    [
        vector_n[0]/magnitude_n,
        vector_n[1]/magnitude_n,
        vector_n[2]/magnitude_n
    ]
    // the normal of the ground plane
    var vector_r = [0,1,0]
    // calculate the dot product of vector_n and vector_r
    var dot_product = vector_n[0] * vector_r[0] + vector_n[1] * vector_r[1] + vector_n[2] * vector_r[2]
    // calculate the angle between vector_n and vector_r
    var angle_between = Math.acos(dot_product)
    // returned value is less than or equal to pi
    return angle_between
}

```
> 0 votes

# Answer
EDIT (added short steps):

1. get triangle normal vector `v1` (normalized)
2. get reference surface normal vector `v2` (normalized)
3. get angle between normals : `angle = acos(v1•v2)` (where • = 'dot' product )
4. get `slope = Tan(angle)`

if you need a surface normal here come the simple algoritm :

A surface normal for a triangle can be calculated by taking the vector cross product of two edges of that triangle. The order of the vertices used in the calculation will affect the direction of the normal (in or out of the face w.r.t. winding).

So for a triangle p1, p2, p3, if the vector U = p2 - p1 and the vector V = p3 - p1 then the normal N = U X V and can be calculated by:

Nx = UyVz - UzVy

Ny = UzVx - UxVz

Nz = UxVy - UyVx

EDIT: to get the angle between reference plane and triangle plane , you can calculate the angle between reference plane normal vector (call it Nref) and triangle normal (N already calculated). Here the angle between 3d vectors math:

"If v1 and v2 are normalised so that |v1|=|v2|=1, then,

angle = acos(v1•v2)"

Finaly from angle to slope : Tan(angle)
> 4 votes

---
Tags: mathematics, javascript, geometry, 3d-meshes
---


# Question
Title: How to get the next line character to work in a self-typing dialog box?
With the help of a tutorial, I've created an almost successful dialog box that types itself out (just as older RPGs do, and some still do). The only problem is that I've wrapped the text so that if a word is too long for the line within the dialog box, it goes on down to the next line.

However, since my code is typing out the dialog character by character, it probably can't use the "\n" directly. And even when I do use "\n" it does not go to the next line. It simply prints those characters exactly.

I initially tried using a single character ("\*") that my code would then replace during the typing with a "/n" character. However, this just printed the "/n" per usual. Whether I use '\n', "\n", or \n, it doesn't seem to work.

You can see, I've got some special characters being used to signal whether the text should go slower than usual, or whether or not there should be a longer pause. I also included the function that goes through and takes out those special characters. But anyway, here's the code in general, how can I add a next line?

```
private IEnumerator TextScroll(string lineOfText)
{
    int letter = 0;
    theText.text = "";
    isTyping = true;
    cancelTyping = false;
    while (isTyping && !cancelTyping && (letter < lineOfText.Length)) {

        if (lineOfText[letter] == '@')
            {
            letter += 1;
            yield return new WaitForSeconds(0.5f);
            }

        if (lineOfText[letter] == '<')
            {
            typeSpeed = 0.5f;
            letter += 1;
            }

        if (lineOfText[letter] == '>')
        {
            typeSpeed = 0.025f;
            letter += 1;
        }

        theText.text += lineOfText[letter];
        letter += 1;
        yield return new WaitForSeconds(typeSpeed);
    }

    newLineOfText = lineOfText;
    theText.text = TrimString(newLineOfText);
    isTyping = false;
    cancelTyping = false;
}

public string TrimString(string line)
    {
        var charsToRemove = new string[] { "@", "<", ">"};
        foreach (var c in charsToRemove)
        {
            line = line.Replace(c, string.Empty);
        }
        return line;
    }

```

# Answer
Use Enviroment.NewLine instead of \n. On windows, this will return the value of \n\r, while on unix systems, this will return \n.

Test script I used to test this is below. Note, this uses functionality that requires 4.6 (the string interpolation).

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

public class testscript : MonoBehaviour {

    Queue<string> toWrite;

    Text text;

    // Use this for initialization
    void Start () {
        text = GetComponent<Text>();
        toWrite = new Queue<string>();
        toWrite.Enqueue("hello" + Environment.NewLine);
        toWrite.Enqueue($"Nice to meet you. {Environment.NewLine} how are you?");
        StartCoroutine(write());
    }

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

    }

    IEnumerator write()
    {
        while(toWrite.Count> 0)
        {
            var current = toWrite.Dequeue();
            int idx = 0;
            while (idx < current.Length)
            {
                text.text += current[idx];
                idx++;
                yield return new WaitForSeconds(0.1f);
            }
        }
    }
}

```

Incidentally, in case you didn't know, idx+= 1; and idx++; are equivalent.
> 1 votes

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


# Question
Title: Unity: Create large Terrain with accurate raycast detection?
I'm not using the Unity Terrain because it lacks certain features.

Amongst them, you cannot tile them:

You cannot create concave walls or make holes in it:

No custom textures, no detail textures, awful sculpting tools... the list goes on and on. So I imported my own Terrain as a Mesh. The collision works perfectly, however raycasting onto the Terrain is horribly inaccurate. Unity seems to compress the Mesh Collider depending on distance to player. See the video linked below. Since Unity is (by my knowledge) the only Game Engine that supports convex colliders, how do other game engines create Terrain colliders?

For a racing game or a RTS or RPG the colliders are no problem, but for a shooter it's unacceptable. Here's a video showing the problem:

## **https://youtu.be/coiFS6IT4wI**

I've researched long and hard and there seems to be no known solution for this. So my question remains, if it's possible at all, how can i create large scale Terrains for Unity? This problem makes it completely impossible for me to create outdoor scenes. There HAS to be some kind of solution.

---

## 1) Raycasting script:

```
//Spread
        float spreadAmount = Mathf.Lerp(spreadMin, spreadMax, burstTimer / spreadThreshold); //Current Spread lerps between spreadMin and spreadMax by burstTimer (increases per shot)

        int i = 0;
        totalShotDamage = 0; //Buckshot sends 8 rays down the range. totalShotDamage gets total damage done by all rays. Needed for displaying damage text

        while (i < bulletCount) //Repeats Shooting Vector for bulletCount amount (needed for buckshot)
        {
            Vector3 shootDirection = shootOrigin.transform.forward; //Shoot Vector 100% accuracy

            shootDirection += shootOrigin.transform.right * (Random.Range(-spreadAmount, spreadAmount)); //Randomizes Vector horizontally, reduces accuracy
            shootDirection += shootOrigin.transform.up * (Random.Range(-spreadAmount, spreadAmount)); //Randomizes Vector Vectically, reduces accuracy

            Ray ray = new Ray(shootOrigin.transform.position, shootDirection); //Ray from Shoot vector
            RaycastHit hitInfo;

            if (Physics.Raycast(ray, out hitInfo, 2000, shootLayerMask)) //Sets range of gun & sends ray
            {
                Vector3 hitPoint = hitInfo.point; //Point of impact with any object
                GameObject go = hitInfo.collider.gameObject; //GameObject of impacted Object

                string targetTag = hitInfo.collider.gameObject.tag; //Tag of GameObject of impacted Object

                addHitParticleEffects(targetTag, hitInfo, enableBulletholes); //Add hitparticle effects based on Tag (IMPACTmaterial)
                damageEnemy(targetTag, hitInfo, damage, damageRollOff); //Damage enemy
            }
            i++; //total bullet count (needed for buckshot)
        }

```

## 2) Terrain Inspector Settings

## 3) LOD Settings

There are no LOD Settings (yet). Individual Planes of the whole Terrain and objects on top of it simply pop in and out of existence depending on the Players position.

# Answer
First of all **I have no idea how all this stuff works and why.** But the answer was a lot simpler than ArcaneEngineer would suggest. The problem seemed to be here:

The Model was scaled to 32 in Blender. After scaling it down to 1 and reimporting to Unity, and scaling it back up inside Unity the Mesh Collider was very accurate.

I experimented with that and the result is: The higher the scale inside Blender when you export the model the less accurate the Mesh Collider is. The lower the scale (such as 0.01) the more accurate the Mesh Collider is. It had absolutely **nothing** to do with the amount of Polygons. Unity is not compressing the mesh for the MeshCollider.

And no the MeshCollider is not expensive at all. I was running hundreds of fps with a 200k Mesh Collider on the Model. Disabling the MeshCollider gave an increase of 2-3 fps. However I am using the MeshCollider against 10-20 Sphere or Capsule colliders and of course for RayCasting.
> 0 votes

# Answer
**(1) Notes on terrain systems**

**Outdoor scenes are always a challenge to render and interact with, given viewing distance** and subsequent complexity involved. This is just a reality of outdoor terrain. One often has to create one's own LoD systems (or at least heavily adapt those available) to get what one wants.

**There is no way they can be *both* general purpose (as Unity's is) *and* fast / efficient**; especially given all the other factors involved: static vs dynamic, LoD structure, etc. etc. Custom (concave) mesh-based collision is a very slow check, which is undoubtedly (part of) the reason Unity uses a sort of LoD on the mesh itself.

**Unity doesn't support overhangs in terrain, because it uses heightmaps**, a very old and very efficient system for reducing complexity and thereby cost, in various areas from rendering to physics to networking. It's typically cheaper to use a planar heightmap and run through a list of `n` objects that act as overhangs, than to make the entire terrain suitable for creating overhangs.

**Geometry-based raycasts against large meshes using (concave) MeshColliders are COSTLY**, because the collider has to check against the *triangle count* of the underlying mesh. No wonder Unity applies it's own optimisations in the process... as you have found. Concave geometry checks are an order of magnitude more costly compared with convex checks.

**(2) Solutions**

I would voxelise each chunk into a low resolution grid (3D array) by sampling the point at the centre of each grid cell to see whether that point falls inside or outside the fine polygon chunk mesh. If you raycast that grid using a cheap 3D-DDA raycast (not the same as Unity raycasting) and score a hit, then you can perform a more costly check for the associated subsection of the chunk mesh, using a standard triangles-based Unity raycast. Grid & DDA provide *broadphase* collision detection.

The voxelisation sampling step would involve you sampling either:

* Each chunk of your custom mesh directly

OR

* The world heightmap AND
* The list of N objects sitting on the surface thereof (possibly creating overhangs).

It may be that others can give a better answer for Unity specifically, but I think you will find these are limitations inherent in any general purpose terrain system, with Unity being no exception.

One way or another, some sort of spatial acceleration structure is needed to solve these problems of cost without reducing the fidelity of your terrain. See octrees, quadtrees, KD-trees, and the like; however, having the data structure available and working (quickly) is one thing; inserting data into it according to your design needs is a whole other story that will need addressing.

Other than that I can only say, game design that is constrained often leads to better gameplay. You may be better off starting with smaller levels and working your way up to complex ones from there as you discover what is technically possible and feasible, in various areas.
> 4 votes

---
Tags: unity, terrain, meshcollider
---


# Question
Title: The number of shaders a large game or game engine has
Wondering the scale basically. The number of shaders a large game or game engine has. I've seen some metal repos but they typically just have 1 or 2 shaders for small demos. I think I've seen a few with 5 or 10, 1 with maybe 20. But I haven't seen anything where there is like 100 or 1,000 shaders or anything like that.

Wondering what the scale is like for typical large games or game engines, if they are on the order of 1-10, or 100, or 1000, sorta thing. And if it's a large number, maybe a quick idea of what the various tasks they are used for would be interesting but not required :). Thank you!

# Answer
> 5 votes
It depends in part on how you count them.

Many games & engines use large shaders, called "ubershaders," that try to cover many different material effects and rendering techniques, with controllable toggles to turn features on and off depending on:

* what's needed for each specific material
* graphics quality/performance settings selected at build time, by the player at runtime, or by the level-of-detail system as the object recedes into the background
* peculiarities of each target platform (eg. adaptations to differences in APIs, or optimizations specific to console hardware)

These then get compiled into individual shader programs (called "variants" or "permutations") for each unique subset of features used somewhere in the game, and each platform-specific variant.

So if we had a material with:

* transparent & opaque versions
* metallic & non-metallic reflection models
* with & without a smoothness/roughness map
* with & without an emissive texture
* with & without parallax occlusion mapping
* with & without a detail map / detail normal
* baked or realtime diffuse lighting
* with and without sampling a realtime reflection probe
* DirectX vs OpenGL platform targets
* high & low-quality presets
* VR/stereoscopy support

Then we've already got over 2000 permutations just from that "one" shader!

This example is a little contrived, but not outside the realm of possibility. This article for example suggests that in Unreal 4, recompiling all shaders means around ~125 base effects multiplied to ~10 000 permutations, and Unity users report seeing ~6000 shader variants compiled under certain VR conditions.

So, as ballparks, "dozens to low hundreds" of root shader types is realistic, which may expand into hundreds or thousands of compiled shader programs in use, depending on the scope of the game and the number of different features/platforms it's trying to support.

---
Tags: shaders, software-engineering
---