Search code examples
c#floating-pointintegerunity3d-terrain

How do you Calculate with floats in c#


I want to programm a terrain generator in Unity and already have some working code for a Perlin Noise Terrain Generator. Im currently using Unity (using c#) and i cant figure out how to seperate the generation of the terrain depth(z)(the height of the mountains/depth of the valleys which i want to calculate using a Sqrt function) depending on x and the terrain depth depending on y. My problem is, when i try to convert the floats into ints, i would have to round them up or else they wont work, but i want to calculate the Terraindepth smoothly, is there a way i can combine those 2 heights into 1 without roughening the terrain?

float CalculateHeights(int x, int y)
{
    float xCoord = x;

        private int xz = float xCoord; 

    float yCoord = (float)y / height; 

        private int yz =float yCoord;

    int z = (xz + yz) / 2;

    return Mathf.Sqrt(z);
}

Solution

  • If you're trying to use Perlin Noise in Unity, you can always use the inbuilt generator.

    Ex:

    float height = Mathf.PerlinNoise(X,Y);
    

    Warning though: If you don't use floating point values for X and Y with this function, you'll have issues with always getting the same value.

    Hope this helps.

    Docs - https://docs.unity3d.com/ScriptReference/Mathf.PerlinNoise.html