# Question
Title: What's the proper way to use static objects and singletons in Unity?
I have a GameObject in Unity, which I've attached this script to, in order to make it function as a Static Singleton :

```
using UnityEngine;
using System.Collections;

public class SceneStatics : MonoBehaviour {

    private static SceneStatics instance;

    public static SceneStatics Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new GameObject ("SceneStatics").AddComponent<SceneStatics> ();
                DontDestroyOnLoad(instance);
            }

            return instance;
        }
    }

    public void OnApplicationQuit ()
    {
        instance = null;
    }
}

```

I have two other scripts that I'd like to be able to access from scene to scene. What's the proper way to do that?

Do I attach my Inventory and Room scripts to the same game object as the SceneStatics? If so, how do I access them? Can I go from SceneStatics.Instance to one of the other scripts directly via GetComponent?

Alternatively, what happens if I add two child gameObjects (each containing one of the other scripts) to the SceneStatics?

Or is the intended use that I simply make any other static items I need properties of the SceneStatics class? (I.e., add in a Public static Inventory and Public static Room attributes)?

# Answer
> 3 votes
A really short way of ensuring there's only one instance of a script in the scene is to get it to destroy itself on creation if others are found.

```
public class UIManager : MonoBehaviour {

    void Awake()
    {
        // hyper-advanced singleton implementation
        if (FindObjectsOfType(typeof(UIManager)).Length > 1)
        {
            Debug.Log("UIM: Already found instance of script in scene; destroying.");
            DestroyImmediate(gameObject);
        }
    }
}

```

Does your class absolutely have to extend MonoBehaviour? If not, you might as well make it a static class.

# Answer
> 1 votes
Here is an example of a proper Unity singleton implementation https://wiki.unity3d.com/index.php/Singleton. However, you can simplify the code for your needs. The article also contains an example of how to use this class.

In case of a dead link here is the code:

```
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    // Check to see if we're about to be destroyed.
    private static bool m_ShuttingDown = false;
    private static object m_Lock = new object();
    private static T m_Instance;

    /// <summary>
    /// Access singleton instance through this propriety.
    /// </summary>
    public static T Instance
    {
        get
        {
            if (m_ShuttingDown)
            {
                Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
                    "' already destroyed. Returning null.");
                return null;
            }

            lock (m_Lock)
            {
                if (m_Instance == null)
                {
                    // Search for existing instance.
                    m_Instance = (T)FindObjectOfType(typeof(T));

                    // Create new instance if one doesn't already exist.
                    if (m_Instance == null)
                    {
                        // Need to create a new GameObject to attach the     singleton to.
                        var singletonObject = new GameObject();
                        m_Instance = singletonObject.AddComponent<T>();
                        singletonObject.name = typeof(T).ToString() + " (Singleton)";

                        // Make instance persistent.
                        DontDestroyOnLoad(singletonObject);
                    }
                }

                return m_Instance;
            }
        }
    }

    private void OnApplicationQuit()
    {
        m_ShuttingDown = true;
    }

    private void OnDestroy()
    {
        m_ShuttingDown = true;
    }
}

```

And an example of how to use it:

```
public class MySingleton : Singleton<MySingleton>
{
    // (Optional) Prevent non-singleton constructor use.
    protected MySingleton() { }

    // Then add whatever code to the class you need as you normally would.
    public string MyTestString = "Hello world!";
}

public class MyClass : MonoBehaviour
{
    private void OnEnable()
    {
        Debug.Log(MySingleton.Instance.MyTestString);
    }
}

```

So to use this class you need to inherit from it instead of MonoBehaviour. And you can access your class anywhere just by its name and getter Instance. Also, you can simplify this class with your needs. For example, you can get rid of the lock if you don't use multithreading. It will slightly speed up your code but you won't be able to safely use it in a multithreading environment.

# Answer
> -1 votes
Personally I think singletons are an abomination and I don't recommend them. But you can implement them however you like. There's no such thing as a 'proper' way.

If you only want 1 of something, just create a single instance. You don't need a code straitjacket to stop you adding more, and you'll probably find a use for more later. So why bother?

> Do I attach my Inventory and Room scripts to the same game object as the SceneStatics?

Nobody can answer that without knowing what those scripts do or what the implications of such an attachment are.

> Can I go from SceneStatics.Instance to one of the other scripts directly via GetComponent?

Yes, certainly. If a GameObject has multiple components then you can easily find one from the other.

> What happens if I add two child gameObjects (each containing one of the other scripts) to the SceneStatics?

Nothing happens. You now have 3 game objects. To access one from the other will require a little more than a simple GetComponent, but that's all.

> Is the intended use that I simply make any other static items I need properties of the SceneStatics class?

There's no intention here, just many different ways of reaching a goal. I try to avoid statics in Unity as (a) they're generally just globals in disguise, and (b) you lose the potential benefit of being able to use the Inspector to edit the values. Instead I'll just have one GameObject with one instance of the component and will create it in the scene that needs it. In the very rare occasions I need something to persist throughout I just have 1 instance in the first scene and use DontDestroyOnLoad.

---
Tags: unity
---


# Question
Title: Using one Vive controller: default to left hand?
We're making a sailing game in VR for Vive Pro, where you hold the rudder with your left hand using a Vive controller. We use just one controller because there's nothing to do with your other hand, and the rudder is on the left side of the player (it's a seated setup). The second controller will be charging, or it will be off while the game is being played.

We use the Player prefab that comes with the Steam VR Unity Plugin, that has GameObjects for both the left and right hand, with the option to show controllers and/or hand skeletons that move according to what controls you're using on the controllers.

The problem is that when only one controller is on and detected by Steam VR, it decides to show the *right* hand, instead of the left hand that we're holding it with.
When both controllers are switched on and connected, it works as expected. The left hand controller is at the player's left side as long as the unused controller is located at the player's right side.

I tried putting a left handed skeleton on the right hand controller gameObject in the Player prefab, but that resulted in an unresponsive skeleton (not visualising the interaction of the player with the controller).

**How can we make it so that when using only one controller, it shows as the left hand?**

So what we want is like in this picture, hold the controller with one hand (normally the left hand) except *always* showing a left virtual hand in the application, and still mimicking whatever controls the user is pressing on the real controller.

# Answer
> 1 votes
you should be able to update the mappings using the tool described here: https://www.pcgamer.com/valve-now-lets-you-map-your-own-custom-controller-bindings-in-steamvr/

But you might also have luck by adding the Unity tracked-pose-driver to your rudder and manually selecting which controller you'd like to use: https://docs.unity3d.com/2018.3/Documentation/ScriptReference/SpatialTracking.TrackedPoseDriver.html

Hope this helps!

---
Tags: unity, steam-vr
---


# Question
Title: How do i play mp3 files in Unity Standalone?
I am making a game in Unity in which the player can select music files in their hard drive to use them in-game. I use the **WWW** class to load the sound files, but this only works for OGG, WAV and Tracker files. I use the following code:

```
WWW www = new WWW ("file:///" + soundPath);
while(!www.isDone){
    yield return 0;
}
GetComponent<AudioSource> ().clip = www.GetAudioClip(false, true);

```

I want to play audio files in mp3 format, which is the most widely used format for music in general, but when i try to play them, this gets printed to the debug log:

> Streaming of 'mp3' is not supported on this platform.

How can i easily achieve mp3 playback on desktop?

# Answer
To be able to play .mp3 files on desktop, you'll need help from an **external library** to convert it first to another format.

You can use NAudio to convert the audio from MP3 to WAV before playing it.

* You must set the API Compatiblity Level to .NET 2.0 (Edit-\>Project Settings-\>Player)
* Put NAudio.dll in /Assets/Plugins
* Create a new C# Script, name it "NAudioPlayer.cs" and put the following on it:

```
  using UnityEngine;
  using System.IO;
  using System;
  using NAudio;
  using NAudio.Wave;

  public static class NAudioPlayer {
      public static AudioClip FromMp3Data(byte[] data)
      {
          // Load the data into a stream
          MemoryStream mp3stream = new MemoryStream(data);
          // Convert the data in the stream to WAV format
          Mp3FileReader mp3audio = new Mp3FileReader(mp3stream);
          WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(mp3audio);
          // Convert to WAV data
          WAV wav = new WAV(AudioMemStream(waveStream).ToArray());
          Debug.Log(wav);
          AudioClip audioClip = AudioClip.Create("testSound", wav.SampleCount, 1,wav.Frequency, false);
          audioClip.SetData(wav.LeftChannel, 0);
          // Return the clip
          return audioClip;
      }

      private static MemoryStream AudioMemStream(WaveStream waveStream)
      {
          MemoryStream outputStream = new MemoryStream();
          using (WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
          {
              byte[] bytes = new byte[waveStream.Length];
              waveStream.Position = 0;
              waveStream.Read(bytes, 0, Convert.ToInt32(waveStream.Length));
              waveFileWriter.Write(bytes, 0, bytes.Length);
              waveFileWriter.Flush();
          }
          return outputStream;
      }
  }

  /* From http://answers.unity3d.com/questions/737002/wav-byte-to-audioclip.html */
  public class WAV  {

      // convert two bytes to one float in the range -1 to 1
      static float bytesToFloat(byte firstByte, byte secondByte) {
          // convert two bytes to one short (little endian)
          short s = (short)((secondByte << 8) | firstByte);
          // convert to range from -1 to (just below) 1
          return s / 32768.0F;
      }

      static int bytesToInt(byte[] bytes,int offset=0){
          int value=0;
          for(int i=0;i<4;i++){
              value |= ((int)bytes[offset+i])<<(i*8);
          }
          return value;
      }
      // properties
      public float[] LeftChannel{get; internal set;}
      public float[] RightChannel{get; internal set;}
      public int ChannelCount {get;internal set;}
      public int SampleCount {get;internal set;}
      public int Frequency {get;internal set;}

      public WAV(byte[] wav){

          // Determine if mono or stereo
          ChannelCount = wav[22];     // Forget byte 23 as 99.999% of WAVs are 1 or 2 channels

          // Get the frequency
          Frequency = bytesToInt(wav,24);

          // Get past all the other sub chunks to get to the data subchunk:
          int pos = 12;   // First Subchunk ID from 12 to 16

          // Keep iterating until we find the data chunk (i.e. 64 61 74 61 ...... (i.e. 100 97 116 97 in decimal))
          while(!(wav[pos]==100 && wav[pos+1]==97 && wav[pos+2]==116 && wav[pos+3]==97)) {
              pos += 4;
              int chunkSize = wav[pos] + wav[pos + 1] * 256 + wav[pos + 2] * 65536 + wav[pos + 3] * 16777216;
              pos += 4 + chunkSize;
          }
          pos += 8;

          // Pos is now positioned to start of actual sound data.
          SampleCount = (wav.Length - pos)/2;     // 2 bytes per sample (16 bit sound mono)
          if (ChannelCount == 2) SampleCount /= 2;        // 4 bytes per sample (16 bit stereo)

          // Allocate memory (right will be null if only mono sound)
          LeftChannel = new float[SampleCount];
          if (ChannelCount == 2) RightChannel = new float[SampleCount];
          else RightChannel = null;

          // Write to double array/s:
          int i=0;
          while (pos < wav.Length) {
              LeftChannel[i] = bytesToFloat(wav[pos], wav[pos + 1]);
              pos += 2;
              if (ChannelCount == 2) {
                  RightChannel[i] = bytesToFloat(wav[pos], wav[pos + 1]);
                  pos += 2;
              }
              i++;
          }
      }

      public override string ToString ()
      {
          return string.Format ("[WAV: LeftChannel={0}, RightChannel={1}, ChannelCount={2}, SampleCount={3}, Frequency={4}]", LeftChannel, RightChannel, ChannelCount, SampleCount, Frequency);
      }
  }

```

You can then do this:

```
WWW www = new WWW (musicUrl);
while(!www.isDone){
    yield return 0;
}
GetComponent<AudioSource> ().clip = NAudioPlayer.FromMp3Data(www.bytes);

```

Please note that this **will likely freeze the game for about a second or two**, so use it wisely. If you need to load multiple sounds this way, try to do it during a load screen so the game doesn't get frozen while playing.
> 6 votes

# Answer
This is only for monochannel audio files:

```
audioClip.SetData(wav.LeftChannel, 0);

```

For Stereo Channels, create a new float array which is the result of both left and right channel. (L\[0\], R\[0\], L\[1\], R\[1\], etc...) Then set data with that array.

Example:

```
        float[] combinedChannels = new float[wav.LeftChannel.Length + wav.RightChannel.Length];
        int pointer = 0;
        int lpointer = 0;
        int rpointer = 0;
        while(pointer < combinedChannels.Length)
        {
            combinedChannels[pointer] = wav.LeftChannel[lpointer];
            lpointer++;
            pointer++;
            combinedChannels[pointer] = wav.RightChannel[rpointer];
            rpointer++;
            pointer++;
        }
        audioClip.SetData(combinedChannels, 0);

```

Remember to check if the wav is mono first before doing this.

Also make sure to change the channels to 2 when creating the audioclip so it works properly

`AudioClip audioClip = AudioClip.Create("testSound", wav.SampleCount, 2,wav.Frequency, false);`

Just dropping a comment here for referencing afterwards if I need it. ;)
> 0 votes

