# Question
Title: Mapping TrueSkill scores to a ranking system
I have a 1v1 game that I would like to apply a ranking system to like most competitive multiplayer games out there.

I'm specifically looking for systems like League of Legends where they have Silver, Gold, Plat, Diamond etc and players can move between those ranks as they win or lose.

I'm calculating player ratings with TrueSkill. I actually have not a clue if I'm using it correctly I'm starting off everyone with a mu of 50 and a sigma of 10?

After some iterations people end up with different mu and sigma values. How should I determine what mu values are what ranks?

# Answer
> 2 votes
While I'm not that familiar with TrueSkill; I would probably use the MU to *indirectly* determine their rank. If you had Gold be "Within the upper 10th-percentile of MU" and Silver be "Within the upper 30th-percentile of MU" (etc..) then you don't have to futs-around with specific numbers.

You could, instead, run a reasonable sized beta test to see where percentages you would consider using seem to stabilize and then use a nice round number that's nearby. Say you have 1000 users and the upper 10% have a lower-bound MU of 516; you may then decide that everyone over 500 is "Gold" now that you've seen how your algorithm performs in the real world.

Heck, you could actually do this with simulated games to start with to get a rough estimate.

If your TrueSkill Mu can go to infinity over time (as in, if everyone is playing the upper ranks continue increasing) I'd lean back into my first suggestion and basically have a percentile cut-off.

# Answer
> 0 votes
Variables in consideration: You need to decide if Silver, Gold, Plat, Diamond ranks are fixed to a value or not. Also if your rank is in relation to the number of players or not. If it is so, for the first players will be easier than the latest ones or not.

As for example in a soaring simulator game, the rank is fixed. If the pilot makes more than an amount of time it gets silver and if it passes that and makes more than an amount of altitude it gets Gold. Each rank will be in function of the amount. Mu will be the rank and sigma the amount but:

Using Microsoft TrueSkill, ("Published formulas for Trueskill are not complete" Wikipedia) is better if you read the latest state if the patent that will help you to understand how this tow variables mu and sigma are used: LINK

---
Tags: scoring, ranking
---


# Question
Title: In random loop button dont work properly
I have this code to add 10 point if someone click the button and change the question. But it returns 10 point every time. I want to make it 10,20,30,40... etc.

```
IEnumerator TransitionToNextQuestion() {

            unAnsweredQuestions.Remove(currentQuestion);
            yield return new WaitForSeconds (timeBetweenQuestions);
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }

        public void addPoint(int addPoint) {
            point = point + addPoint;
        }

        public void ButtonDown() {
            addPoint (10);
            Debug.Log (point);
            StartCoroutine (TransitionToNextQuestion());

        }

```

# Answer
> 0 votes
That is because **int**s are value types, this means they are located in the stack, which, on the other hand, classes are reference types, so they are located in dynamic memory. In a nutshell: when you have a class, you have its memory's reference, when you have a value type, you have its value, but not its memory reference.

When you pass a value type as a parameter and you modify it inside a function, it will not be modified, you could use a **ref** or **out** modifier in your parameter instead, with that, you also pass the location in memory of that value type. Or you could do a wrapper class.

Example:

```
public class Example : MonoBehaviour
{
    int integer;

    void Start()
    {
        AddTen(ref integer);
        Debug.Log(integer);  /// Will return 10.
    }

    void AddTen(ref int _value)
    {
        _value += 10;
    }
}

```

So, in short, if you want to modify a value type (structs, string, int, char, double, float, etc.) you should use the **ref** or **out** modifiers.

Check in more depth the **differences between value and reference types**. Hope it helps.

---
Tags: unity, c#, game-loop
---


# Question
Title: How to convert Clip-space gl_Position to something you can write to a color buffer (0-1)
"How do I convert clip-space gl\_Position to a valid depth?" I have a vertex shader that calculates a vertex position

```
//Do stuff
gl_Position = stuff;

```

then in my fragment shader I want to use the value of stuff.z and write it to a color buffer. How?!?!

# Answer
(ourdepth+janear)/(jafar+janear) where Janear is the near clip plane and jafar is the far clip plane

ourdepth is the value output as gl\_Position.z in the vertex shader

This is infinitely useful for people trying to do shadowmapping

Here is my example code (sorry if it is messy)

```
#version 330

//INITIAL_OPAQUE.VS
//(C) Geklmin 2018

layout( location = 0 ) in vec3 vPosition;
layout( location = 1 ) in vec2 intexcoord;
layout( location = 2 ) in vec3 Normal;
layout( location = 3 ) in vec3 VertexColor;

out vec2 texcoord;
out vec3 normout;
flat out vec3 flatnormout;
out vec3 Smooth_Vert_Color;
out vec3 ND_out;
out vec2 window_size;
flat out vec3 Flat_Vert_Color;
out vec3 vert_to_camera;
out float ourdepth;

vec3 worldpos; //Position of the fragment in the world!

uniform float windowsize_x;
uniform float windowsize_y;
uniform mat4 World2Camera; //the world to camera transform. I figure this is faster than calculating MVP seperately per vertex.
uniform mat4 Model2World; //Model->World
uniform uint renderflags;
uniform vec3 CameraPos;
void
main()
{
    window_size = vec2(windowsize_x, windowsize_y);
    //The position of this vertex in the world coordinate system.
    worldpos = (Model2World * vec4(vPosition,1.0)).xyz;
    vec4 big_gay = World2Camera * Model2World * vec4(vPosition,1.0);
    texcoord = intexcoord; //this is faster
    gl_Position = big_gay;
    ourdepth = big_gay.z; //Depth
    normout = (Model2World * vec4(Normal, 0.0)).xyz;
    flatnormout = normout;
    ND_out = big_gay.xyz;
    Smooth_Vert_Color = VertexColor;
    Flat_Vert_Color = VertexColor;

    vert_to_camera = CameraPos  - worldpos;
}

```

and my fragment shader:

```
#version 330
// #extension GL_ARB_conservative_depth : enable
// out vec4 fColor[2];
// INITIAL_OPAQUE.FS
// (C) Geklmin 2018
// layout (depth_greater) out float gl_FragDepth;
// ^ should probably re-enable that later

//List of flags. Some of these are no longer implemented, they caused too much of a performance problem. I do not recommend you enable them.
const uint GK_RENDER = uint(1); // Do we render it? This is perhaps the most important flag.
const uint GK_TEXTURED = uint(2); // Do we texture it? if disabled, only the texture will be used. if both this and colored are disabled, the object will be black.
const uint GK_COLORED = uint(4);// Do we color it? if disabled, only the texture will be used. if both this and textured are disabled, the object will be black.
const uint GK_FLAT_NORMAL = uint(8); // Do we use flat normals? If this is set, then the normals output to the fragment shader in the initial opaque pass will use the flat layout qualifier.
const uint GK_FLAT_COLOR = uint(16); // Do we render flat colors? the final, provoking vertex will be used as the color for the entire triangle.
const uint GK_COLOR_IS_BASE = uint(32); //Use the color as the primary. Uses texture as primary if disabled.
const uint GK_TINT = uint(64); //Does secondary add to primary?
const uint GK_DARKEN = uint(128);//Does secondary subtract from primary?
const uint GK_AVERAGE = uint(256);//Do secondary and primary just get averaged?
const uint GK_COLOR_INVERSE = uint(512);//Do we use the inverse of the color?
const uint GK_TEXTURE_INVERSE = uint(1024);//Do we use the inverse of the texture color? DOES NOT invert alpha.
const uint GK_TEXTURE_ALPHA_MULTIPLY = uint(2048);//Do we multiply the color from the texture by the alpha before doing whatever it is we're doing? I do not recommend enabling this and alpha culling, especially if you're trying to create a texture-on-a-flat-color-model effect (Think sega saturn models)
const uint GK_ENABLE_ALPHA_CULLING = uint(4096); //Do we use the texture alpha to cull alpha fragments
const uint GK_TEXTURE_ALPHA_REPLACE_PRIMARY_COLOR = uint(8192); //if the alpha from the texture is <0.5 then the secondary color will replace the primary color.

uniform sampler2D diffuse; //This is actually the texture unit. limit 32. This one happens to be for the literal object's texture.
uniform samplerCube worldaroundme; //This is the cubemap we use for reflections.

in vec2 texcoord;
in vec3 normout;
flat in vec3 flatnormout;
flat in vec3 Flat_Vert_Color;
in vec3 Smooth_Vert_Color;
in vec3 ND_out;
in vec2 window_size;
in vec3 vert_to_camera;
in float ourdepth;
uniform float ambient;
uniform float specreflectivity;
uniform float specdamp;
uniform float emissivity;
uniform float jafar; //The floating-point number you gave to GLM or GLU when you told it to build a perspective matrix, for the far clipping plane
uniform float janear; //The floating-point number you gave to GLM or GLU when you told it to build a perspective matrix, for the near clipping plane

uniform float diffusivity;

vec2 bettertexcoord;
vec4 texture_value;
vec3 color_value;
vec3 primary_color;
vec3 secondary_color;
vec3 finalcolor;
uniform uint renderflags;
vec4 FindNDC() //this fuckin thing!
{
    return vec4((gl_FragCoord.x / window_size.x - 0.5) * 2.0, (gl_FragCoord.y / window_size.y - 0.5) * 2.0, (gl_FragCoord.z - 0.5) * 2.0, 1.0);
}

void main()
{
    bettertexcoord = vec2(texcoord.x, -texcoord.y); //Looks like blender
    vec3 UnitNormal;
    vec3 usefulNormal;
    //Just normalizing our vectors...
    if ((renderflags & GK_FLAT_NORMAL) > uint(0))
    {
        UnitNormal = (normalize(flatnormout) + vec3(1.0,1.0,1.0)) * 0.5;
        usefulNormal = normalize(flatnormout);
    }
    else
    {
        UnitNormal = (normalize(normout) + vec3(1.0,1.0,1.0)) * 0.5;
        usefulNormal = normalize(normout);
    }

    //Texture stuff
    if ((renderflags & GK_TEXTURED) > uint(0))
        texture_value = (texture2D(diffuse, bettertexcoord));
    else
        texture_value = vec4(0.0,0.2,0.0,1.0);

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //UNCOMMENT THIS LINE IF YOU WANT ALPHA CULLING! It will slow down your application, be weary!
    // if ((renderflags & GK_ENABLE_ALPHA_CULLING) > uint(0))
        // if (texture_value.w == 0)
            // discard;
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    //Color stuff
    if ((renderflags & GK_FLAT_COLOR & GK_COLORED) > uint(0))
    {
            color_value = Flat_Vert_Color;
    } else {
        if ((renderflags & GK_COLORED) > uint(0))
        {
            color_value = Smooth_Vert_Color;
        } else {
            color_value = vec3(0.0,0.0,0.0);
        }
    }

    //primary_color and secondary_color stuff

    if ((renderflags & GK_COLOR_IS_BASE) > uint(0))
    {
        primary_color = color_value;
        secondary_color = texture_value.xyz;
    } else {
        primary_color = texture_value.xyz;
        secondary_color = color_value;
    }

     if ((renderflags & GK_TEXTURE_ALPHA_REPLACE_PRIMARY_COLOR) > uint(0))
     {
         //extremely clever programming results in perfect effect...
        primary_color = (primary_color * (1-texture_value.w)) + (texture_value.xyz * texture_value.w);
     }

    //EQUATION TIME!
    if ((renderflags & GK_TINT) > uint(0))
        finalcolor = primary_color + secondary_color;
    else if ((renderflags & GK_DARKEN) > uint(0))
        finalcolor = primary_color - secondary_color;
    else if ((renderflags & GK_AVERAGE) > uint(0))
        finalcolor = vec3(
        (primary_color.x + secondary_color.x)/2.0,
        (primary_color.y + secondary_color.y)/2.0,
        (primary_color.z + secondary_color.z)/2.0);
    else
        finalcolor = primary_color;

    vec4 ND_Modified = FindNDC();
    ND_Modified = vec4(
    (ND_Modified.x + 1.0) * 0.5,
    (ND_Modified.y + 1.0) * 0.5,
    (ND_Modified.z + 1.0) * 0.5,
    ND_Modified.w);

    // (diffuse component * texture) + specular
    gl_FragData[0] = vec4(finalcolor,specreflectivity);
    //gl_FragData[0] = (vec4(betterdiffuse,1.0) + vec4(ambient,ambient,ambient,1.0)) * vec4(Smooth_Vert_Color,0) + vec4(finalSpecular, 1.0);
    gl_FragData[1] = vec4(UnitNormal,specdamp); //Normals

    //INTENSE DEBUGGING OF FRAG DEPTH
    // if ((ourdepth+janear)/(jafar+janear) >= 0 && (ourdepth+janear)/(jafar+janear)<= 1.0)
    // {
        gl_FragData[2] = vec4((ourdepth+janear)/(jafar+janear), diffusivity, 1.0, emissivity);
    // }
    // else if ((ourdepth+janear)/(jafar+janear) < 0)
    // {
        // gl_FragData[2] = vec4(1.0,0.0,0.0,0.0);
    // } else if ((ourdepth+janear)/(jafar+janear) > 1.0){
        // gl_FragData[2] = vec4(0.0,1.0,0.0,0.0);
    // }

    //These are unnecessary and should be deleted.
    gl_FragData[3] = vec4(
        ambient,
        specreflectivity,
        specdamp/128.0, //This should give a wide range...
        emissivity
    );
    gl_FragData[4] = vec4(texture(worldaroundme,reflect(-vert_to_camera, usefulNormal)).xyz, 0); //To be used for cubemap reflections
}

```
> -2 votes

