3D MeshInstances spawn c# script

systemerrorsystemerror Posts: 9Member
edited July 27 in Tutorials

Hi community,
meshinstances added from c# script to test how to add for example spheres. in the first example with metallic material and random positions/colors - only for fun and to get a nice picture:

using Godot;
using System;

public class Spheres : Spatial
{

    public override void _Ready()
    {
        for (int i = 0; i < 77; i++)
        {
            NewSphere();
        }
    }


    public void NewSphere()
    {
        var r1 = new RandomNumberGenerator();
        r1.Randomize();
        MeshInstance mi = new MeshInstance();
        mi.Mesh = new SphereMesh();
        var ma = new SpatialMaterial();
        var color = new Color(r1.Randf(), r1.Randf(), r1.Randf());
        ma.AlbedoColor=color;
        ma.Metallic=0.85f;
        ma.Roughness=0.4f;
        mi.MaterialOverride = ma;
        var newscale = new Vector3(r1.Randf()+0.4f, r1.Randf()+0.4f, r1.Randf()+0.4f);
        mi.Scale=newscale;
        var newtrans = new Vector3(r1.Randf()*10-5, r1.Randf()*10-5, r1.Randf()*10-5);
        mi.Translate(newtrans);
        AddChild(mi);
    }
}

in the second example we change the code only in the way that we arrange the spheres on the x and z coordinates and change the y/height and the color by a function and we have a functionplotter. there are many other possible functions like 7*(Sin(x/5)+Cos(z)) etc (the code of the colors is not good ok):

using Godot;
using System;

public class Functionplotter : Spatial
{

    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        for (int x = 1; x < 32; x++)
        {
            for (int z = 1; z < 32; z++)
            {
                NewSphere((float)x, (float)z);
            }
        }
    }


    public void NewSphere(float x, float z)
    {
        MeshInstance mi = new MeshInstance();
        mi.Mesh = new SphereMesh();
        var ma = new SpatialMaterial();
        float d1=12.0f;
        float function=(float)Math.Exp(-Math.Cos(x/d1*x/d1+z/d1*z/d1));
        var color = new Color(function/2.0f/(x/2), function/2.0f/(x/10+z/10), function/2.0f/(z/2));
        ma.AlbedoColor=color;
        mi.MaterialOverride = ma;
        var newscale = new Vector3(0.5f, 0.5f, 0.5f);
        mi.Scale=newscale;
        var newtrans = new Vector3(x*1.5f, function*4.0f, z*1.5f);
        mi.Translate(newtrans);
        AddChild(mi);
    }
}

To start add a project-3D with a Spatialnode, add the c#script with code above, add a camera and a light...

btw: why are always some codelines outside the codesection can you tell me please?


Tags :

Comments

  • MegalomaniakMegalomaniak Posts: 2,785Admin

    Fixed the code formatting in the OP. Thanks for contributing. :)

Sign In or Register to comment.