# Answer
There might be something helpful in this thread:
https://forum.unity.com/threads/how-play-audio-mp3-from-server-url.472243/

They load mp3s from a server and I realize you're trying to get them from the user's hard disk. You may be able to spawn a server to host the directory of mp3s with something like https://www.npmjs.com/package/serve. That should work at least on your system and then you could start exploring ways of packaging it since I assume you'd like this app to run on other people's system too and it may be harder to spawn a server without certain dependencies outside of the Unity build.
> 0 votes

---
Tags: unity, c#, music, file
---


# Question
Title: What's a good way to draw multiple circles?
Why does the following code not work?

```
public float ThetaScale = 0.0001f;
private int Size;
private LineRenderer LineDrawer;
private float Theta = 0f;

void Start ()
 {
  LineDrawer = GetComponent<LineRenderer>();
  LineDrawer.SetWidth(0.1f, 0.1f);
  LineDrawer.material = new Material(Shader.Find("Mobile/Particles/Additive"));
  LineDrawer.SetColors(Color.blue, Color.blue);
 }

void DrawingCircle(float radius)
{
Theta = 0f;
Size = (int)((1f / ThetaScale) + 1f);
LineDrawer.SetVertexCount(Size);
for(int i = 0; i < Size; i++){
    Theta += (2.0f * Mathf.PI * ThetaScale);
    float x = radius * Mathf.Cos(Theta);
    float y = radius * Mathf.Sin(Theta);
    LineDrawer.SetPosition(i, new Vector3(x, y, 0));
}}

void Update ()
{
    for(int l = 0; l < 3; l++)
    {
        DrawingCircle(l);
    }
 }

```

I want to plot a multiple circles like that

What's a good way to draw multiple circles?

# Answer
> 1 votes
I think your confusion comes from a misunderstanding of what the LineRenderer component does.

A LineRenderer isn't a "line drawer". It doesn't draw lines. It visualizes a game object in form of a visible polygon strip in 3d space. Just like a SpriteRenderer visualizes a game object as a sprite or a MeshRenderer visualizes a game object as a 3d mesh.

So when you want 3 separate lines in your game, you need 3 different game objects with a LineRenderer each. When their coordinates don't change, you only need to set them once. It's not necessary to reassign their components in every update.

---
Tags: unity
---


# Question
Title: Unity websockets client disconnects after server emits with data
I am using some unity "socket-io" plugin i found on the asset store. (its essentially just a scoket.io wrapper for websocket-sharp) everything works absolutely fine, i can catch clients connecting or disconnecting, i can also emit from both sides and call some functions, but the only problem is, when i try to send data from server using `.emit("name", data);` client receives this data properly(i can console.log it) and suddenly disconnects, but restores connection afterwards. if i just use `.emit("name")` everything works fine.

This is my server code:

```
//where _PLAYERS is just an array(object) of socket.id-s with corresponding Player objs
for (var key in _PLAYERS) {
    var data = {
        name: "test"
    };
    io.sockets.connected[key].emit("update", data);
}

```

I have also tried: `io.to(key).emit("update", data);` and inside `io.on("connection")` i did `socket.emit("update", data)`. disconnects in all cases.

client:

```
socket.On("update", OnUpdate);
public void OnUpdate(SocketIOEvent e)
{
    Debug.Log(e.data); //this one doesn't work here
}

```

but it works inside wrapper code:

```
    private void OnMessage(object sender, MessageEventArgs e)
    {
        #if SOCKET_IO_DEBUG
        //result: 42["update","{\"name\":\"test\"}"]
        debugMethod.Invoke("[SocketIO] Raw message: " + e.Data);
        #endif
        Packet packet = decoder.Decode(e);

        switch (packet.enginePacketType) {
            case EnginePacketType.OPEN:     HandleOpen(packet);     break;
            case EnginePacketType.CLOSE:    EmitEvent("close");     break;
        ...

```

Hence, correct client receives a message with data successfully, but wrapper or websocket-sharp(not really sure which) causes it to error and doesn't fire my onUpdate() method.

OnMessage is just a function bind to websocket-sharp's onMessage. Like this:

```
ws = new WebSocket(url);
ws.OnMessage += OnMessage;

```

*Keep in mind that `io.sockets.connected[key].emit("update");` without data works fine. But i need to send data. Also client can `.emit("name", data)` to server, and it also works, but data from server crashes.*

**My main question is, what are all the possible reasons in this whole websocket thing that may cause client to disconnect after receiving a message with data?** So If anybody isn't familiar with these particular libraries, at least i would be able to debug and find that error myself.

ps: websocket-sharp

and the wrapper i am using(which is deprecated a long time ago)

# Answer
Finally, after many hours of debugging, found an error. This library expects data from server to be a JSON object, and not string *(that's a bit weird because this library allows to send both string and object to the server)*

so instead of `io.to(key).emit("update", JSON.stringify(data));`

I did:

`io.to(key).emit("update", {
 data: "isMine"
 });`

And now, everything is fine :) Hope that will help somebody in future.
> 4 votes

# Answer
I don't have enough reputation to comment yet but I wanted to thank Nick for the above answer. I was facing the same issue but my Unity client was disconnecting when the server sent events that *it wasn't listening for* that were not in JSON format.
> 2 votes

---
Tags: unity, c#, node.js
---


title: Tower Defence stat storing system

text:
# Question
Title: Tower Defence stat storing system
I'm trying to find a smart way to store and retrieve stats for a tower defence game, but am currently unsure as to which approach would be best.

**Description:**

The stats system should quite basic, there are 4 different towers, with up to 5 different levels each. One important requirement is that the stats should be stored in an XML file so that the game designer easily can access and balance the stats. (He knows nothing about programming)

I can see two ways of doing this:

1. By creating a TowerStats class which hold values for one type of tower for one level. Something like:

```
public class TowerStats2
{
    public TowerType type;
    public int lvl;
    public int damageLow;
    public int damageHigh;
    public float range;
    public float attackFrequency;
}

```