---
Tags: opengl, glsl
---


# Question
Title: How can I draw gizmos and move the drawn gizmos when moving the transform in the editor in scene view?
```
public void OnDrawGizmos() {
        if(_thisT == null) _thisT = transform;
            if(!Application.isPlaying && _posBuffer != _thisT.position+_startPosOffset){
                _posBuffer = _thisT.position+_startPosOffset;

            }
            if(_positionSphereDepth == -1){
                    _positionSphereDepth = _positionSphere;
                }
                if(_spawnSphereDepth == -1){
                    _spawnSphereDepth = _spawnSphere;
                }
            Gizmos.color = Color.blue;
            Gizmos.DrawWireCube (_posBuffer, new Vector3(_spawnSphere*2, _spawnSphereHeight*2 ,_spawnSphereDepth*2));
            Gizmos.color = Color.cyan;
            Gizmos.DrawWireCube (_thisT.position, new Vector3((_positionSphere*2)+_spawnSphere*2, (_positionSphereHeight*2)+_spawnSphereHeight*2 ,(_positionSphereDepth*2)+_spawnSphereDepth*2));
        }

```

\_posBuffer is Vector3 \_spawnSphereDepth is float

The problem is that it's drawing the cube in the center of the scene view window and when I'm changing the transform position the cube Gizmo is not moving.

Is there a way to draw the DrawWireCube so it will be position around the transform and when moving the transform that the gizmos draws will move with it too ?

# Answer
That is because the vector given is a world position. If you want a gizmo to be drawn with the player, you must add that transform's position:

```
public class Example : MonoBehaviour
{
    public Color color;
    public Vector3 gizmoPosition;
    public float radius;

    void OnDrawGizmos()
    {
        Gizmos.color = color;
        Vector3 newPosition = transform.position + gizmoPosition;
        Gizmos.DrawWireSphere(newPosition, radius);
    }
}

```

Hope it helps.
> 0 votes

---
Tags: unity, unityscript
---


title: A* implementation issue

text:
# Question
Title: A* implementation issue
I admit defeat, I must ask the community the same question it has been asked a million times before: "What is wrong with **MY** implementation of the A\* algorithm?"

I am getting some very wonky results, especially with goal locations which have a x-coordinate equal to or less than the actor's x-coordinate. There's gotta be something going on with how I'm searching through the neighbors, something with my heuristic, or even something with the use of my data structures...

Here is an example of some strange paths that it generates:

Here is my own version of the A\* that is dying on me:

```
/// <summary>
/// Tries to get a path from the start to the end.
/// </summary>
/// <param name="start">Start of the path.</param>
/// <param name="end">End of the path.</param>
/// <param name="grid">Grid of values indicating whether grid squares are open or closed.</param>
/// <param name="path">Path from start to end.</param>
/// <returns>Whether a valid path could be found.</returns>
public bool TryGetAStarPath(Point start, Point end, out List<Point> path)
{
    // setup the path
    path = new List<Point>();

    // if either start or end is bad then don't find a path
    if (!this.IsSquareOpen(start) || !this.IsSquareOpen(end))
    {
        return false;
    }

    // setup sets
    var closed = new Dictionary<Point, AStarNode>();
    var cameFrom = new Dictionary<Point, AStarNode>();
    var open = new LinkedList<AStarNode>();
    open.InsertNode(new AStarNode(start, null, end));

    // keep going until the open set has nothing in it
    while (open.Count > 0)
    {
        // node currently being examined
        var current = open.GrabAndRemoveFirst();

        // if the end was found then reconstruct the path and return it
        if (current.Position == end)
        {
            // construct the path
            var currentPathNode = current;
            while (currentPathNode != null && currentPathNode.Position != start)
            {
                // add node position to the path
                path.Add(currentPathNode.Position);

                // get the node this node came from
                cameFrom.TryGetValue(currentPathNode.Position, out currentPathNode);
            }

            // the path is currently reversed, correct it
            path.Reverse();

            // successfully found a path
            return currentPathNode.Position == start;
        }

        // add current to the closed set
        closed.Add(current.Position, current);

        // iterate through all the neighbors
        foreach (var neighbor in this.GetNeighbors(current, end))
        {
            // if the neighbor is already in the closed set or the square is not open then skip it
            if (!this.IsSquareOpen(neighbor.Position) || closed.ContainsKey(neighbor.Position))
            {
                continue;
            }

            // if the neighbor is in the open set then compare the g-score
            var testAgainstNode = open.Find(neighbor);
            if (testAgainstNode == null || testAgainstNode.Value.FScore < neighbor.FScore)
            {
                // set the came-from node
                if (cameFrom.ContainsKey(neighbor.Position))
                {
                    cameFrom.Remove(neighbor.Position);
                }

                cameFrom.Add(neighbor.Position, current);

                // add or replace the neighbor on the open set
                if (open.Contains(neighbor))
                {
                    open.Remove(neighbor);
                }

                open.InsertNode(neighbor);
            }
        }
    }

    // if we are here then the path was never found
    return false;
}

```

I am using a search for neighbors that looks like this:

```
/// <summary>
/// Gets all the neighboring grid squares to the current grid square based on its location.
/// </summary>
/// <param name="current">Current grid square to find the neighbor locations for.</param>
/// <param name="endPoint">Location of the end-point.</param>
/// <returns>Neighboring grid square locations.</returns>
private IEnumerable<AStarNode> GetNeighbors(AStarNode current, Point endPoint)
{
    // setup the search space
    var searchspace = new int[] { -1, 0, 1 };

    // find the neighbors
    foreach (var x in searchspace)
    {
        foreach (var y in searchspace)
        {
            // skip 0, 0
            if (x == y && x == 0)
            {
                continue;
            }

            // test if in bounds
            var testPoint = new Point(current.Position.X + x, current.Position.Y + y);
            if (testPoint.WithinBounds(this))
            {
                yield return new AStarNode(testPoint, current, endPoint);
            }
        }
    }
}

```

And finally my AStarNode object is defined as:

```
/// <summary>
/// A-Star node.
/// </summary>
class AStarNode
{
    // Variable declarations elided

    /// <summary>
    /// Instantiates a new instance of the <see cref="AStarNode"/> class.
    /// </summary>
    /// <param name="position">Position of the node on the grid.</param>
    /// <param name="parent">Node that this node comes from.</param>
    /// <param name="endPoint">The goal.</param>
    public AStarNode(Point position, AStarNode parent, Point endPoint)
    {
        // set the position
        this.Position = position;

        // calculate the scores
        this.CalculateScores(parent, endPoint);
    }

    /// <summary>
    /// Calculates the f, g, and h scores for this node.
    /// </summary>
    /// <param name="parent">Node that this node comes from.</param>
    /// <param name="endPoint">The goal.</param>
    private void CalculateScores(AStarNode parent, Point endPoint)
    {
        // h-score is the estimated distance to the end-point
        this.HScore = (float)Math.Sqrt(Math.Pow(endPoint.X - this.Position.X, 2) + Math.Pow(endPoint.Y - this.Position.Y, 2)) * HSCORE_MULTIPLIER;

        // g-score is the actual distance from the start
        if (parent == null)
        {
            this.GScore = 0;
        }
        else
        {
            this.GScore = parent.GScore + (parent.Position.X == this.Position.X || parent.Position.Y == this.Position.Y ? CARDINAL_MOVEMENT_COST : DIAGONAL_MOVEMENT_COST);
        }

        // f-score is g + h
        this.FScore = this.GScore + this.HScore;
    }

    public static bool operator ==(AStarNode left, Point right) => left.Position == right;
    public static bool operator !=(AStarNode left, Point right) => !(left == right);
    public override int GetHashCode() => -425505606 + EqualityComparer<Point>.Default.GetHashCode(Position);
    public override bool Equals(object obj)
    {
        var node = obj as AStarNode;
        return node != null &&
               Position.Equals(node.Position);
    }
}

```