Then i would load the stats from the XMl file using Linq and XDocument and load it directly into a TowerStat List. I would do this for each tower so in the end there would be 4 different List's which would hold the different level stats for the specified tower.

* gunTowerStats\[0\] would hold level 1 stats of the gun tower
* rocketTowerStats\[2\] would be level 3 stats of the rocket tower

When a new tower is bought by the player or when a tower is upgraded, the stats would then be taken from the List so something like:

```
UpgradeTower()
{
    lvl++;
    towerStats = gunTowerStats[towerLevel - 1]
}

```
2. Alternativly I could hardcode all the values, and have one big class which would go something like this:

```
gunTowerDamageLvl1 = 4;
gunTowerDamageLvl2 = 8;
gunTowerDamageLvl3 = 15;
rocketTowerDamageLvl1 = 10;

```

you get the point. I know that hardcoding is never never really the way to go. But does that also count for this kind of example where all possible tower attributes are known and will not change? the only thing that will change are the values of these attributes.

**Question** I'm personally in favour of the first way, but I must admit that I find both ways a bit clumsy, would it be alright to do it one of these ways or is there a much smarter and more obvious way to deal with this that I'm completely unable to see?

I hope my question is understandable.

# Answer
> 2 votes
Firstly, I see no issue (in principle) with the first approach, the XML file. Easily editable, easily extendable.

Secondly, I would still recommend not using XML, and using JSON instead, since it's going to make the saving/loading of the stats significantly easier:

```
[System.Serializable]
public class TowerStats2
{
    public TowerType type;
    public int lvl;
    public int damageLow;
    public int damageHigh;
    public float range;
    public float attackFrequency;
}

```

And then instead of having to write annoying boilerplate to convert to/from XML, you can just do

```
var stats = JsonUtility.FromJSON<TowerStats2>(jsonString);
string jsonStats = JsonUtility.ToJson(stats);

```

And if you ever add new attributes, it'll still work.

Thirdly, if the XML files are inside the unity Assets folder, meaning to modify them, you need to actually open the project in unity, meaning your designer needs to have unity editor and work within it anyway... ...you might want to look into ScriptableObject, which is basically... A C# class that the unity uses as a prescription for a data storage file, which you can then create in your project as an asset.

How that works in principle is that you can create assets (data files) equivalent to the XML/JSON ones you'd use, except all of the deserialization is automatically handled by unity, you can edit the data in them via inspector, and you can also readily plug them into C# code, assign them into fields in Inspector, all the good standard Unity Editor stuff, so now the workflow for your designer is literally the same as doing anything else within unity editor. So if there's no need for the files to be external to the project (meaning they would be besides the compiled data, still accessible and editable even within the built game), this would be probably the easiest and "most native to Unity" way to do it.

# Answer
> 1 votes
Although I think @sh code 's answer is the correct way to go, I wanted to add that Unity's new prefab variant workflow is really useful for making related objects have slightly different properties. It also works great when the visuals need to match the variations in internal state, since each variant can have a different meshes or effects.

You could also take a hybrid approach. Use prefab variants that access different scriptable-object settings for internal state, while still being able to vary the visuals.

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


# Question
Title: How to have multiple GameObjects sharing pieces of same material?
My question is: There's any way of having GameObjects sharing pieces of same Material, not a clone, but an extension of one? For example, in these case nine game objects sharing just the same material enlarged to fulfill the size of nine ones:

And in the case, I delete for example one in the middle, it will keep the same material enlarged with the blank space inside:

For this purpose, I used one material per object, but my intention is to use it just one texture for multiple objects, or for example, more of one texture in different parts of the same one. (Like the painting button we have in the custom Unity3D Terrains).

# Answer
Have you looked into using Unity's Shadergraph to make your own shader for the material? You might be able to achieve what you want by using the worldspace position for texture/uvs. I am not good at explaining it and am not great at shaders but I mocked up a quick example for you as a water shader because I was bored and already playing around in my project dedicated for experiments.

This picture is showing that the overlapping planes appear to share the same material

This is the example made in shadergraph

Quick summary of the shader nodes from my example as I understand them

1. These nodes are grabbing the *x* and *z* values in worldspace and combining them in a vector 2
2. This node is using the *xz* values and offsetting them based on nodes in *3*
3. using *Time* and a Vector 2, to scroll the uv offset. gives a wave effect
4. Multiplying the value based on *Normal Tiling* value.
5. Takes the UV data from *4* and a normal map
6. Normal strength. changes the strength of effect
7. Takes all the data from 1 - 6 and the water texture and feeds into albedo in *8*
8. all the nodes feed into here for the shader to change how each of these properties affects the material.

If anyone thinks anything I have said or done is incorrect or could be improved, please feel free to correct me. I am still learning and a nudge in the right direction is always welcomed. I have uploaded the example scene to google drive for you mess around with. unsure if attribution is required but the water asset used is free and from gametextures.com
> 3 votes

# Answer
You can create a sprite atlas from one texture, create a child object for your plane or whatever shape you are using, drag in created sprite cutouts, Rotate and place the child within the plane gameobject however you like, and voila, look at the pic below to see what I mean,

It might be tedious work but it seems like this solution fits what you want.
> 1 votes

# Answer
Another option is to use the Projector object in the unity standard assets folder. It isn't very performant, but is really easy to set up. So for simple cases, it may be exactly what you are looking for. But like I said it has a pretty significant performance impact especially if you're projecting larger textures.
> 0 votes

---
Tags: unity, 3d-meshes, gameobject
---


title: Chunked LOD split by distance

text:
# Question
Title: Chunked LOD split by distance
So when you get near to the chunk it splits, and then when getting near to the splited chunk it does the same again and over (quad tree). But what is the formula for calculating the distance when it should split depending on the distance? For smaller chunks, smaller distance?

# Answer
One way to think about the problem is in terms of visible triangle density. How many pixels does a typical triangle span?

If your triangles are all the same size, then as they recede into the distance, they start taking up fewer and fewer pixels, until you end up with many distant triangles all drawing to the same pixel - lots of redundant calculations for no visible benefit. Or on the other side, as they get closer to the camera, the triangles get bigger and bigger until their pointy edges are obvious.

To avoid either extreme, we want to replace our terrain chunks with LOD versions with a triangle density appropriate to their distance, so that the rendered image has a roughly even density of pixels per triangle in both near and far terrain.

Let's take a look at the terrain you show at 1m away, which covers an area of about C on-screen pixels. As this triangle recedes to distance D away, it will cover an area of about \\$\frac C {D^2}\\$.

So, if you're halving your grid frequency on each axis at each quadtree level (1/4 as many triangles, 4x the area each), then you'll want to drop one level of detail each time you double your distance. Or conversely, anytime you halve your distance to a triangle, you should double the grid frequency. Something like...

* Up to 5m (Or whatever reference distance you pick as "highest detail range"): Full Res
* Up to 10m: Half Res
* Up to 20m: Quarter Res
* Up to 40m: Eighth Res

This way your visible triangle area stays roughly consistent on screen.

Now obviously since the depth falloff is continuous but your LOD transitions are discrete jumps constrained to chunk boundaries, you'll have some judgement calls to make about where to put your transition point within this range or how to round up or down to favour visuals, performance, consistency, etc. But thinking about it in terms of pixels per triangle should give you a solid metric to use in making and evaluating those decisions.
> 1 votes

# Answer
There is no "one-size-fits-all" formula for Level Of Detail calculations. A game where assets are frequently travelling from the far distance to directly in front of the camera will need a different formula than a 2D sidescroller game that just happens to use 3D assets.

Ideally you'd have to make your own experiments and find the right balance between quality, not noticing that the asset is changing shape and performance.

Also I'm not sure "splitting" an asset is the way to go, as usually games use separate assets for each Level Of Detail asset, and swap between them.
> 1 votes

---
Tags: procedural-generation, level-of-detail
---


# Question
Title: Instantiate objects in a List and use it
Why does the following code not work?

I want to instantiate prefabs in a list and then use it as a GameObject like that :

```
public GameObject prefab;

void Start()
{

 ArrayList players = new ArrayList();

  for(int i=0; i<5; i++)
  {
        players.Add( (GameObject)Instantiate(prefab));
  }

  players[2].transform.position = new Vector3(1, 1, 1);

}

```

there is an error message

# Answer
I'm not super familiar with Unity and c#, but...

> The ArrayList class is designed to hold heterogeneous collections of objects. (Source)

So the only thing your `players` contains, is `object`s (at least w.r.t. the world).

You either want to cast the content before using it:

```
((GameObject)players[2]).transform.position = ...

```

Or use a clearer type like `List<GameObject>`, which will explicitly tell the world that it contains `GameObjects`, and let you do what you want.
> 2 votes

# Answer
I think your code is not working because you are adding prefabs to another list(numbers) Your code should be like this

```
void Start()
{

 ArrayList players = new ArrayList();

  for(int i=0; i<5; i++)
  {
        players.Add((GameObject)Instantiate(prefab));
  }

  players[2].transform.position = new Vector3(1, 1, 1);

}

```
> 1 votes

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


title: Fade into scene in Unity / SteamVR

text:
# Question
Title: Fade into scene in Unity / SteamVR
I am using this code below for a gradual fade into a scene/next level in Steam VR (HTC Vive) The whole idea is to cover up the scene loading icon which is viewable for 3-4 seconds, and the default Steam landscape scene. The fade (to red) works fine…BUT it comes in after the loading icon so this defeats the whole purpose of it. Is there any simple way to fix this? thanks

```
public class NewFade : MonoBehaviour {

private float _fadeDuration = 4f;

private void Start()
{
    FadeFromWhite();
}

private void FadeFromWhite()
{
    //set start color
    SteamVR_Fade.View(Color.red, 0f);
    //set and start fade to
    SteamVR_Fade.View(Color.clear, _fadeDuration);
}

```

}

# Answer
You can prevent the Steam landscape scene, as you call it, from showing by checking "**Do not fade to grid when app hangs**" in Steam VR Settings.

Ignore the other highlighted checkbox in the image above, that one does something unrelated.
> 1 votes

---
Tags: unity, virtual-reality, steam-vr
---


title: Quickly Running Out Of Memory

text:
# Question
Title: Quickly Running Out Of Memory
Over the past months I have been developing an application using Vulkan. Recently I have implemented loading 3d models from .fbx files and their associated .png textures. At this point there appears to be no performance issues **until you look at the memory usage**.

A single, `4096x4096 10mb .png` file after loaded is spiking memory usage over 500mb. Loading an `80,000 polygon .fbx` file is spiking memory usage over **2GB!** during the loading process and then it levels down around `800mb`. That is still ***800mb*** for loading 1 model and 1 texture and this is just on the CPU.

On the GPU, which as considerably less available ram than the CPU, just by looking at task manager, is showing about the same amount of usage. If I load in more model+texture pairs I can see memory usage on the GPU's graph take large steps up after transfer operations complete.

At this rate I wont be able to have but only a small handfull of objects in an entire scene.

**So what am I doing wrong here? Just what important factor have I completely overlooked when designing this application?**

This is a learn-as-you-go project, and i'm proud of myself for getting this far, but this memory issue is absolutely dumbfounding and I haven't a clue.

If anyone want's to have a rummage around in my code the project is up on GitHub.

# Answer
Generic advices.

Don't use png. It's good for intermediate image processing, acceptable in some test runs, but it's quite slow for loading and needs extra ram for decompressing.

Use the texture file formats that's very close to the data format that will be actually consumed by gpu - dds/ktx/pkm - whatever that supports your target hardware's texture compression (bc1/bc3/bc5/etc) and will allow you do read the binary dump directly without processing. You can pack that later with zlib as part of the game's resources archive.

Same applies to 3d model formats. If something is good for exchanging geometry between different modelling software - like FBX or Collada - then it's overly generic, it will require some (or lots) processing upon loading, and will fragment your memory.

And don't judge about your app's consumption by looking in the task manager. Use some profiling tool to actually track the allocations done by the app.
> 1 votes

---
Tags: memory-efficiency, vulkan
---


title: How to use local-storage

text:
# Question
Title: How to use local-storage
So I have this game and I would like to have a save function. Here is my code below:

```
function SaveData() {
  localStorage.setItem('save', score);
  localStorage.setItem('save', btoa(JSON.stringify(score)));
}
function LoadData() {
  score = window.localStorage.getItem('save');
  document.getElementById('demo').innerHTML = score;
}
window.onload = function()  {
LoadData();
}

```

When it loads it does not use the storage or it says Not a Number (NaN)

# Answer
> 0 votes
Ok, so let's assume you have a DOM element in which you display the score, and start with that. So, the first time the user will arrive on the game, the score will be "0" (you will probably have something to calculate it and that's not the scope of this answer, let's focus on the load and save parts for now. I'll write the save function in this way:

```
function SaveData(score) {
  localStorage.setItem('save', btoa(score));
}

```

While, the load function could be like:

```
function LoadData() {
  var score = window.localStorage.getItem('save');
  if (score === null){
    score = 0;
  }else{
    score = atob(score);
  }
  document.getElementById('demo').innerHTML = score;
}

```

I've used the `btoa` an `atob`, but they are unnecessary to save just a number, but since you used them I suppose there will be a reason, I deleted the JSON.stringyfy (and not added the parse) because that's totally unnecessary and could be trivial, because you will end up with an object (or an error)

# Answer
> 0 votes
Your code here has several issues. Your score will be NaN if nothing has been saved (the first time the game is played). Then when you try to save that NaN, it remains NaN. Also, you don't convert it back from `btoa` and `JSON.stringify` (which is entirely unnecessary in the first place).

In the code you linked, you go back and forth between `score` being a number and it being a DOM node (with `.value`).

---
Tags: javascript, storage, html
---


title: How to synchronize a game with music

text:
# Question
Title: How to synchronize a game with music
You may be familiar with ryhtm games as Dancing Line, Geometry Dash, or even Guitar Hero. They have something in common : every single action in the game is synchronized with the music. My purpose is to make a game like Geometry Dash where the player has to do some actions in rythm while the character scrolls automatically in the level. I have a few questions about this type of game :

* Do I have to keep my FPS constant as it has to be always synchronized with the music ?
* How can I build my levels with a music in mind to make sure that it will be synchronized ?

I am working on Unity using C#.

# Answer
> 19 votes
I don't recommend using Time.deltaTime to track progress through playing the song as described in another answer.

It's great for smoothing & interpolating effects to play out in realtime, but when you want to match the *song's time* you should ask the song.

In Unity, you can measure an Audio Source's progress through playing a track directly using `AudioSource.time` or `AudioSource.timeSamples` to get the precise playhead position. (Note that the latter measures in samples, which may vary in rate per second depending on how you've compressed your track)

This way, you don't need to run your own separate timer and hope they stay in sync. You can wire up game triggers of beat matching effects to run off of the song's own timeline.

For layering gameplay sounds onto the music, you can use AudioSource.PlayScheduled to ensure your sounds land exactly on the beat, as even a small mismatch can be noticed

# Answer
> 2 votes
As an alternative if you are fine with not working from scratch.