Oh, and I guess it is also important to know how I'm inserting and removing from the LinkedList object. Why do I use a linked list? So that the node with the shortest path is always at the beginning with tiny insert and remove costs.

```
/// <summary>
/// Inserts the provided node into the linked list based on it's f-score value.
/// </summary>
/// <param name="list">Linked list to instert into.</param>
/// <param name="node">Node to insert.</param>
public static void InsertNode(this LinkedList<AStarNode> list, AStarNode node)
{
    // if the list is empty then just insert
    if (list.Count == 0)
    {
        list.AddFirst(node);
    }
    else
    {
        // start at the front of the list and move toward the end looking for the right spot to insert
        var compareNode = list.First;
        while (compareNode != null && compareNode.Value.FScore <= node.FScore)
        {
            compareNode = compareNode.Next;
        }

        // if the compare node is null then add to the end, otherwise add before the compare node
        if (compareNode == null)
        {
            list.AddLast(node);
        }
        else
        {
            list.AddBefore(compareNode, node);
        }
    }
}

/// <summary>
/// Grabs and removes the first node from the linked list.
/// </summary>
/// <param name="list">Linked list.</param>
/// <returns>First node.</returns>
public static AStarNode GrabAndRemoveFirst(this LinkedList<AStarNode> list)
{
    // if the list is empty then return null
    if (list.Count == 0)
    {
        return null;
    }

    // get the value to return and remove it from the list
    var toReturn = list.First;
    list.RemoveFirst();

    // return the node
    return toReturn.Value;
}

```

# Answer
> 3 votes
Since your goal is implementation rather than game dev, I highly recommend writing tools to test out your implementation.

As someone in comment section pointed out, it is better if you had traceable "executing on paper" some form of "I can look at and see where things are going wrong".

I am sure some of us could go through the pain of looking at your code but I doubt the possibility.

Only way for me to help you is "looking at your code then executing it in my head to understand how the code works" and that sounds just painful tbh.

I highly recommend for you to create something like below to help yourself to get a better idea on how your code works.

Though from the quick glance I can tell a few things that are wrong with your implementation.

There you are making a diagonal turn, then moving forward ahead then turning. It seems like your thinging doesn't properly handle "diagonal moving".

IF your diagonal moving would cost as much as to the adjacent tile then your path should be something like...

If you are applying the same movement cost for diagonal movement direction, it can explain the 2nd error case of your screenshot.

There is no cost difference between blue path and purple path because you set diagonal movement to cost as much as the adjacent movement.

But your 2nd debug shot, I can't even understand what is going on here.  There are more than three ways you can read this output. What is the direction and order in which your program is taking? I need you to tell me.

So basically,

1. I can *guess* what is wrong. I hope my guess helps.
2. If you actually want to get help and tackle this thing, you need better debug result for yourself and other people to look at and understand what is wrong with your code. Otherwise someone needs to look at your code and "run it in their head".

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


# Question
Title: How to make the camera follow the mouse in first or third person camera
I currently I have a game made of a few small scripts, the `PlayerController`, `PlayerStats`, and `CameraChange` (each below).

My question is how do I get the camera to follow the mouse movement? I want the player to be able to switch between each camera and look around with the mouse.

Any idea as to how I'd go about doing this? My current theory is I would some how have to access the current active camera and make it follow the mouse but not sure how to do that.

PlayerController-

```
using UnityEngine;

public class PlayerContorller : MonoBehaviour

{

    // Update is called once per frame
    void Update ()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;

        var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;

            transform.Rotate(0, x, 0);
        transform.Translate(0, 0, z);
    }
}

```

PlayerStats-

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

public class PlayerStats : MonoBehaviour {

    public int Health = 100;
    public int Stamina = 100;
    public int magic = 100;

    // Use this for initialization
    void Start () {

    }

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

        }
    }
}

```

CameraChange-

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

public class CameraChange : MonoBehaviour {

    public GameObject ThirdCam;
    public GameObject FirstCam;
    public int CamMode;

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

        if (Input.GetButtonDown("Camera"))
        {
            if (CamMode == 1)
            {
                CamMode = 0;
            }
            else
            {
                CamMode += 1;
            }
            StartCoroutine(CamChange());
        }
    }
    IEnumerator CamChange()
    {
        yield return new WaitForSeconds(0.01f);
        if(CamMode == 0)
        {
            ThirdCam.SetActive(true);
            FirstCam.SetActive(false);
        }
        if(CamMode == 1)
        {
            FirstCam.SetActive(true);
            ThirdCam.SetActive(false);
        }
    }
}

```

# Answer
You should create a new script called `MouseLookAt` and attach it to each camera that the player can "take control of" and look through.

This script determines whether or not its currently being controlled, and if so, takes in the mouse input and translates it into a rotation, applying that rotation value to the object the script is attached to.

In doing it this way you:

1. Get the behavior you want
2. Don't need to reference the camera from somewhere else
3. Have infinite extendability (no matter how many cameras you add, you don't have to change anything)

The "translate mouse into rotation" is very common and easy to find (here's one), but you'll have to modify it to handle the "is the player currently using this camera" part yourself, as its not a generic problem.

One option is to keep the script disabled, then when the player selects a new camera:

1. disable the mouse look script on the current camera (if any)
2. get the new camera
3. enable the mouse look script on that camera (`cam.GetComponent<MouseLookAt>().enabled = true`)
4. set the camera as the current camera

You're likely already doing step 2 anyway.
> 2 votes

# Answer
This is script to switch between cameras. Everytime left mouse-button is clicked, `myInt` +1. Camera with index `myInt` in the list is then activated, with others deactivated. When `myInt` exceeds `List.Count`, `myInt` is then reset back to 0;

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

public class MyCameraController : MonoBehaviour {
    [SerializeField]
    private List<Camera> myList;

    public Transform activeCamTransf;

    private int myInt;

    private void Update () {
        if (Input.GetMouseButtonDown (0)) {
            ActivateCam (SwitchMyInt ());
        }
    }

    private int SwitchMyInt () {
        if (myInt < myList.Count - 1) {
            myInt += 1;
        } else {
            myInt = 0;
        }
        return myInt;
    }

    private void ActivateCam (int i) {
        if (i < myList.Count) {
            myList [i].enabled = true;
            activeCamTransf = myList [i].transform;

            foreach (Camera camTemp in myList) {
                if (camTemp != myList [i]) {
                    camTemp.enabled = false;
                }
            }
        }
    }
}

```

---

This is script to rotate the active camera. Rotation is achieved by accumulating X and Y axis of the mouse, then applying it to the `EulerAngle` of the `Transform` of the `GameObject`.

```
using UnityEngine;

public class CamRotationController : MonoBehaviour {
    [SerializeFiled]
    private MyCameraController myCameraController;

    [SerializeField]
    private float speedX;

    [SerializeField]
    private float speedY;

    private float x;
    private float y;

    void Update () {
        x += speedX * Input.GetAxis("Mouse X") * Time.deltaTime;
        y -= speedY * Input.GetAxis("Mouse Y") * Time.deltaTime;

        myCameraController.activeCamTransf.eulerAngles = new Vector3(x, y, 0);
    }
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Can I implement allocation-free time releated event scheduler via pure C#?
I read some article about a gameloop, based on Actor system. (yes, it is Development & Deployment of Multiplayer Online Games Vol.2 by 'No Bugs' Hare)

Here is pseudocode.

```
while(true) {
    wait_for_event();
    read_and_process_inputs();
    update();
    post_updates_to_clients();
    post_timer_event(time_left_until_end_of_network_tick);
}

```

It has post\_timer\_event() instead of thread sleep method. I want to know that is it possible to implement like this by using pure C#? especially, without any memory-allocation or performance issue. If it is possible, I want to know how implement it (or ideas, keywords for googling).

Thanks.

# Answer
> 0 votes
On C# you make use of **IEnumerators** and the **yield** keyword. **Unity**, for example, makes use of these features for coroutines.

How it works? the yield, which only can be declared on a IEnumerator, statement returns an object, then on the next tick of that IEnumerator reference continues on the yield (not at the start of a function).

As an example, suppose you have a **deltaTime** global variable, preferably on a static Time class (I am just inventing this class for example's purposes, every GameLoop library must have some sort of delta time that tracks how much time passed last frame), on your GameLoop you would have an IEnumerator variable getting called its **MoveNext()** method (it both moves to the next iterator and also returns true if it has successfully moved to a next element), when the iterator has no more reasons to yield (on this case, when currentTime reaches approximately zero), the IEnumerator wont't move to a next iterator, finishing the wait.

Just take note, that this is not the same as a threading, since that is parallel programming, this is concurrent, it means that it will run after another instruction, when parallel runs certain operations at the same time.

Example:

```
public static class Time
{
    private static int fps;
    private static float deltaTime;

    public static int FPS
    {
        get { return fps; }
        set
        {
            fps = value;
            deltaTime = (1f/fps);
        }
    }

    public static float DeltaTime { get { return deltaTime; } }

    static Time()
    {
        FPS = 60;
    }
}

public class Game
{
    public float waitTime;
    IEnumerator waitAndDo;

    void GameLoop()
    {
        while(true)
        {
            if(waitAndDo == null) waitAndDo = WaitAndDo(waitTime, DoSomething);
            if(!waitAndDo.MoveNext()) waitAndDo = null;
        }
    }
    void DoSomething()
    {
        // Does something...
    }

    IEnumerator WaitAndDo(float seconds, Action onWaitEnds)
    {
        float currentTime = seconds;
        while(currentTime > 0.0f)
        {
            /// On 60 frames divided by seconds it will reach 0.
            currentTime -= Time.DeltaTime;
            yield return null;
        }
        if(onWaitEnds != null) onWaitEnds();
    }
}

```

This is something rather hard to explain by myself, so I encourage you to check **Jamie King**'s channel on Youtube, he has a pretty good series of IEnumerators and yield statements (see this **IEnumerator's video**). This is basically an interface used for all data types that a **foreach** can receive, so it is used most of the times for iterations, but it can be used for the aforementioned coroutine pattern. Of course, always check .NET's API first than any other thing regarding C#.

Hope it helps, any question don't hesitate to ask, since I may have omitted something or left ambiguous terms.

---
Tags: c#, game-loop, events
---


# Question
Title: Destroying a ship removes both the ship and the bullets it has fired
So I'm making a game where you fire bullets at enemy ships which are flying past you. The enemy ships are also firing at a straight line in front of them. The bullets are made into a list of another class and the enemy ships are as well. Both the player and the enemy ships fire from the same class of bullets but just from different initialized lists.

My issue here is that when a bullet fired from the player's ship destroys an enemy ship, every bullet which in already in play after being fired by the same ship is also removed and I don't know how to only remove the ship while leaving the bullets in play. Sorry if this is confusing.

Here is my code which detects collisions between created rectangles on my player bullets and the enemies.

```
public void HitEnemy()
    {
        foreach (Bullets bullet in bullets)
        {
            bulletbb = new Rectangle(
                (int)bullet.position.X,
                (int)bullet.position.Y,
                texWeaponBullet.Width,
                texWeaponBullet.Height);

            foreach (Enemies enemy in enemies)
            {
                enemybb = new Rectangle(
                    (int)enemy.position.X,
                    (int)enemy.position.Y,
                    texEnemy1.Width,
                    texEnemy1.Height);

                if (bulletbb.Intersects(enemybb))
                {
                    bullet.isVisible = false;
                    enemy.isVisible = false;
                }
            }
        }
    }

```

If isVisible = false then the object is removed from play.

Here is my Enemies class:

```
namespace MainProject
{
class Enemies
    {
    public Texture2D texture;

    public Vector2 position;
    public Vector2 velocity;

    public bool isVisible = true;

    Random random = new Random();
    int randY;
    int randX;

    //Bullets
    List<Bullets> eBullets = new List<Bullets>();
    Texture2D bulletTexture;
    float shoot = 0;

    public Enemies(Texture2D newTexture, Vector2 newPosition, Texture2D newBulletTexture)
    {
        texture = newTexture;
        position = newPosition;
        bulletTexture = newBulletTexture;

        randY = random.Next(-4, 4);
        randX = random.Next(-4, -1);

        velocity = new Vector2(-4, 0);
    }

    public void Update(GraphicsDevice graphics, GameTime gameTime)
    {
        position += velocity;

        if (position.Y <= 0 || position.Y >= 600 - texture.Height)
        {
            velocity.Y = -velocity.Y;
        }

        if (position.X < 0 - texture.Width)
        {
            isVisible = false;
        }

        shoot += (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (shoot > 1)
        {
            shoot = 0;
            ShootBullets();
        }

        UpdateBullets();
    }

    public void UpdateBullets()
    {
        foreach(Bullets bullet in eBullets)
        {
            bullet.position += bullet.velocity;
            if (bullet.position.X < 0)
            {
                bullet.isVisible = false;
            }
        }
        for(int i = 0; i < eBullets.Count; i++)
        {
            if (!eBullets[i].isVisible)
            {
                eBullets.RemoveAt(i);
                i--;
            }
        }
    }

    public void ShootBullets()
    {
        Bullets newBullet = new Bullets(bulletTexture);
        newBullet.velocity.X = velocity.X - 1.5f;
        newBullet.position = new Vector2(position.X + newBullet.velocity.X,
            position.Y + (texture.Height / 2f) - (bulletTexture.Height / 2));

        newBullet.isVisible = true;
        if (eBullets.Count < 3)
        {
            eBullets.Add(newBullet);
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        foreach (Bullets bullet in eBullets)
        {
            bullet.Draw(spriteBatch);
        }

        spriteBatch.Draw(texture, position, Color.White);
    }
}
}

```

I am at a bit of a loss for what to do. Any help would be appreciated and tell me if you need any more information because there might be something I missed.

# Answer
> 3 votes
As you're probably aware, since the ship is responsible for drawing and moving the bullets it created, the bullets it created will no longer be drawn or updated when their creator is destroyed.

Instead, consider having another object that manages bullets -- let's call it *BulletManager*. BulletManager has UpdateBullets, which it calls each frame. It also has ShootBullets, taking position as an argument. When an enemy shoots, it calls BulletManager.ShootBullets(position).

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


# Question
Title: Perlin noise terrain: 3 coordinates from one
I am making a game with procedural terrain, like minecraft. I have a perlin noise function which takes one integer and returns a number between zero and one. However, for terrain, I need a single density value from three coordinates: x, y and z. But my noise function only takes one number. Should I take the average of the noise values for x, y and z for a single density value? Or something else?

# Answer
The short answer is it depends.

Yes, you can use three Perlin noise functions, average them & use the result. This will map 3 input parameters to a single output noise parameter. But there are some complications.

First, the noise functions should be uniquely seeded, otherwise you'll get some odd results. For instance, if you use the same seed & function for each coord, the coords \<1,2,3\>,\<1,3,2\>,\<2,1,3\>,\<2,3,1\>,\<3,1,2\>,\<3,2,1\> will all have the same values & this can lead to undesirable symmetries & artifacts in the final result.

Second, even if you do use uniquely seeded functions for each coord, taking the average essentially washes out or mutes some of the original signal.

Usually, the preferable solution is to use a higher dimension Perlin noise function. Perlin noise can be defined as an n-dimensional function. If you need a unique output for 3 input parameters, using a 3D Perlin or Simplex noise function will give you what you want without worrying about multiple seeds, muted results & other annoyances.

That being said, if you haven't already done so, read through some of the procedural-generation & terrain posts. For instance you may discover that you actually want to use 2d noise function to create a height map for the surface & then use an additional technique to carve out caves beneath the surface.
> 1 votes

# Answer
There are higher-dimensional noise functions available, but if you're stuck with this one, you can always consider using the Cantor Pairing function. It is very easy to implement and can be pre-computed.

See https://en.wikipedia.org/wiki/Pairing\_function#Cantor\_pairing\_function for further details.
> 0 votes

---
Tags: procedural-generation, terrain, perlin-noise
---


# Question
Title: How to correctly combine scoreboard data?
I need a help with a scoreboard I am making. Here's the scoreboard I want to achieve:

I actually have 4 tables and each tables has its own scoreboard but for this question only one table matters.

Here's how I am creating this kind of scoreboard:

```
if (gametable_no == 1)
{
    for (int i = 0; i < tzPlayInfo.Instance.bc_gametable_history_list.Count; i++)
    {
        newString[0] += tzPlayInfo.Instance.bc_gametable_history_list[i].r;
        newString[0] += ",";
    }
    string[] groupedString = newString[0].Split(',');

    foreach (string allchars in groupedString)
    {
        int x = 0;
        int y = 0;

        GameObject o = Instantiate(prefab_big_road[0]) as GameObject;
        o.transform.SetParent(pos_big_road[0]);
        o.transform.localScale = Vector3.one;
        o.transform.localPosition = new Vector3(2.0f, -5.0f, 0f);
        o.transform.localPosition = new Vector3(o.transform.localPosition.x + x,
            o.transform.localPosition.y + y, o.transform.localPosition.z);

        if (allchars.Contains(playerwinnopairboth))
        {
            o.GetComponent<UISprite>().spriteName = "layout_player_bigline-01";
            NGUITools.SetActive(o, true);
        }
        if (allchars.Contains(bankerwinnopairboth))
        {
            o.GetComponent<UISprite>().spriteName = "layout_banker_bigline-01";
            NGUITools.SetActive(o, true);
        }
        if (allchars.Contains(tienopairboth))
        {
            o.GetComponent<UISprite>().spriteName = "layout_tie_bigline-01";
            NGUITools.SetActive(o, true);
        }
    }
}

```

The result I get with this code is this:

Here's what the data I use to generate the table looks like:

`Gametable 1 history : P ,P ,P ,B ,B P,P P,TBP`

So I need a way to know if the character is *changing* in the `gametable 1 history data`.

Here's the expected scoreboard output with the data above:

If the value is not changing like `P ,P ,P` then the position should only increment on the y-axis. If the next value is different like `B ,` then it will move on the x-axis.

So, how would I implement this?

# Answer
I came up with this

```
if (table.GetLength(0) < xIndex)
            {
                break;
            }

            if (previousValue.Equals(newPreviousValue) && yIndex < table.GetLength(1))
            {
                yIndex += 1;
                table[xIndex, yIndex] = previousValue;
            }
            else
            {
                xIndex += 1;
                yIndex = 0;
                table[xIndex, yIndex] = previousValue;
            }
            newPreviousValue = previousValue;

```

Thanks Tyyppi\_77
> 0 votes

# Answer
I'm not a C# user so the solution is pseudo-code, but it should be relatively trivially translated into actual compiling C# that uses the correct GUI positioning stuff that you need. I just use `x` and `y` to denote the position of the current score.

Anyways, the important bit here is to keep track of the previous item.

```
string previous = "";

string scores = history.split(",");

int x = 0, y = 0;

foreach (string score in scores)
{
    if (score == previous)
    {
        // Next row:
        y += 1
        addToTable(score, x, y);
    }
    else
    {
        // Next column:
        x += 1
        y = 0
        previous = score;
        addToTable(score, x, y);
    }
}

```

The code simply iterates over all the scores, and keeps track of the previous score. If the items match, the row is incremented. Otherwise we move onto the next column and start from the top again.
> 1 votes

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


# Question
Title: How do I use more than 32 textures in my game?
I'm building a game in OpenGL, relying on shaders as much as possible because python. However, I think I've been working under a misunderstanding of OpenGL since I started.

I've abstracted stuff into a homemade shader class/object that takes vertices and images, and turns them into VBOs and textures, and a `draw()` function. Not realizing there was a small limit on the `GL_TEXTURE_*` stuff, I was giving each one its own texture slot (as I'm thinking of them). I also hadn't yet bothered making sure the same models were using the same shader. You can see how I was running into problems.

So, just how do you deal with using more than 16/32/`GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS` textures in a frame? If I have floor, a player, three NPCs, four types of tree and a house, (each with unique textures) how am I going to add a fridge?

# Answer
> 13 votes
You only need the textures bound when you'd need to refer to them during the rendering of an object. You do not need every texture you will ever use bound to the pipeline at once.

Thus, to render the floor, you bind only the textures you need for the floor; then you render the floor. Then you bind only the textures you need for the NPCs, and render all the NPCs. Et cetera. This generalizes to something like

```
foreach (object in the scene) {
  texture_slot = 0;
  foreach (texture used by that object) {
    bind the texture to texture_slot
    ++texture_slot
  }

  draw the object
}

```

Note that texture state changes like this are relatively expensive, so when possible you want to minimize them (perhaps by sorting your object list by which textures they use, so you don't switch back and forth).

However, this is the general idea that you want to employ.

# Answer
> 0 votes
You could merge multiple images into one (like a sprite sheet) if they are small enough then crop the UV to that selected image when you need to render it. It helps avoid rebinding texture slots if you've got a lot of small images.

# Answer
> 0 votes
When one runs against this limit, then one is almost certainly doing something wrong.

Using lots of textures has many obvious and not-so-obvious disadvantages, the most obvious one being that you have no way of knowing *how many* you can use (at the time of writing the program). Sure, in theory you would query the limit, but let's stay realistic. It's not a very workable (or efficient) approach. In particular, what do you do if you have 17 textures, and the limit is 16? Leave one object black?

Binding one of several small sets of textures at a time as needed is a common approach, but is not the optimum since changing texture descriptor sets is possibly a massively expensive operation. GPUs can typically switch between a very small number of descriptor sets for almost free, but whenever you exceed that unknown small number (which might be something like 2 or 4), you have a complete pipeline stall. That's going to kill you.
So, rebinding textures once or twice per frame is probably no issue, but doing it 200 times is a bad idea. Keyword: batching. When one says "batching" that doesn't necessarily mean draw calls (those are actually pretty cheap with GL). Batching refers to leaving all state (such as textures) as it is. If one changes textures (or state in general) mid-frame, then at the very least care must be taken to *sort* and thus batch all objects by state.

Ideally, one uses a single small set of textures (never change bindings) where the many different textures are either packed in what's called a texture atlas, or if the hardware supports it (virtually all hardware nowaday does, core since 3.0) *different* textures are actually layers within *the same* array texture.
A texture atlas works with even older hardware, but has a few little gotchas (bleeding, derivatives, etc) that you need to take care of. Packing textures into an array texture "just works". All you need is one uniform to pick the right layer.

# Answer
> 0 votes
You are misunderstanding `GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS`.

This value dictates the maximum number of simultaneously bound textures at any given time, and that you can access in a shader via `texture(tex_id,coord.xy)`.

You can have as many textures as you have GPU memory, and more, if you have a smart asset manager than loads/unloads assets as required. But I digress.

In all practical circumstances, unless the hardware specification of `GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS` is something low, like a value of two, it should have zero impact on your game. Even with a relatively fancy rendering system, you should need no more than 5-6 textures bound at once for each rendered object.

---
Tags: opengl, textures, python
---


# Question
Title: How do you Draw a path and have a GameObject follow it?
How would you go about creating a path that a gameobject would follow?

I'm looking to create similar functionality that you see in some RTS games. most notability the Total War series does this well. here are a few screen shots for reference.

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

Goal.

1. Click a Unit
2. Hold the mouse button down and drag to draw a line
3. Release the mouse button. unit follows path drawn

# Answer
> 1 votes
If you are talking about a simple (straight) line, you can simply create two `Vector3`, one called `startPosition` which equals to the point that you clicked, and one called `endPosition` which while holding your mouse it equals the mouse location, and then you release it, it keeps that last value. After that, how to draw the path is up to you. You can use a `LineRenderer` with the above coordinates, or you can be more creative with a 3D mesh.

If you want to make something more complicated, like a line that has angles, you can still use `LineRenderer`, just create multiple points, and each time you click the mouse (or any other input you like) create a new point on that position.

If you want curves, you can keep all the points like above, but you can also add control points (depending what kind of curve you want to make) and calculate their position based on their surrounding points, to make a smooth curve. If interested I'd suggest taking a look at Bezier Curves (Wikipedia). After you have the points (and their control points), there are some options how to draw them on the screen. I'd suggest taking a look at this tutorial.

---
Tags: unity
---


# Question
Title: Is there a stable Unity release for linux?
I am doing some machine learning and need to run unity on linux but didn't come across the stable release, if anyone is working on unity on linux, please point me towards a stable release.

# Answer
> 2 votes
No. At this time the Unity site still refers to the Linux editor as an "experimental" Beta feature. There is not a stable release. The latest Linux builds, release notes, and known issues are documented in this Unity forum thread.

In future, please direct this type of software query to the makers of that software. Because it's time-sensitive (maybe in two months there *will* be a stable Linux build released), handling it through our Q&A here risks leaving misleading signposts for future users.

> (So, if you're a future user reading this after May 2018: don't take my word for it — check the manufacturer's website for the most up to date information)

---
Tags: unity, linux, release
---


# Question
Title: How perform for obj follow mouse with angle?
how i can perform for sprite follow mouse if i change angle ? If i change angle the sprite no more follow mouse correctly. **I absolutely need the obj follow mouse with pivot.**

https://jsfiddle.net/jonforum/ow9w7rfz/10/

thank a lot for help

**edit:** if you can help me with math problem !

How i can compute from a sprite (radian.skew,pivot) a new point XY ?

Example i move pivot to XY. And i move rotation to ( randian || degree ) After i move again pivot with mouse compute... all became weird..

How i can compute rotation but base on the position from pivot ? for now here it my try code. thank guys, i have difficult with deep math. Also, I would like to compute skew

# Answer
> 0 votes
This looks like it might be as simple as setting your position, instead of your pivot.

```
// add a graphics instance
var rec = new PIXI.Graphics();
rec.beginFill(0x00ff00);
rec.drawRoundedRect(-20, -65/2, 40, 65, 4); // Shifted so the rect is centered across 0,0

// setup
rec.pivot.set(0,0);                         // Pivot at the center 0,0
rec.position.set(500/2,500/2);
rec.rotation = 45 * Math.PI / 180;
stage.addChild(rec);
renderer.render(stage);

//** listener ********
    var updatePosition = function(event) {
      this.position.set(event.layerX,event.layerY); // Set postion, no offset.

      renderer.render(stage);
    };

    document.addEventListener('mousemove', updatePosition.bind(rec));

```

---
Tags: mathematics, javascript, geometry, pixi.js
---


# Question
Title: What is the best way to code grinding for a skate game in Unity?
I am making a inline skate game, what could be the best method to code the grinding system, there are many various and complex stuff to use but what could be used to set it up simple and not that complex? I made some research, I come up with Catmull Splines or Bezier curves but that seems very complex, my Idea is getting something simple to build up on that and improve it. Maybe use a simple waypoint system that the player follows along while jump on a trail or something. Any ideas or suggestions? Because you cant find any tutorials on grinding system in YouTube or somewhere.

Thanks.

# Answer
> 1 votes
actually catmull splines and bezier curves are probably the easiest method to go about this. there's plenty of plugin's that can provide this kind of functionality. take a look at the leantween plugin, it's great, and you could wrap it into a scriptable object: \[link\]https://www.assetstore.unity3d.com/en/#!/content/3595 this plugin allows you to define paths, and you could read them out in your code, to get the waypoints. then simply iterate over them. edit: Here's an example of code, set up to create an instance of an LTSpline on a gameObject:

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

public class PathSpline : MonoBehaviour{
public Color color;

[HideInInspector]
public Vector3[] splinePoints;
    [HideInInspector]
public LTSpline  spline;
public Vector3[] localPts;

int i,j;
[ExecuteInEditMode]
void Start(){
    j = 0;
    GameObject parent = this.gameObject;
    //Vector3[] localPts = new Vector3[splinePoints.Length];
    if (localPts.Length > 2) {
        System.Array.Resize (ref splinePoints, localPts.Length);
    }
    for (j = 0; j < localPts.Length; j++) {
        if(parent.transform.TransformPoint(localPts[j]) != splinePoints [j]){
            splinePoints[j] = parent.transform.TransformPoint(localPts[j]);
        }
    }
    if (splinePoints.Length >= 4) {
        System.Array.Resize (ref spline.pts, splinePoints.Length);
        spline = new LTSpline (splinePoints);

        //System.Array.Resize (ref spline.ptsAdj, splinePoints.Length);
        //spline.ptsAdjLength = splinePoints.Length;
    }
}

```

# Answer
> 1 votes
Catmull splines and Bezier curves are no doubt the easiest method, although Bezier curves have the downside of not passing through the actual waypoints. Another option is to use Hermite curves.

---
Tags: unity, c#, rotation, movement, beziers
---


# Question
Title: Can i somehow set update time for FixedUpdate?
I'm just curious if can i have more control over that function.

# Answer
> 0 votes
Please remember to search the documentation first.

* In the Unity Editor, you can control the period of FixedUpdate ticks using the Time Manager (Edit \> Project Settings \> Time)
* In scripts, you can set this period via Time.fixedDeltaTime

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


# Question
Title: Is there a way to run Unity without rendering the scene on the monitor (headless)?
I am doing some machine learning and I get my environment from Unity in the form of images but the training is taking too long and it keeps me from doing anything else on my system. Is there a way to hide the simulation rendering? Any help will be highly appreciated.

# Answer
Run Unity in batch mode with `-batchmode` in combination with `-executeMethod <ClassName.MethodName>` (and likely `-quit`, which quits the Editor after commands have finished executing).

For example:

```
"C:\Program Files\Unity\Editor\Unity.exe" -quit -batchmode -executeMethod MachineLearningTrainer.Start

```

Note `executeMethod` only works with static methods.

For more information, see Unity's documentation on Command line arguments.
> 2 votes

---
Tags: unity, rendering, simulations
---


# Question
Title: How to create loading bar for asset bundles on Unity (without changing scene)?
So from the official documentation and unity forum now I know that there's async version of LoadFromFile (that I also will probably call `UnityWebRequest.GetAssetBundle` later for updated asset). Now the problem is where can I call it, and how to get the `.progress` value, converting from this:

```
public AssetManager()
{
    if (!useAssetBundle) return;
    foreach (var bundle_name in bundle_names)
    {
        var full_path = Path.Combine(Application.streamingAssetsPath + "/Bundle/", bundle_name);
        var bundle = AssetBundle.LoadFromFile(full_path);
        if (bundle == null) LogHelper.Critical("Failed to load AssetBundle {0}", full_path);
        bundles[bundle_name] = bundle;
    }
}

```

To this (that obviously wrong):

```
private List<AssetBundleCreateRequest> loadPro = new List<AssetBundleCreateRequest>();

private IEnumerator<AssetBundle> _loadOneAssetBundle(string full_path)
{
    var creq = AssetBundle.LoadFromFileAsync(full_path);
    loadPro.Add(creq);
    yield return creq.assetBundle;
}

public AssetManager(MonoBehaviour parent)
{
    if (!useAssetBundle) return;
    foreach (var bundle_name in bundle_names)
    {
        var full_path = Path.Combine(Application.streamingAssetsPath + "/Bundle/", bundle_name);
        var bundle = parent.StartCoroutine(_loadOneAssetBundle(full_path)).assetBundle; // NOPE T_T)
        if (bundle == null) LogHelper.Critical("Failed to load AssetBundle {0}", full_path);
        bundles[bundle_name] = bundle; // NOPE 'n')
    }
}

public void Update()
{
    var progress = 0f;
    foreach (var pro in loadPro)
    {
        progress += pro.progress;
    }
    LogHelper.Debug("Progress %f",progress);
}

```

# Answer
> 2 votes
Remember, when you start a coroutine, your execution doesn't block and wait for it to finish. It continues to the next line immediately.

So, the problems in your code are:

```
var bundle = parent.StartCoroutine(_loadOneAssetBundle(full_path)).assetBundle;

```

A) StartCoroutine just starts a Coroutine - it doesn't load your asset bundle for you (it doesn't know what an AssetBundle is!) so you can't fetch a reference to your bundle out of it like this.

```
if (bundle == null) LogHelper.Critical("Failed to load AssetBundle {0}", full_path);
bundles[bundle_name] = bundle;

```

B) Even if you could, the Coroutine has only just started at this point. The load hasn't had a chance to complete yet, so you're trying to grab your bundle too early.

Instead, you want to read your AssetBundle *after* the load has finished *inside your Coroutine*. This adapted straight from the documentation for LoadFromFileAsync:

```
IEnumerator LoadAssetBundleFromPath(string path)
{
    var bundleLoadRequest = AssetBundle.LoadFromFileAsync(path);

    // Track progress while it's loading.
    loadProgress.Add(bundleLoadRequest);

    // Wait until the load has finished.
    yield return bundleLoadRequest;

    // Done tracking.
    loadProgress.Remove(bundleLoadRequest);

    // NOW it's safe to grab the bundle, since we waited for it to load.
    var myLoadedAssetBundle = bundleLoadRequest.assetBundle;
    if (myLoadedAssetBundle == null)
    {
        Debug.Log("Failed to load AssetBundle!");
        yield break;
    }

    // Put your code that stores / uses the AssetBundle here.
}

```

---
Tags: unity, assets, coroutines
---


title: Does == cause branching in GLSL?

text:
# Question
Title: Does == cause branching in GLSL?
Trying to figure out exactly what causes branching and what doesn't in GLSL.

I'm doing this a lot in my shader:

```
float(a==b)

```

I use it to simulate if statements, without conditional branching... but is it effective? I don't have if statements anywhere in my program now, nor do I have any loops.

EDIT: To clarify, I do stuff like this in my code:

```
float isTint = float((renderflags & GK_TINT) > uint(0)); // 1 if true, 0 if false
    float isNotTint = 1-isTint;//swaps with the other value
    float isDarken = float((renderflags & GK_DARKEN) > uint(0));
    float isNotDarken = 1-isDarken;
    float isAverage = float((renderflags & GK_AVERAGE) > uint(0));
    float isNotAverage = 1-isAverage;
    //it is none of those if:
    //* More than one of them is true
    //* All of them are false
    float isNoneofThose = isTint * isDarken * isAverage + isNotTint * isAverage * isDarken + isTint * isNotAverage * isDarken + isTint * isAverage * isNotDarken + isNotTint * isNotAverage * isNotDarken;
    float isNotNoneofThose = 1-isNoneofThose;

    //Calc finalcolor;
    finalcolor = (primary_color + secondary_color) * isTint * isNotNoneofThose + (primary_color - secondary_color) * isDarken * isNotNoneofThose + vec3((primary_color.x + secondary_color.x)/2.0,(primary_color.y + secondary_color.y)/2.0,(primary_color.z + secondary_color.z)/2.0) * isAverage * isNotNoneofThose + primary_color * isNoneofThose;

```

EDIT: I know why I don't want branching. I know what branching is. I'm glad you're teaching the children about branching but I would like to know myself about boolean operators (and bitwise ops but I'm pretty sure those are fine)

# Answer
What causes branching in GLSL depends on the GPU model and OpenGL driver version.

Most GPUs seem to have a form of "select one of two values" operation that has no branching cost:

```
n = (a==b) ? x : y;

```

and sometimes even things like:

```
if(a==b) {
   n = x;
   m = y;
} else {
   n = y;
   m = x;
}

```

will be reduced to a few select-value operation with no branching penalty.

Some GPU/Drivers have (had?) a bit of a penalty on the comparison operator between two values but a faster operation on comparison against zero.

Where it might be faster to do:

```
gl_FragColor.xyz = ((tmp1 - tmp2) != vec3(0.0)) ? E : tmp1;

```

rather than compare `(tmp1 != tmp2)` directly **but this is very GPU and driver dependant** so unless you are targeting a very specific GPU and no others I recommend using the compare operation and leave that optimising job to the OpenGL driver as another driver might have an issue with the longer form and be faster with the simpler, more readable way.

"Branches" aren't always a bad thing either. For example on the SGX530 GPU used in the OpenPandora, this scale2x shader (30ms) :

```
    lowp vec3 E = texture2D(s_texture0, v_texCoord[0]).xyz;
    lowp vec3 D = texture2D(s_texture0, v_texCoord[1]).xyz;
    lowp vec3 F = texture2D(s_texture0, v_texCoord[2]).xyz;
    lowp vec3 H = texture2D(s_texture0, v_texCoord[3]).xyz;
    lowp vec3 B = texture2D(s_texture0, v_texCoord[4]).xyz;
    if ((D - F) * (H - B) == vec3(0.0)) {
            gl_FragColor.xyz = E;
    } else {
            lowp vec2 p = fract(pos);
            lowp vec3 tmp1 = p.x < 0.5 ? D : F;
            lowp vec3 tmp2 = p.y < 0.5 ? H : B;
            gl_FragColor.xyz = ((tmp1 - tmp2) != vec3(0.0)) ? E : tmp1;
    }

```

Ended up dramatically faster than this equivalent shader (80ms) :

```
    lowp vec3 E = texture2D(s_texture0, v_texCoord[0]).xyz;
    lowp vec3 D = texture2D(s_texture0, v_texCoord[1]).xyz;
    lowp vec3 F = texture2D(s_texture0, v_texCoord[2]).xyz;
    lowp vec3 H = texture2D(s_texture0, v_texCoord[3]).xyz;
    lowp vec3 B = texture2D(s_texture0, v_texCoord[4]).xyz;
    lowp vec2 p = fract(pos);

    lowp vec3 tmp1 = p.x < 0.5 ? D : F;
    lowp vec3 tmp2 = p.y < 0.5 ? H : B;
    lowp vec3 tmp3 = D == F || H == B ? E : tmp1;
    gl_FragColor.xyz = tmp1 == tmp2 ? tmp3 : E;

```

You never know in advance how a specific GLSL compiler or a specific GPU will perform until you benchmark it.

---

To add the to point (even tho I don't have actual timing numbers and shader code to present you for this part) I currently use as my regular test hardware:

* Intel HD Graphics 3000
* Intel HD 405 Graphics
* nVidia GTX 560M
* nVidia GTX 960
* AMD Radeon R7 260X
* nVidia GTX 1050

As a wide range of different, common, GPU models to test with.

Testing each with Windows, Linux proprietary, and Linux open source OpenGL & OpenCL drivers.

And every time I try to micro-optimise GLSL shader (as in the SGX530 example above) or OpenCL operations for one particular GPU/Driver combo **I end up equally hurting the performance on more than one of the other GPUs/Drivers.**

So other than clearly reducing **high-level mathematical complexity** (eg: convert 5 identical divisions to a single reciprocal and 5 multiplications instead) and reducing texture lookups/bandwidth, it most likely will be a waste of your time.

Every GPU is too different from the others.

If you'd be working specifically on (a) gaming console(s) with a specific GPU this would be a different story.

The other (less significant for small game devs but still notable) aspect of this is that computer GPU drivers might one day silently replace your shaders (**if your game becomes popular enough**) with custom re-written ones optimised for that particular GPU. Doing that all work for you.

They will do this for popular games that are frequently used as benchmarks.

**Or if you give your players access to the shaders so they can easily edit them themselves some of them might squeeze a few extra FPS for their own benefit.**

For example there are fan-made shader & texture packs for Oblivion to dramatically increase frame rate on otherwise barely-playable hardware.

And lastly, once your shader get complex enough, your game almost completed, and you start testing on different hardware you'll be busy enough just fixing your shaders to work at all on a variety of GPUs as it is due to various bugs you wont have time to optimise them to that degree.
> 44 votes

# Answer
@Stephane Hockenhull's answer pretty much gives you what you need to know, its going to be entirely hardware dependent.

But let me give you some examples of *how* it can be hardware dependent, and why branching is even an issue at all, what does the GPU do behind the scenes when branching *does* take place.

My focus is primarily with Nvidia, I have some experience with low level CUDA programming, and I see what PTX (IR for CUDA kernels, like SPIR-V but just for Nvidia) is generated and see the benchmarks of making certain changes.

# Why is Branching in GPU Architectures such a big deal?

Why is it bad to branch in the first place? Why does do GPUs try to avoid to branch in the first place? Because GPUs typically use a scheme where threads share the same *instruction pointer*. GPUs follow a SIMD architecture typically, and while the granularity of that may change (ie 32 threads for Nvidia, 64 for AMD and others), at some level a group of threads share the same instruction pointer. This means that those threads need to be looking at the same line of code in order to work together on the same problem. You may ask how they are able to use the same lines of code and do different things? They use different values in registers, but those registers are still used in the same lines of code across the entire group. What happens when that stops being the case? (IE a branch?) If the program truly has no way around it, it splits up the group (Nvidia such bundles of 32 threads are called a Warp, for AMD and parallel computing academia, it is referred to as a wavefront) in to two or more different groups.

If there is only two different lines of code you would end up on, then the working threads are split up between two groups (from here one I'll call them warps). Lets assume Nvidia architecture, where the warp size is 32, if half of these threads diverge then you will have 2 warps occupied by 32 active threads, which makes things half as efficient from a computational through put end. On many architectures the GPU will try to remedy this by *converging* threads back into a single warp once they reach the same instruction post branch, or the compiler will explicitly put a synchronization point which tells the GPU to converge threads back, or attempt to.

for example:

```
if(a)
    x += z * w;
    q >>= p;
else if(c)
    y -= 3;
r += t;

```

The thread have a strong potential to diverge (dissimilar instruction paths) so in such a case you might have convergence happen in `r += t;` where the instruction pointers would be the same again. Divergence can also happen with more than two branches, resulting in even lower warp utilization, four branches means 32 threads get split up into 4 warps, 25% throughput utilization. Convergence however can hide some of these issues, as 25% does not stay the throughput through out the whole program.

On less sophisticated GPUs, other issues can occur. Instead of diverging they merely compute all branches then select the output at the end. This might appear the same as divergence (both have 1/n throughput utilization), but there are a few major issues with the duplication approach.

One is the power usage, you are using much more power when ever a branch happens, this would be bad for mobile gpus. Second is that divergence only happens on Nvidia gpus when threads of the same warp take different paths and thus have a different instruction pointer (which is shared as of pascal). So you can still have branching and not have the throughput issues on Nvidia GPUs if they occur in multiples of 32 or only happen in a single warp out of dozens. if a branch is likely to happen it is more likely fewer threads will diverge and you won't have a branching issue anyway.

Another smaller issue is when you compare GPUs up against CPUs, they often don't have prediction mechanisms and other robust branch mechanisms because of how much hardware those mechanism take up, you can often see no-op fill on modern GPUs because of this.

# Practical GPU Architectural Difference Example

Now lets takes Stephanes example and see what the assembly would look like for branch-less solutions on two theoretical architectures.

```
n = (a==b) ? x : y;

```

Like Stephane said, when the device compiler encounters a branch it may decide to use an instruction to "choose" element which would end up having no branch penalty. This means on some devices this would be compiled to something like

```
cmpeq rega, regb
// implicit setting of comparison bit used in next part
choose regn, regx, regy

```

on others with out a choose instruction, it might be compiled to

```
n = ((a==b))* x + (!(a==b))* y

```

which might look like:

```
cmpeq rega regb
// implicit setting of comparison bit used in next part
mul regn regcmp regx
xor regcmp regcmp 1
mul regresult regcmp regy
mul regn regn regresult

```

which is branch-less and equivalent, but takes way more instructions. Because Stephanes example will likely be compiled to either on their respective systems, it doesn't make much sense to try to manually figure out the math to remove the branching ourselves, as the first architecture's compiler may decide to compile to the second form instead of the faster form.
> 7 votes

# Answer
I concur with everything said in @Stephane Hockenhull's answer. To expand on the last point:

> You never know in advance how a specific GLSL compiler or a specific GPU will perform until you benchmark it.

Absolutely true. Furthermore, I see this sort of question come up quite frequently. But in practice I have rarely seen a fragment shader being the source of a performance issue. It's much more common that other factors are causing issues such as too many reads of state from the GPU, swapping too many buffers, too much work in a single draw call, etc.

In other words, before you go worrying about micro-optimizing a shader, profile your entire app and make sure that the shaders are what is causing your slowdown.
> 5 votes

---
Tags: glsl
---


# Question
Title: Prefab instantiate or create gameobject at runtime?
I'm developing a skill system for a client-server game, all available player's skills server send to it, then client load it and put it to a spellbook. So I stuck in loading stage, how for performance and/or memory will be better:

* Save all spells in a bunch of prefabs and then just instantiate them
* Create JSON/binary/etc file, parse them and create a gameobject at runtime

From the side of editing, both methods are equal.

# Answer
Well, for starters:

* A prefab is a copy of an instance, therefore, it is cheaper than a GameObject created at runtime.
* Setting aside that in your case both methods represent the same for you in editing. In general it is better to have a prefab asset that can be recycled over and over again on scenes, and update everyone when you have to modify it.

For loading stage, you could have those spells as persistent data, and just load them once, say on the splash screen. For that, you would need a data structure, such as an **Object Pool**, where you can recycle your spells everytime you want to. Example:

```
public astract class Spell : MonoBehaviour
{
    void OnEnable()
    {
        Cast();
    }

    void Awake()
    {
        DontDestroyOnLoad(gameObject);  // With this, you keep it persistent and it gets on a scene called DontDestroyOnLoad.
    }

    public abstract void Cast();
}

public class Fire : Spell
{
    public override void Cast()
    {
        Debug.Log("Casting Fire...");
    }
}

public class Ice : Spell
{
    public override void Cast()
    {
        Debug.Log("Casting Ice...");
    }
}

```

So, instead of destroying spells at runtime, just deactivate their GameObjects, so you don't have memory leaks during object's instantiation and destruction.

If you are interested to know how an Object Pool would me made for this, let me know so I update my answer, or check **Sebastian Lague's Video about it**, just make it also persistent for all scenes.

Hope it helps.
> 1 votes

---
Tags: unity
---


# Question
Title: UNITY - Huge amount of GRAPHICS in RTS Tiled game
after year of development and week of unsuccessful optimization I turn for a help from you, guys.

So, my game is turn-based strategy with hexagon map. One hexagon consists of one texture for hexagon tile type and seven subtiles, which carry spriterenderer with graphics like piece of town. So if soldier steps on the subtile, the graphics of subtile hide.

On good machines like mine, if I zoom out maximally (45 orthographic size) on 1920x1080 and have visible around 18x16 tiles I get solid 160-200 FPS at MAX details, but on my laptop I barely get 25FPS on 1280x720 and LOW details. Each tile has resolution of 636x499.

I have tried:

* Simple shader on SpriteRenderer supporting transparency, just merging texture with color (This had those best results of 160-250FPS at HIGH-END and 25FPS on LOW-END)
* Creating separate material for each subtile and replacing SpriteRenderer with Quad mesh, so those subtiles are statically batched or GPU batched (but I guess they did not batch at all, because frame debugger showed that sometimes more fo the same pieces got rendered and then sometimes just one)

So this is just the 50x50 game, when I start large map, like 120x100, it's not really that worse, so I think the problem is just in the graphics and not in the amount of objects.

What are your suggestions I should try to get better performance on LOW-END devices? Do you think that manual GPU-instancing would make it faster? I think, there would be a lot of trouble maintaining which graphic to render and which not.

# Answer
> 1 votes
Without seeing *any* code, we'll have to guess at what is going on or things that could be attempted. This set of solutions assumes the problem IS the number of *things*:

* Some of your textures could be combined it seems. My guess is each of those trees is an individual sprite, even though you clearly put them in exact places. You can potentially draw that type of sprite to a hex-type programmatically and draw the hex as a single flat texture.
* Similar to the above, it doesn't seem like this needs to be redrawn each time. Were you to take the drawn scene and save it you could simply be treating it as a background until it needs being updated.

*Note: these may not be possible in Unity; but any framework that you manually perform double-buffering would be one that you could essentially double-double buffer, storing only what repeats in the second buffer.*

This set of solutions assumes the problem is RAM:

* A likely problem is that you're probably storing too many references or pieces of data. Start changing your doubles to floats, your longs to ints, and consider not using data structures like Dictionaries wherever you can. Self-expanding Data structures tend to increase by orders of 2, meaning they are going to average on about 75% memory efficiency.
* Stop storing redundant references. A technique I often use is store the references in an array and then store an enum that indexes me into the correct place of the array.

This set of solutions assumes issues in the drawing code:

* You may consider batching the objects yourself before passing them to the sprite batcher. I'm not sure how efficient the sprite batcher is here.
* You should check to make sure you're not performing the same projection over-and-over somewhere. If, for example, when you go to select a unit with a mouse you project everything to the screen first, you're doing a HUGE number of matrix multiplies when you could simply cast your mouse to world space.

Those are the best suggestions I have with my morning coffee ;)

---
Tags: unity, textures, graphics, performance, optimization
---


# Question
Title: Effective & Efficient Way to Simulate a Desert
### Introduction

I hope that this question isn't too broad, my apologies if it is. Anyway, getting to the point, our video game is set in ancient Egypt and, to nobody's surprise I'm sure, Egypt has a lot of sand in it. Sand is one of those substances that is notoriously difficult to simulate, however, in order to create a realistic desert I do have to deal with that aspect. Additionally, it also allows for the landscape to gradually change, which isn't just what real deserts do all the time, but it will also aid with making large stretches of desert seem a bit more interesting.

My primary concern is managing it in real time. On small scales, sand flows almost like a fluid, which needs to be done as characters interact with it, but even as a whole, a desert changes rapidly (compared to most other landscapes) as a result of environmental effects; sand moves, entire dunes displace themselves in a matter of days, and tracks created by humans and animals can quickly dissipate.

### Current Approach

Hence I am requesting methods that are good at achieving all these effects in an efficient manner. Personally, I was thinking about using the incompressible Euler equations utilising Lagrangian mechanics, thus working with particles, and then using something like Marching Cubes to render. However, it sounds like that'd be extremely time–consuming, so I wonder if there's a different, better approach.

### Technology

Currently we're working on our own game engine that is written in C and uses Vulkan as the primary, and probably only, graphics API. Hence, plenty is possible, although we'd prefer to keep the number of dependencies down to a minimum.

---

Thanks a lot in advance.

# Answer
**Notes**:

* I know this is about Egypt, but I will not make this specific to Egypt... because people coming here may find this question and its answers useful for other desert simulations.
* I am trying to keep this simple, avoiding too complex simulation that may eat too much resources.
* This is mainly based on Wikipedia. However I also had a read of the Slope Stability article from the Tulane University, which covers landslide among other things. And the article Coasts: Sand and Dunes from the U.S. Geological Survey.
* This is all speculative, I have never implement a similar system. *I would like to see how it ends ups working, though.*
* Also, I'm being a bit sloppy with my writting, sorry about that.

---

## Layers

You need them. We will have a static layer ("bedrock"), and one dynamic heightmap (sand). We will do large scale simulations on the dynamic one, to handle dunes et.al. That will be the main focus.

**Note**: This model does not handle deserts with different sands types.

We also need to handle placement and movement on the sand. Objects placed on the sand will displace it, making the object sink slighly, depending on the properties of the sand and the local geometry. Also they movement of the sand may take the object out (undug).

Which brings me to... we need a wind vector field, that will tell us the wind direction and speed for every position. The wind is supposed to remove small features, we need it to simulate the movement of the desert, the shape of the desert may affect it, and it can blow objects away.

Given that small features are not permament, I would suggest to have a temporal substractive layer for small local features. Foot prints, for example. Just discard old enough ones - for a sensible definition of old enough, do not bother to simulate wind with them. Thus saving memory and processing time. Using a substractive layer for small temporary features also means that the dynamic layer does not need to have a high resolution.

And of course, particle effects, et.al.

---

## "Bedrock"

This can be - probably - a heightmap, in particular if it is not exposed. However, if you want to have caves, you will have to use full geometry.

Does not need to plain, does not need to rough, does not need to be rendered as rock, or at all. The "bedrock" layer is a static heightmap, predefined for the area. It may serve a way to control how things happen in the upper layer. Since you cannot design the dynamic layer, this is important. I am suggesting to implement it - at least initially - as a smooth heightmap, and tweak as needed.

Remember that not all deserts are made equal, a rocky desert could have a very jaggy "bedrock" and a low dynamic sand layer, for example.

**Optional:** Since you have wind, and you may have exposed "bedrock", you could simulate erotion on it. Probably not something to be done realtime, unless it is some alien desert where that thing happens fast.

---

## Dynamic sand

Here is the deal: Sand will not overhang, and will not leave cavities. So you do not really need to simulate voxel or anything like that. A heightmap will do. You will be adding this layer on top of the geometry from the "bedrock", so the effective height is the addition.

Not all sand is made equal. In particular we need to know the density of the sand, and angle of repose of the sand (this depends on the surface area of the grains, the density and the gravitatory acceleration). For you, this are values to tweak.

The repose angle will be the angle of dunes on the slip face. Usual values for the angle of repose on Earth are between 30º and 45º.

Yes, you can use random deposition for the starting position. Perlin noise will also do, and would be cheaper. You would need to teak it to make sure it does not violate the repose angle. Nothing should be steeper than the repose angle.

**Optional:** You can choose to consider humidity (that is up to you, it makes the model more complex). Low water saturation will make the angle of repose higher (you can build stuff out of wet sand), while high water saturation will lower it (the sand flows better). You would need a humidity map, and a function that gives you the angle of repose from the local humidity. You may consider nearby features (rivers, for example) to decide humidity sources, and use wind to spread it. This may also tell you where the - sporadic - vegetation is more likely to appear.

We need a ramping angle (for the other side of the dunes), that should be a fraction of the repose angle. Also tweak as needed.

---

Now, wind will move sand. In three different ways:

1. Creep
2. Saltation
3. Suspension
4. *Wind*

Tweak the proportions at which these happen.

**Creep** is easy. We just move values around in the dynamic heightmap, according to the wind vector field, the wind effect factor (so you only move a portion of the sand), and the elapsed time.

---

Image for reference (the image shows the angle of repose as 34º, Barchan is the type of dune):

Notice that the ramping angle (on the opposing side of the angle of repose) is lower (less steep).

---

*Notes*:

* Creep should not result in a structure steeper than the ramping angle. You can push the excedent ahead.
* Sand should fall to the other side if it making an angle greater than the repose angle.
* Remember to always push in the direction of wind.

**Saltation** is basically the same thing. The difference is that we pick a landing place for the sand instead. The physics is that of a projectile being launch at the local sand angle. The strength of the launch sould be a function of the local wind vector by a factor you can tweak. *Or just ignore saltation.*

For **Suspension**, you add a sand saturation value to the wind. Honestly, I suggest to disregard the effects of suspension in the layer. And even in the wind. And use it instead for particle effects.

---

**Note on sand sources**: You can have the wind bring sand from off the map (creep from off the map). You can also have the rivers and sea bring sand. However, I would expect that sand from the wind to be main sand input.

---

## Objects

When an object is placed on the sand, it will displace some of it. While the object is sinking, we can pretend sand behaves as a fluid (*that is my engineering talking*) and use the Archimedes principle.

> Any object, wholly or partially immersed in a fluid, is buoyed up by a force equal to the weight of the fluid displaced by the object.

For an object on the surface, yet to displace any sand, this force will be 0. And the object will enter free fall.

An any given instant that the object is sumerged on the sand, we can mock the displaced sand with the depth, the volume of the object, and its density (wich you would need to anotate). I am suggesting to disregard object geometry and fudge it with the density value instead.

Now, that we know the displaced volume, the opposing force is a function of it. Multiply by yet another factor you tweak.

Instead of simulating the whole thing, I suggest to compute, for each object, at what depth these forces are on equilibrium. It is possible that for some object the equilibrium is not reached. You can choose to let the object sink to a given maximun depth (the "bedrock" layer, for example). Once we know the target depth for the object, we can accelerate and decelerate the object in such a way that it reaches that depth (which will be way cheaper).

**Note**: This requires to be able to quickly query if an object is under sand. You can do that by reading the height from the heightmapon the coordinates on the object and comparing the depth.

As per the effect on the sand... I does not matter if the sand overlaps the geometry of the object (unless we need to worry about transparent objects). If you need it can use the substractive layer to make a hole that fits the object, or even have the sand partially cover it (considering the repose angle). When the object is removed, the hole will be needed. You can simulate it filling up by reducing the feature in the substractive layer.

**Optional**: You can use the wheigh of the object, the input speed vector, and yet another fector you tweak, to compute an input crater. It would be better to solve the crater on the dynamic heightmap.

**Note**: Objects doing animations (not just being put on thrown) on the sand should also leave marks. That is the case of footprints. Just add them as features to the substractive layer.

---

You should also consider the wind pushing objects. You can search how to implement wind and drag.

---

## The wind vector field

Since we only care about the wind on the surface, we can use a 2D vector field. We can represent it as a texture, where a color channel represents direction and another color channel represents magnitud. We can have another color channel for sand saturation, and the last one - if you decide to use - for humidity.

**Note**: The optional humidity of the air is not the same as the optional humidy map. The optional humidity map is of the and, and affects the repose angle.

This also allows us to upload it to the GPU to be used as input for particle effects, and animations (you can use it animate things moving in the wind in a vertex shader, or animate textures if you need to).

**Optional**: We can update the wind direction and magnitud with the height map or other relevant obstacles. I would suggest to only do this if a feature reaches a significant height (for a sensible definition of significant). For the method to update it, I suggest to just divert the vectors around the obstacle.

**Addendums**:

* You would also have to update the wind direction when one such object is removed or its height is lowered enough.
* You can push humidity and sand down to the dynamic layer and the huminidy map, if you choose to simulate suspension and have an humidity map, respectively.
* You could use a 1D perlin noise to decide how to change the intensity of wind over time. I do realize that wind should not be blowing at the same magnitud all the time, and it could be easier to just multiply by a factor that follows a smooth pseudorandom curve (evaluated according to time) than to update the vector field.

*It would be interesting to see this integrated into a full wheater system. However, a desert probably does not need that.*

---

## The temporary substractive layer

Since features on this layer are not updated all at once, and we need to query features near to the player. I suggest to use a space partitioning structure.

You may also have a suplementary structure that allows to access them as a queue (probably a circular queue is a good idea), that allows a background thread to walk them and remove them as they become old. Also, evidently, when you query them from the space partitioning structure, you can remove any old elements.

Now, when I say it is a substracting layer, I mean you substract the height from its feature (in their appropiate location) from the height map. And that is how this layer allows you to make holes, footprints and similar features.

**Addendum**: You can also query and remove features on areas that have experienced significant creep (again, for a sensible definition of significant).

---

## Particle effects, et.al.

As I said, the wind will have sand saturation. If you can animate "sand" particles in the direction and speed of the air, around the player (note: you will have to interpolate the surrounding values from the wind vector field), and make these particles more visible as a function of the sand saturation of the wind, you will have the means for sand storms to happen in the simulation. *Or, at least, that is the idea.*

Aside form that, you can use shaders to animate sand sliding or creeping in the wind. I am aware that this is not often visible, but in some cases it is. So, take your artistic license on this.
> 3 votes

---
Tags: physics, terrain, simulations, terrain-rendering, fluid-dynamics
---


# Question
Title: Trouble with Index Out of Range Exception
I'm trying to make a textbox for a small game and I've run into an issue. I'm using drawString, which doesn't support \n so I've made an array of strings for multiple lines like so. Also, there is a global int called lettersShown that will be important later.

```
int lettersShown = 0;
String[] result = new String[] {" "," "," "," "," "," "," "," "};

```

In the constructor of the class, I then created a random event containing an array of 8 strings(Sorry if this is long and poorly formatted, its just for testing purposes.)

```
travel.add(new Event(this, new String[]{"You walk along a winding dirt
road,", "exposed to the scorching of the sun.",
            "Every so often, you pass the remains", "of blasted homes
and dilapidated", "hovels. The air is especially arid",
            "today, and by the time the sun drifts", "down into the horizon
you find", "yourself parched."}, -20,0,0,0));

```

So after I did that, I created a method to draw each line in order.

```
public void drawText( int x, int y, Graphics g) {

    for(int i = 0; i <result.length; i++) {
        g.drawString(result[i].substring(0, lettersShown), x, y);
        if(result[i].length() > lettersShown) {
            lettersShown++;
    }
        //lettersShown = 0;
        y+=15;

    }
}

```

This method works perfectly for any arrays that only have one string, such as this one:

```
travel.add(new Event(this, new String[] {"You traveled to a new city"},
0,0,0,0));

```

However, the second it starts to render an event with multiple lines, I get this exception

```
Exception in thread "Thread-1"
java.lang.StringIndexOutOfBoundsException: String index out of range:23
at java.lang.String.substring(String.java:1963)
at mains.EventManager.drawText(EventManager.java:149)
at mains.Game.render(Game.java:185)
at mains.Game.run(Game.java:87)
at java.lang.Thread.run(Thread.java:748)

```

I've been trying so many things to fix this seemingly small issue and I'd rather not resort to just having a ton of strings and drawing each of them one at a time so any guidance or anyone who can identify the problem would be greatly appreciated. Thanks!

# Answer
> 1 votes
Let's walk through this method one step at a time:

```
public void drawText( int x, int y, Graphics g) {

    for(int i = 0; i <result.length; i++) {
        g.drawString(result[i].substring(0, lettersShown), x, y);
        if(result[i].length() > lettersShown) {
            lettersShown++;
    }
        //lettersShown = 0;
        y+=15;

    }
}

```

Say `result = ["Hello", "You"]` and we're at `lettersShown = 3`, `i = 0`:

1. `g.drawString(result[i].substring(0, lettersShown), x, y);`

will print `"Hello".substring(0, 3)`, ie. "Hel" - so far so good.
2. `if(result[i].length() > lettersShown)`

well, `"Hello"` has length 5 \> 3, so this test passes.
3. `lettersShown++;` So now `lettersShown = 4`
4. `}` We hit the end of our loop, so we increment `i` to 1 and start again.
5. `g.drawString(result[i].substring(0, lettersShown), x, y);`

will try to print the first `lettersShown = 4` letters of `result[1] = "You"`... uh oh.

"You" has only 3 letters, but we're trying to get a substring of length 4 out of it! Kaboom.

So: you need to keep track of how many letters *of the current string* you want to print.

```
public void drawText( int x, int y, Graphics g) {
    // Let's show one more letter than we did last time.
    lettersShown++;

    int lettersRemaining = lettersShown;

    for(int i = 0; i <result.length && lettersRemaining > 0; i++) {

        // Don't try to take more letters than we have!
        int substringLength = Math.min(lettersRemaining, result[i].length());

        g.drawString(result[i].substring(0, substringLength), x, y);

        // Proceed to next line
        // Update our remaining letter count & vertical position.
        lettersRemaining -= result[i].length();
        y+=15;
    }
}

```

---
Tags: java
---