There are ready made assets already (under Editor Extensions/ Audio like https://www.assetstore.unity3d.com/en/#!/content/54639 (paid) or https://www.assetstore.unity3d.com/en/#!/content/39835 (free)) where you can sync music tracks to event. In that example the weapon is shooting on the beat of the music.

If you want to learn how they work, try 1-2 of the free ones and look at the source.

# Answer
> 1 votes
Unity already decouples gameplay from framerate. If you remember to always use `Time.deltaTime` in your Update-functions, the actual graphics framerate should not affect gameplay speed. So when you start the game and the audio track at the same time, they should stay synchronized.

Regarding designing levels around music, there are two approaches:

* The manual approach. Meticulously hand-craft levels around specific audio tracks. Having the original sheets music at hand can help, but it's also possible to do it just by ear.
* The procedural approach. Use audio analysis algorithms to auto-generate levels around audio tracks. The most simple is to just look for volume spikes. That should already allow you to identify drum beats in many songs and spawn obstacles accordingly. A step further is detecting volume shifts separately in different frequency spectrums. This makes beat detection more reliable and allows you to spawn different obstacles for different pitches. But that's still just scratching the surface. Audio analysis is a very wide and interesting field. People wrote a lot of scientific literature about it.

How deep you need to dive into this field depends on how ambitioned you are. Some games are satisfied with just detecting the beats and randomly-generate all the rest of the level design(*Crypt of the Necrodancer*). Others try to put as many aspects of level design under the control of the audio as they can (*Audiosurf*).

Many rhythm games use a hybrid approach. You generate a first draft of the level using a generator and then tweak it by hand to make it more playable.

# Answer
> 0 votes
Very common is the approach to have a "beat map". Any kind of data that represents the beats in the song. It can be a texture, datafile or anything else that holds that information. Most of the time it's created manually to create different beats and combinations, versions of speeds for an audio map.

It can be generated procedurally from audio file data, though.

**How to get the speed to match the "beat point"? When to spawn an object?**

`Speed = Distance / Time`.

`Distance =` Distance between points of creation of GameObject and of "beat point".

`Time =` Audio length and constructed beat map should be enough. With this information you can analyze the data of audio/map to predict when an object must be spawned to reach the exact point. Now it all depends on when you want to spawn that object, if you want it to be very fast after spawn, then you spawn it later with great speed. If you want it to be at a normal speed - then it will need time to reach the player and audio needs time to play to the right moment.

You can even generate a new map with time stamps for spawns of beat objects for particular audio map. You have to make some predictions at some point to be able to match the beat, for most popular style I would say, to predict `when` to spawn the object for it to move with certain `speed`. Those can be made in runtime, or read from some file calculated previously, or saved in RAM...

I assume games like `Osu` don't have this `Distance`, they just have time of circles shrinking, bpm... Maps are generally custom made. So approach to calculate visuals depends on the style of the game you are making as well.

So to sum up everything, the values are interdependent. Depends on how many beats you have, on the distance between spawn point and player, and sometimes depends on data provided \[some games have the speed of every beat and its appearance encoded in some data file which is created manually\]. If you are doing it procedural way, then you can calculate everything basically by using audio data.

---
Tags: unity, game-design, music
---


title: Update TTF Texture for Score

text:
# Question
Title: Update TTF Texture for Score
I have a little problem with Updating my Score with TTF. Im a neewbie so dont blame me :P

I Try to Update my Score But the Buffer Get too small after a while and my Game Crashes.

```
    void CText::Init(const string &_text, int xPos, int yPos, int Width, int Height)
{
    m_Text = _text;
    Font = TTF_OpenFont("arial.ttf", 30);

    SDL_Surface *pTempt = TTF_RenderText_Solid(Font, m_Text.c_str(), color);
    Texture = SDL_CreateTextureFromSurface(m_Renderer, pTempt);

    m_xPos = xPos;
    m_yPos = yPos;

    m_Rect.x = xPos;
    m_Rect.y = yPos;
    m_Rect.w = Width;
    m_Rect.h = Height;
    SDL_FreeSurface(pTempt);
}

void CText::RenderScore(int Score)
{
    sprintf_s(Buffer, "Score: %i", Score);
    SDL_Surface *pTempt = TTF_RenderText_Solid(Font, Buffer, color);
    Texture = SDL_CreateTextureFromSurface(m_Renderer, pTempt);
    SDL_RenderCopy(m_Renderer, Texture, NULL, &m_Rect);
    SDL_FreeSurface(pTempt);
}

//Game Loop
if (lastscore != currentscore)
        {
            m_Text->Destroy(); //<-- This is SDL_DestroyTexture(Texture);
            lastscore = currentscore;
        }else{
        m_Text->RenderScore(currentscore);}

```

It shows my score and Updetes it too but I have my char Buffer\[50\] and after a while it runs out of memory. And i free my font and texture in the destructor.

I thank everybody who helps me out there

# Answer
Every time you call `RenderScore`, you leak an `SDL_Texture` by not calling `SDL_DestroyTexture(Texture)` before reallocating it with `SDL_CreateTextureFromSurface`.
> 3 votes

---
Tags: c++, sdl2, ttf
---


# Question
Title: How can I make caves with Unity's terrain creator?
With Unity's terrain creator, I can't simply make a "hole" on the mesh.

I don't know how I would make cave-like structures other than using "rock" meshes for the roof (wich will indeed look weird) or using portals (wich I always have problems with -- the teleportation isn't thruly smooth and there's always a small "jump". You know, not like a fluid thing.

How can I make caves in terrain with Unity?

# Answer
> 4 votes
Starting from Unity **2019.3**, you can properly cut holes in terrain surface (see https://blogs.unity3d.com/2019/08/27/unity-2019-3-beta-is-now-available/#attachment\_82836) However, this **won't** create the cave mesh for you.

If you are looking for a terrain hole system that creates meshes automatically you may want to use a plugin like this one: https://assetstore.unity.com/packages/tools/terrain/digger-terrain-caves-overhangs-135178

# Answer
> 2 votes
You can't make a cave in Unity's terrain system natively because it uses a 2d heightmap, where each point can only have one height.

This allows for some major optimizations (and a radically different approach) compared to a system that allows for 3D height definition.

But there is an easy work around that AAA games have used (including certain CryENGINE games). Simply make a hole in the terrain and place a mesh representing the cave.

There are different approaches to making holes in a terrain like Unity's. I like the approach taken here for being robust and easy to modify.

---
Tags: c#, 3d, unity, terrain
---


title: AddForce results in stuttering movement

text:
# Question
Title: AddForce results in stuttering movement
I'm currently developing a simple breakout/arkanoid mobile game. Now, I noticed that my ball movement is noticably stuttering. I've read various approaches about how to make the ball move and decided to go for AddForce so I don't have to do any physics calculations myself. The only thing im currently doing is using AddForce on my ball's rigidbody2D and have it collide with the walls and blocks. There's nothing done manually in Update or FixedUpdate and there are no other scripts running while the ball is moving. The scene is pretty empty actually.

Things I have tried so far without success:

* Disable V-Synch
* Increase the velocity iterations (I tried values 15-500)
* Set the RigidBody2D's interpolation mode to: Interpolate/Extrapolate
* Using different mass values and force values in AddForce
* Checking, whether it's just an optical illusion (it seems to run more smoothly in editor and other breakout/arkanoid games don't have that problem on my Galaxy S7)

RigidBody settings of the ball:

* Body Type: Dynamic
* Material: Friction: 0 | Bounciness: 1
* Mass: 0.025
* Linear Drag: 0
* Angular Drag: 0
* Gravity Scale: 0
* Collision Detection: Continous
* Sleeping Mode: Start Awake
* Interpolate: Interpolate

The walls and blocks are simple BoxCollider2D components. And I'm calling AddForce(new Vector2(0f, GameConstants.DESIRED\_BALL\_SPEED)) on the ball's RigidBody2D.

**Edit:**

```
public void OnPointerUp(PointerEventData eventData) {
    if(!_ballStarted) {
        PaddleController.ShootStickingBalls();
        _ballStarted = true;
    }
}

public void ShootStickingBalls() {
    int stickyBallsAmount = _stickingBallsRigidBody2D.Count;
    for (int i = 0; i < stickyBallsAmount; i++) {
        _stickingBallsRigidBody2D[i].AddForce(new Vector2(0f, GameConstants.DESIRED_BALL_SPEED));
        _stickingBallsRigidBody2D[i].transform.SetParent(_nonStickyBallsTransform);
    }
    Sticky = false;
}

```

# Answer
> 0 votes
My intuition on this was correct, it was indeed a general performance problem. I've deactivated all unnecessary quality settings on the camera object (HDR, MSAA, etc.) and now it's running smoothly.

---
Tags: unity, projectile-physics
---


title: Performance problem with chunked LOD

text:
# Question
Title: Performance problem with chunked LOD
I managed to create Zoomable planet. When I get closer to it the respective chunks are splitting and every split holds 4 x 16x16 grid (1024 verts). When getting closer the respective chunks split again and so on. AT the end (let's say when Im on ground), there is so much splits, that when looking on horizont its about 120000 vertices, what is way to much and drops fps to around 7-12. Where I really want like 3-4 layers - near detailed, far less detailed, farest coarse.

I can't get my brain around how to fix this. Any advice appreciated.

# Answer
A few things you can try...

1. **Share your vertices**

You mention you have 16x16 grids of 1024 vertices. But 16x16 is only 256 cells. So it sounds like you're rendering 4 separate vertices for each square of your grid. But 4 adjacent grid squares all share one vertex at their shared corner, so we can use this fact to use our vertex bandwidth more efficiently.

We could have 32 vertices along the x, and 32 vertices along the y, for a total of 1024 vertices and 1922 triangles (31x31x2)
2. **More aggressive LOD reduction**

In a previous answer I recommended halving your grid resolution every time you double your distance, as a way to get approximately even polygon-to-pixel coverage in each detail band. But this is just a guideline.

You could instead choose to halve the resolution each time the distance multiplies by 1.5 - making noticeably larger polygons in the far distance, but these are generally the least important for gameplay, and often get occluded by nearer details, so they're the safest place to drop stuff down.
3. **Render front-to-back**

Draw your closest / highest resolution chunks first. This populates the depth buffer with the closest terrain, so that terrain rendered later will often find itself behind an already-rendered surface, letting the graphics card skip it through an early-Z rejection, so it never has to invoke the fragment shader at all for this bit of terrain.

This doesn't mean you have to draw every polygon in front-to-back order (micromanaging the draw order like this can make it hard to get good batching performance), but even just breaking your terrain into coarse bands and drawing the near band of chunks first can give you substantial reductions in overdraw.
4. **Cull aggressively**

I assume you're already culling chunks outside the camera's frustum (out of view beside/behind the camera, or out beyond the far plane), along with any chunks that are out of view because they're below the horizon from the current viewing angle.

You can use some tricks to bring the rendering horizon closer in order to cull even more.

On the earth, an observer at human height can see about 4.7 km on a clear day, but lots of things can mask that far detail. Atmospheric effects can mask or diminish distant objects, and local geography can occlude more distant landmarks.

So, you could be justified in pulling in your rendering horizon to more like 2-3 km, and culling chunks outside that range. To avoid popping, you can fade the most distant chunks into your skybox as they approach the cut-off, dither them out, or scale them down to 0 height gradually, to help tall-but-distant mountain peaks roll out of view behind closer hills.

On Starlink Battle for Atlas, our planets are actually tiny by the standards of real star systems, and we use vertex shader tricks to bend the horizon to where we want it for our gameplay experience and rendering budget. ;)
5. **Update asynchronously**

If a lot of your frame time is spent iterating over your chunks and deciding which ones need to be up-rezzed or combined, or actually building the new chunk versions (profile and find out), this may be work you can offload.

Set aside a thread to update your chunk information based on the latest camera position, and write it to a second buffer alongside the one the main thread is currently reading/drawing. At the start of each frame, the main thread just picks the latest version of the buffer and works from that, freeing the old buffer for a fresh update pass on the other thread.

You can also enforce a budget of how many chunks you'll regenerate in a single pass, and place them in a queue to be served on the next pass, so you can keep your peak recalculation time bounded, minimizing overall terrain update latency.

It might mean a chunk uprezzes/downrezzes a frame or two later than it should, but unless you're rocketing through the scene this shouldn't be too noticeable (and if you *are* going that fast, a little motion blur or VFX can help hide your sins).
6. **Use bigger chunks**

You mention each grid is 16 x 16. This is extremely small by the usual standards of game terrains. If you're submitting each chunk to the GPU as a separate draw call, then you're spending a lot of your time in the overhead of all these calls and the state switches between them, and giving the GPU relatively little to chew on in each call.

Graphics cards tend to be optimized for the opposite: a smaller number of draw calls, with big batches of data to grind through in each call.

If you're drawing an indexed triangle list with unsigned shorts for your indices, you could fit up to 256 x 256 vertices into a single chunk / a single draw call. Not that this is necessarily the best size (bigger chunks also means less granularity in the border between high & low detail areas, so you might keep more polygons at a redundantly high level of detail than what you strictly need), but it gives you a range to experiment within.
7. **Combine your draw call batches**

Look for ways that you don't need to submit each chunk as its own separate draw call.

This could include setting aside vertex buffers as big as you can make them, then packing multiple chunks into them (eg. if your chunks are 1024 vertices each, you could pack 64 chunks into a single buffer of 65k vertices, and draw them all in a single pass) When a chunk is regenerated, mark its space in the buffer unused, and write its successor(s) in unused buffer slots.

Or you could use GPU tessellation or compute capabilities to send only sparse information to the GPU - like the corners of the chunks or of your rendered area - and let GPU generate all the intermediate triangles within the chunks for you. Then you might be able to submit a single draw call that just says where all the chunks are, and draw all the chunks in one go.

Instead of storing and transferring a full 3-component position, normal, and UV vector for every vertex in the terrain, you might be able to store just a buffer/texture of height values, with the rest determined implicitly as the GPU generates the intermediate vertices, cutting down on memory & bandwidth use and letting you pack more into a single pass (like drawing an 8k x 8k texture's worth of heightmap information all in one go, without also maintaining & sending 67 million vertices' worth of index buffers)

I can't speak to the specific techniques that would be best for your context, but other users may be able to elaborate on strategies to use here.
> 2 votes

---
Tags: procedural-generation, terrain, level-of-detail
---


# Question
Title: Rotating Sprite Around A Point Without Messing Its Drawing Point
I am trying to draw and rotate an arrow sprite based on a point,around a static circle body without messing its drawing starting point. Arrow should be directed to the same direction with user touch point,static body center vector.

Let me explain it with an example.

This is how i calculate arrow drawing point:

```
fun powerIndicatorDownPointCalculator(playerPosition: Vector2,touchPosition: Vector2,distanceBetweenTouchPointAndPlayer:Float):Vector2{
  // player position is static body center,touch position is touch point.

    val playerPositionHolder = playerPosition.cpy()

    val abVector = playerPosition.sub(touchPosition);

    val normalizedAbVector = Vector2(abVector.x/distanceBetweenFingerAndPlayer,abVector.y/distanceBetweenFingerAndPlayer)

    Gdx.app.log("normalized ab vector",normalizedAbVector.toString())

    var pointToAddX  = 90*normalizedAbVector.x
    var pointToAddY  = 90*normalizedAbVector.y

    var newPointX  = playerPositionHolder.x + pointToAddX
    var newPointY = playerPositionHolder.y + pointToAddY
    Gdx.app.log("NEW POINT", Vector2(newPointX,newPointY).toString())

    return Vector2(newPointX,newPointY)

}

```

Here is a simple gif showing it:

https://i.ibb.co/TvHBMh9/MNML-November19-041320-AM.gif

This is how i calculate C point to use later on rotation(?)

```
 fun calculateAimingPoint(playerPosition: Vector2,touchPosition: Vector2):Vector2{
//playerPosition is staticbody center
        val abVector = playerPosition.sub(touchPosition);

        val secondPos = blackBody.position.cpy()
        val cPointPosition  = secondPos.add(abVector)
        return cPointPosition

}

```

This is what i wrote for rotation but for sure it is wrong since not working as i wanted:

```
var angle = atan2(aimingPoint.y - blackBody.position.y, aimingPoint.x - blackBody.position.x ) *180/ PI ;
//aiming point is C point, blackBody is static body
  if (angle > 90)
  {
      angle = 450 - angle;
  }
  else
  {
      angle = 90 - angle;
  }

// powerIndicator.setOrigin(????) // setOrigin is for rotation but i dont now what to write here.

  angle = angle*-1
  powerIndicator.rotation = angle.toFloat()

```

What i actually wanna achieve is this: https://i.ibb.co/gDM9H3L/MNML-November19-042729-AM-2.gif

# Answer
I solved my problem guys. Trick was to set origin correctly

```
  var degrees = (Math.atan2((aimingPoint.x - xDownPoint).toDouble(), -(aimingPoint.y - yDownPoint).toDouble()) * 180.0 / Math.PI - 180.0f).toFloat()

            powerIndicator.setOrigin(powerIndicator.width/2,0f)

           powerIndicator.rotation = degrees

```
> 1 votes

---
Tags: libgdx, mathematics, rotation, vector
---


# Question
Title: Cannot implicitly convert type 'UltimateSurvival.ItemProperty.Value' to 'UnityEngine.GameObject'
As the title states, I am getting this error and I cannot figure out why. I have tried Google and I couldn't find a precise answer as to how to fix it.

Error:

> Assets\Ultimate Survival\Scripts\By Namespace\UltimateSurvival\Inventory\InventoryController.cs(189,32): error CS0029: Cannot implicitly convert type 'UltimateSurvival.ItemProperty.Value' to 'UnityEngine.GameObject'

Code:

```
public bool Try_DropItem(SavableItem item, Slot parentSlot = null)
{
    if(item && item.ItemData.WorldObject)
    {
        var cameraTransform = GameController.WorldCamera.transform;

        GameObject w_Object = item.ItemData.WorldObject;

        if (item.ItemData.IsBuildable)
        {
            w_Object = item.GetPropertyValue("Bag");
        }

        GameObject droppedItem = Instantiate(w_Object, cameraTransform.position + cameraTransform.TransformVector(m_DropOffset), Random.rotation) as GameObject;

        var rigidbody = droppedItem.GetComponent<Rigidbody>();
        if(rigidbody)
        {
            rigidbody.angularVelocity = Random.rotation.eulerAngles * m_DropAngularFactor;
            rigidbody.AddForce(cameraTransform.forward * m_DropSpeed, ForceMode.VelocityChange);

            Physics.IgnoreCollision(m_Player.GetComponent<Collider>(), droppedItem.GetComponent<Collider>());
        }

        var pickup = droppedItem.GetComponent<ItemPickup>();
        if(pickup)
            pickup.ItemToAdd = item;

        if(parentSlot)
            parentSlot.ItemHolder.SetItem(null);

        return true;

    }

    return false;
}

```

ItemProperty:

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

namespace UltimateSurvival
{
[Serializable]
public class ItemCategory
{
    public string Name { get { return m_Name; } }

    public ItemData[] Items { get { return m_Items; } }

    [SerializeField]
    private string m_Name;

    [SerializeField]
    private ItemData[] m_Items;
}

/// <summary>
/// The data / definition for an item.
/// </summary>
[Serializable]
public class ItemData
{
    public string Name { get { return m_Name; } }

    public string DisplayName { get { return m_DisplayName; } }

    public int Id { get { return m_Id; } set { m_Id = value; } }

    public string Category { get { return m_Category; } set { m_Category = value; } }

    public Sprite Icon { get { return m_Icon; } }

    public GameObject WorldObject { get { return m_WorldObject; } }

    public string[] Descriptions { get { return m_Descriptions; } }

    public int StackSize { get { return m_StackSize; } }

    public List<ItemProperty.Value> PropertyValues { get { return m_PropertyValues; } }

    public bool IsBuildable { get { return m_IsBuildable; } }

    public bool IsCraftable { get { return m_IsCraftable; } }

    public Recipe Recipe { get { return m_Recipe; } }

    [SerializeField]
    private string m_Name;

    [SerializeField]
    private string m_DisplayName;

    [SerializeField]
    private int m_Id;

    [SerializeField]
    private string m_Category;

    [SerializeField]
    private Sprite m_Icon;

    [SerializeField]
    private GameObject m_WorldObject;

    [SerializeField]
    [Multiline]
    private string[] m_Descriptions;

    [SerializeField]
    private int m_StackSize = 1;

    [SerializeField]
    private List<ItemProperty.Value> m_PropertyValues;

    [SerializeField]
    private bool m_IsBuildable;

    [SerializeField]
    private bool m_IsCraftable;

    [SerializeField]
    private Recipe m_Recipe;
}

/// <summary>
/// A SavableItem is an instance of an item, which can have it's own properties, vs ItemData which is just the data for an item, just the definition.
/// </summary>
[Serializable]
public class SavableItem
{
    public Message<ItemProperty.Value> PropertyChanged = new Message<ItemProperty.Value>();

    public Message StackChanged = new Message();

    public bool Initialized { get; private set; }

    public ItemData ItemData { get; private set; }

    public int Id { get { return ItemData.Id; } }

    public string Name { get { return ItemData.Name; } }

    public int CurrentInStack { get { return m_CurrentInStack; } set { m_CurrentInStack = value; StackChanged.Send(); } }

    public List<ItemProperty.Value> CurrentPropertyValues { get { return m_CurrentPropertyValues; } }

    [SerializeField]
    private int m_CurrentInStack;

    [SerializeField]
    private List<ItemProperty.Value> m_CurrentPropertyValues;

    public static implicit operator bool(SavableItem item) { return item != null; }

    /// <summary>
    ///
    /// </summary>
    public SavableItem(ItemData data, int currentInStack = 1, List<ItemProperty.Value> customPropertyValues = null)
    {
        CurrentInStack = Mathf.Clamp(currentInStack, 1, data.StackSize);

        if(customPropertyValues != null)
            m_CurrentPropertyValues = CloneProperties(customPropertyValues);
        else
            m_CurrentPropertyValues = CloneProperties(data.PropertyValues);

        ItemData = data;
        Initialized = true;

        for(int i = 0;i < m_CurrentPropertyValues.Count;i ++)
            m_CurrentPropertyValues[i].Changed.AddListener(On_PropertyChanged);
    }

    /// <summary>
    /// Must be called after the item was loaded / deserialized, (not required when the item is created at runtime, through the constructor).
    /// </summary>
    public void OnLoad(ItemDatabase itemDatabase)
    {
        if(itemDatabase)
        {
            ItemData data;
            if(itemDatabase.FindItemById(Id, out data))
            {
                ItemData = data;
                Initialized = true;

                for(int i = 0;i < m_CurrentPropertyValues.Count;i ++)
                    m_CurrentPropertyValues[i].Changed.AddListener(On_PropertyChanged);
            }
            else
                Debug.LogErrorFormat("[SavableItem] - This item couldn't be initialized and will not function properly. No item with the name {0} was found in the database!", Name);
        }
        else
            Debug.LogError("[SavableItem] - This item couldn't be initialized and will not function properly. The item database provided is null!");
    }

    public string GetDescription(int index)
    {
        string description = string.Empty;
        if(index > -1 && ItemData.Descriptions.Length > index)
        {
            try
            {
                description = string.Format(ItemData.Descriptions[index], m_CurrentPropertyValues.ToArray());
            }
            catch
            {
                Debug.LogError("[SavableItem] - You tried to access a property through the item description, but the property doesn't exist. The item name is: " + Name);
            }
        }

        return description;
    }

    public bool HasProperty(string name)
    {
        if(!Initialized)
        {
            Debug.LogError("[SavableItem] - This SavableItem is not initialized, probably it was loaded and not initialized! (call OnLoad() after loading / deserializing).");
            return false;
        }

        for(int i = 0;i < m_CurrentPropertyValues.Count;i ++)
            if(m_CurrentPropertyValues[i].Name == name)
                return true;

        return false;
    }

    /// <summary>
    /// Use this if you are sure the item has this property.
    /// </summary>
    public ItemProperty.Value GetPropertyValue(string name)
    {
        ItemProperty.Value propertyValue = null;

        if(!Initialized)
        {
            Debug.LogError("[SavableItem] - This SavableItem is not initialized, probably it was loaded and not initialized! (call OnLoad() after loading / deserializing).");
            return null;
        }

        for(int i = 0;i < m_CurrentPropertyValues.Count;i ++)
            if(m_CurrentPropertyValues[i].Name == name)
            {
                propertyValue = m_CurrentPropertyValues[i];
                break;
            }

        return propertyValue;
    }

    /// <summary>
    /// Use this if you are NOT sure the item has this property.
    /// </summary>
    public bool FindPropertyValue(string name, out ItemProperty.Value propertyValue)
    {
        propertyValue = null;

        if(!Initialized)
        {
            Debug.LogError("[SavableItem] - This SavableItem is not initialized, probably it was loaded and not initialized! (call OnLoad() after loading / deserializing).");
            return false;
        }

        for(int i = 0;i < m_CurrentPropertyValues.Count;i ++)
            if(m_CurrentPropertyValues[i].Name == name)
            {
                propertyValue = m_CurrentPropertyValues[i];
                return true;
            }

        return false;
    }

    private List<ItemProperty.Value> CloneProperties(List<ItemProperty.Value> properties)
    {
        List<ItemProperty.Value> list = new List<ItemProperty.Value>();
        for(int i = 0;i < properties.Count;i ++)
            list.Add(properties[i].GetClone());

        return list;
    }

    private void On_PropertyChanged(ItemProperty.Value propertyValue)
    {
        PropertyChanged.Send(propertyValue);
    }
}

```

}

# Answer
> 1 votes
Your problem is here:

```
w_Object = item.GetPropertyValue("Bag");

```

You've declared `w_Object` is a `GameObject`, but this function is returning an `UltimateSurvival.ItemProperty.Value` (which you say is effectively a string? We can't see that part in your question...)

Unity doesn't know how to convert that value into the `GameObject` you want to reference, so we have to tell it what we want it to do.

> I want to produce a gameobject and the title of the prefab is stored in that UltimateSurvival.ItemProperty.Value

Here's one simple way to do it, where you populate a shortlist of prefabs in the Unity Inspector.

```
public List<GameObject> prefabs;

GameObject InstantiatePrefabByName(string name) {
    // Find a prefab in our list that has a name matching this string.
    var source = prefabs.Find(prefab => prefab.name == name);

    // If we didn't find a hit, throw an error that helps us diagnose the issue.
    if(source == null) {
        Debug.LogErrorFormat(
            "Tried to instantiate unknown prefab name, \"{0}\"",
            name
        );
        // Return a dummy game object as the best we can do.
        return new GameObject(name + " (Missing)");
    }

    // Instantiate our prefab and return the instance.
    return Instantiate(source);
}

```

Then you can call this with something like...

```
// I assume you get your string value with ToString() - if not, swap this part.
string prefabName = item.GetPropertyValue("Bag").ToString();

// Now we call our prefab-finding-and-spawning function with this string.
w_Object = InstantiatePrefabByName(prefabName);

```

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


title: Nested transform.position in Unity

text:
# Question
Title: Nested transform.position in Unity
The following code works so good , but it is so long.

How can I use a `for` loop to write a short script for any number of prefabs?

```
public GameObject prefab1;
public GameObject prefab2;
public GameObject prefab3;
float timCounter = 0f;

void FixedUpdate()
{
  timCounter += Time.deltaTime;

  float[]  r = {3,2,1};
  float[]  f = {3,2,1};

  //motion on a circle

  float x = r[0] * Mathf.Cos(f[0] * timCounter);
  float y = r[0] * Mathf.Sin(f[0] * timCounter);

  float x1 = r[1] * Mathf.Cos(f[1] * timCounter);
  float y1 = r[1] * Mathf.Sin(f[1] * timCounter);

  float x2 = r[2] * Mathf.Cos(f[2] * timCounter);
  float y2 = r[2] * Mathf.Sin(f[2] * timCounter);

  float z = 0;

  //position of a any prefab_n = position of prefab_(n-1) + Vector3(x,y,z)

  prefab1.transform.position = new Vector3(x,y,z);

  prefab2.transform.position = prefab1.transform.position + new
  Vector3(x1,y1,z);

  prefab3.transform.position = prefab2.transform.position + new
  Vector3(x2,y2,z);
 }

```

# Answer
> 1 votes
Try something like this:

```
public GameObject[] prefabs;
public float[] r;
public float[] f;
float timeCounter = 0f;

void FixedUpdate()
{
    timeCounter += Time.deltaTime;

    var z = 0;
    var numPrefabs = prefabs.Length;
    var prevPosition = new Vector3(0, 0, 0);

    for (var i = 0; i < numPrefabs; ++i)
    {
      var x = r[i] * Mathf.Cos(f[i] * timeCounter);
      var y = r[i] * Mathf.Sin(f[i] * timeCounter);
      var pos = new Vector3(x, y, z);

      prefabs[i].transform.position = prevPosition + pos;

      prevPosition = pos;
    }
}

```

Here we have an array of game objects to proceed. You should link them to your game objects in Unity Inspector as well as setup r array and f array. Then this script will iterate over all game objects and set a position like in your script.

---
Tags: unity, transformation
---


# Question
Title: Upper & Lower angular limits on Y and Z axes
**My Task:** I'm trying to replicate this project. I'm using unity as my physics engine. Currently I'm still learning how to work with the different joints unity has to offer. The type of movement I'm looking for is where a body is connected to only one other body and its relative movement can be limited based on angles on different axes.

**My Problem:** I'm using Configurable joints for my movement restrictions. The *Low Angular X Limit* and *High Angular X Limit* does exactly what I'm looking for since it can have a different uppper and lower rotation limit. Looking at the documentation, it seems that this can only be done on the X axis. The Y and Z axes only have a *Angular Y Limit* or *Angular Z Limit* which set the upper as the opposite of the lower limit.

**My Question:** Is it possible for the Y and Z axes to have the same lower-upper limit system that the X axis has? Is the use of configurable joint good for this task?

Thanks in advance :)

# Answer
> 1 votes
I used the method @DMGregory suggested and rotated the joint before setting the limits. Since the joint limits rotation and also cannot be disabled I created a script that rotates and then adds the joint.

```
public class ConfigJoint : MonoBehaviour {

    private ConfigurableJoint joint;

    [SerializeField]
    private Rigidbody connectedBody;

    [Header("Angular X Limits")]

    [SerializeField, Range(-180, 0)]
    private float xLower;
    [SerializeField, Range(0, 180)]
    private float xUpper;

    [Header("Angular Y Limits")]
    [SerializeField, Range(-180, 0)]
    private float yLower;
    [SerializeField, Range(0, 180)]
    private float yUpper;

    [Header("Angular Z Limits")]
    [SerializeField, Range(-180, 0)]
    private float zLower;
    [SerializeField, Range(0, 180)]
    private float zUpper;

    [Header("Anchors")]
    [SerializeField]
    private Vector3 anchor;
    [SerializeField]
    private Vector3 connectedAnchor;

    void Start () {

        Rotate(); // Rotate to the rotation that matches the wanted limits

        joint = gameObject.AddComponent<ConfigurableJoint>();  // Adds a configurable joint

        LockMotion();   // Sets all movement to Locked
        LimitRotation();    // Sets all angular movement to Limited

        SetAnchors();   // Sets the anchors to the wanted anchors

        SetAngularLimits();  // Sets the limits for the joint
    }

    private void Rotate()
    {
        // The mid point between the upper and lower limit
        float xMid = (xUpper + xLower) / 2;
        float yMid = (yUpper + yLower) / 2;
        float zMid = (zUpper + zLower) / 2;

        //Debug.Log("Setting rotation: " + new Vector3(xMid, yMid, zMid));
        transform.localRotation = Quaternion.Euler(xMid, yMid, zMid);
    }

    private void SetAngularLimits()
    {
        // The value that each angular limit needs to be to create the effect of an upper and lower limit
        float xAbsAvg = (xUpper - yLower) / 2;
        float yAbsAvg = (yUpper - yLower) / 2;
        float zAbsAvg = (zUpper - zLower) / 2;

        SoftJointLimit sjl = new SoftJointLimit();

        sjl.limit = xAbsAvg;
        joint.highAngularXLimit = sjl;

        sjl.limit = -xAbsAvg;
        joint.lowAngularXLimit = sjl;

        sjl.limit = yAbsAvg;
        joint.angularYLimit = sjl;

        sjl.limit = zAbsAvg;
        joint.angularZLimit = sjl;

    }

    private void SetAnchors()
    {
        joint.connectedBody = connectedBody;
        joint.anchor = anchor;
        joint.connectedAnchor = anchor;
    }

    private void LockMotion()
    {
        // Body parts should not move. They can only rotate
        joint.xMotion = ConfigurableJointMotion.Locked;
        joint.yMotion = ConfigurableJointMotion.Locked;
        joint.zMotion = ConfigurableJointMotion.Locked;
    }

    private void LimitRotation()
    {
        joint.angularXMotion = ConfigurableJointMotion.Limited;
        joint.angularYMotion = ConfigurableJointMotion.Limited;
        joint.angularZMotion = ConfigurableJointMotion.Limited;
    }
}

```

**How to use:** Add this to the component you would add the configurable joint to. All parameters are pretty self-explanatory or parallel to those in regular joints.

---
Tags: unity, rotation, joints
---


# Question
Title: Engine for a Football Manager Type game (data driven, menu clicking)
A friend and I had started developing a football manager two years ago, but ultimately squashed the whole thing because we found ourselves in a mess with developing UI and saving/loading.
The basic game loop of simulating matches and advancing days until the match day was already done. We also had a e-mail system up and running (for receiving messages which might need decisions/trigger events).
In our lack of of knowledge, we tried building the game in GameMaker2. It made saving all the objects (a Team has 23 Player, a league has 20 Teams, there are several Leagues) a nightmare. Also, UI development (things like scrollbars for example) ate up incredible amounts of our time and still everything looked relatively bland. Short: GameMaker2 seemed not suitable for the type of game we wanted to build.
There must be a better engine/system for developing a manager type game. Most of the game is spent in menus, There's *no* time-critical interaction going on. Since we've benched the project, I started working a legit software development job and I have gained some skills which I hadn't have before, like knowledge of databases and a heap of Python experience.

It has me looking at the game again. Now I see it as having a 'data backend' and an point-and-click-frontend, with game design elements, like tough decisions, events and goals as the driving force in the middle.
We want nice looking menus, where players can set the training schedule, make the line-up for match day, talk to players/executives/whoever. The other necessity is managing all data objects, which there will a lot of. A league might easily contain 400 players which all need to have stats and so on and so forth. I see a relational database for this, but maybe there's something smarter regarding game-development?

## So my Question is:

What is a suitable game engine/development stack for developing data-heavy, non real-time menu-clicking type manager games such as a football manager?

# Answer
> 0 votes
I don't have GameMaker direct/specific experience but I hear/read this type of questions often. I would like to give you some consolation by saying that GameMaker isn't fit for UI-heavy projects but look at Kingsway for example.

The question template is "**I failed with this game engine, is there a better game engine?**". I'm sure GameMaker has its own limits (like all facilitated game engines) but the variety of games made with GameMaker is pretty amazing which makes me say that quite likely you didn't have enough experience to complete your idea. Have you considered starting from the scratch? In your situation I would not discard this path because even if you find the next game engine, you'll have another learning curve and you certainly learnt something very valuable (about GameMaker and more) from your (also very valuable) failure. You should think twice before throwing away what you learnt.

So, I could tell you to go Cocos 2D or Unity or even consider going with a HTML5 engine or go to a UI framework like Qt but are you sure you want to climb another learning curve?

I think you are in a good place. You realised that you failed and you need to understand the value of this awareness (that many don't get). You know you failed, you can now sit down and understand how, where and when you failed and learn from your mistakes.

Starting over is just the right move sometimes.

Also, when you start over you never really start over in the strict sense. There's always stuff you can refactor and reuse and it's a good feeling to see the things you did right and carry them over to your version 2.

I know it's a borderline answer but I this is what I sincerely think of your situation and I hope this helps and encourages you to make treasure of your failure and maybe fail again and then one day publish a real killer game!

Have fun!

---
Tags: software-engineering, databases, turn-based
---


# Question
Title: How to develop VR PC games without a Head-Mounted Display of my own?
I am an intermediate student of Unity 3D, and I am not able to purchase heavy and expensive equipment like Oculus Rift, HTC Vive, or other models that are not available in Pakistan.

So I'm wondering how I can develop VR games without these peripherals.

# Answer
> 3 votes
I'd recommend that you do not try to develop for a platform you cannot test on.

This is a recipe for a long, slow, and confusing development process, and a poor result with terrible experience for your players. You have so many other options for target platforms — with vastly greater market share — I don't see any good reason to put yourself in this position.

That said, since Unity is a cross-platform engine that can package games for both mobile and PC, you could as TomTsagk mentioned get yourself a Google Cardboard to test your VR experience with your phone, then compile for Oculus/PC and *hope* it behaves similarly.

I'd recommend you at the very least recruit some testers (working remotely) who do have the actual hardware, and can test your Oculus builds and send you feedback. This likely means a day or more turnaround to find out whether your bug fix worked, so it's not a good way to make high-quality games (or enjoy your job). But if you're dead set on developing for VR without the necessary tools then I think this is the closest you can get.

---
Tags: unity, virtual-reality
---


title: Question about CDLOD quad tree

text:
# Question
Title: Question about CDLOD quad tree
I have been digging and researching into CDLOD and there are some things I dont understand.

https://github.com/fstrugar/CDLOD/blob/master/cdlod\_paper\_latest.pdf states:

> The quadtree structure is generated from the input heightmap. It is of constant depth, predetermined by memory and granularity requirements. Once created, the quadtree does not change unless the source heightmap changes. Every node has four child nodes and contains minimum and maximum height values for the rectangular heightmap area that it covers.

Doe's this mean I calculate **every** node and child nodes to the finest level at the setup phase (i do not split and unsplit at run)? If so, what's the roughest level I start with? And how do I get the minimum and maximum height from my perlin noise height map for an node area?

Lastly how CDLOD would work, when I zoom in/out into a big planet (up factor)? Can get that into my imagination.

# Answer
> 1 votes
> > The quadtree structure is generated from the input heightmap. It is of constant depth, predetermined by memory and granularity requirements.
>
> Does this mean I calculate every node and child nodes to the finest level at the setup phase?

Yes, for the "quadtree data" that contains only min/max height information.

> I do not split and unsplit at runtime?

At runtime, you may load/generate heightmap "terrain data" for the chunks that need to be visible at a particular level of detail, and recycle chunks of heightmap that are no longer in view / no longer of the needed level of detail. So you do not need to have all of the terrain loaded at all times, only a minimal bit of metadata about its bounds.

> What's the roughest level I start with?

You start at the root of the tree - the largest square that encompasses your terrain. For the case of a planet, you might have 6 roots: one for each face of a cube that you project into the spherical domain.

You continue down to the finest level of granularity your game will support. On planetary scales with procedural geometry, this might span a truly stupendous range, so you will likely want to handle this as an offline pre-process if you can, and set it up so you keep only a fixed number of levels "in core" at a time, writing out the results to the metadata structure as you go and discarding any bit of heightmap you're not actively investigating.

If you need this for a planet that is not known at build time, but generated at runtime, then you will need to use a different algorithm, or adapt it to skip this complete top-to-bottom scan, possibly using looser bounds as discussed below.

> How do I get the minimum and maximum height from my Perlin noise height map for a node area?

Since the description of the algorithm asks you to evaluate all the way down to the finest granularity leaf node as part of the process, the trivial answer is: generate the height for every point in the terrain mesh in that leaf, and store the min and max that you generated.

Then you can throw out that leaf, and proceed to the next one. Once you have four leaves, you can take the minimum of the four leaf minima, and use that as the parent node's minimum. Then take the maximum of the four leaf maxima, and use that as the parent node's maximum. Then you can compress the leaf minima & maxima into the normalized range of the parent's min & max for compression purposes, as described in the paper.

The process then repeats with four parent nodes' minima & maxima informing the grandparent node's min & max, recursively all the way up the tree.

You may be able to approximate this without visiting every tilemap point:

Most noise-based terrain algorithms use a concept of "octaves", where you add together multiple noise samples over increasingly fine spatial frequencies and diminishing amplitude. In these cases, the first octave dominates the resulting height, and changes the least often over a range.

So, given a node in your quadtree, you can evaluate how many grid cells of the first octave it covers.

* If it covers more than a threshold number of cells, you can conclude "the terrain probably hits both the global min and global max over this range" and just use your most conservative limits (ie. assuming every octave contributes its full amplitude at one point, and every octave hits its lowest possible value at another point).
* If it covers a smaller number of grid cells, then you can walk through those cells and determine for each what minimum or maximum this first octave hits in each cell. Multiply that by the octave's amplitude, then make it a conservative estimate by adding the maximum possible impact of all the other octaves added together.

This gives you a ballpark for the min/max the noise function will take over that area, with a bounded amount of computation, even for planetary hexant scale quadtree nodes of indeterminate maximum detail.

> How would CDLOD work, when I zoom into/out of a big planet?

Your computed distance from each node changes, leading you to either morph it toward and ultimately replace it with a coarser mesh, or subdivide it into finer meshes.

The main difference from the flat plane case is that your distance calculation will need to take into account the curvature of the planet when you're a long distance away, so that chunks that curve away from you are adequately down-rezzed.

You may also need to adjust the formula for morphing between detail levels in the vertex shader to apply the spherical projection *after* the morphing. I expect trying to apply the morphing in the curved form could get more complex. Doing it this way, the algorithm can basically pretend it's working on a flat plane, then you can just bend the result to fit your real application as a kind of post-process.

---
Tags: procedural-generation, terrain, level-of-detail
---