Nov
10
2014

Draw Ascii Sphere

draw_text_sphere_ascii_unity_csharp

Just for fun tried to convert this LUA script into unity c#,
Original source: http://rosettacode.org/wiki/Draw_a_sphere#Lua

*Note this source outputs the file into spheredump.txt file (at project root folder)

C# Source ( DrawSphere.cs ) *not optimized..


// ORIGINAL SOURCE: http://rosettacode.org/wiki/Draw_a_sphere#Lua

using UnityEngine;
using System.Collections;

public class DrawSphere : MonoBehaviour
{

    char[] shades = new char[]{'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'};
    Vector3 lightVec;

    void Start ()
    {
        lightVec = normalizer(30, 30, -50);
        draw_sphere (20, 4, 0.1f);
    }

    void draw_sphere (float radius, float k, float ambient)
    {
        string lineTemp = "";
        for (int i = (int)Mathf.Floor(-radius);i<-(int)Mathf.Floor(-radius);i++)
        {
            int x = (int)(i + 0.5f);

            for (int j = (int)Mathf.Floor(-2*radius);j<(int)-Mathf.Floor(-2*radius);j++)
            {
                float y = (j / 2 + 0.5f);
                if ((Mathf.Pow(x,2) + Mathf.Pow(y,2)) <= (Mathf.Pow(radius,2)))
                {
                    Vector3 vec = normalizer(x, y, Mathf.Sqrt( Mathf.Pow(radius,2)-Mathf.Pow(x,2)-Mathf.Pow(y,2)));
                    float b = Mathf.Pow(dotter(lightVec,vec),k) + ambient;
                    float intensity = (int)(Mathf.Floor((1 - b) * shades.Length));
                    lineTemp = lineTemp + ((intensity>-1)?shades[(int)intensity]:shades[0]);
                }else{
                    lineTemp = lineTemp + " ";
                }
            }
            lineTemp = lineTemp+System.Environment.NewLine;
        }

        // output to textfile
        System.IO.File.WriteAllText("spheredump.txt", lineTemp);
    }

    Vector3 normalizer(float vec1,float vec2, float vec3)
    {
        float[] vec = new float[]{0,vec1,vec2,vec3};
        float len = Mathf.Sqrt( Mathf.Pow(vec[1],2) + Mathf.Pow(vec[2],2) + Mathf.Pow(vec[3],2));
        return new Vector3 (vec[1]/len, vec[2]/len, vec[3]/len);
    }
        
    float dotter(Vector3 vec1, Vector3 vec2)
    {
        float d = (vec1[0]*vec2[0] + vec1[1]*vec2[1] + vec1[2]*vec2[2]);
        return d<0?-d:0;
    }
}

 

 


Leave a comment

Connect

Twitter View LinkedIn profile Youtube Github Join Discord Twitch Instagram BlueSky

UnityLauncherPro

Get UnityLauncherPRO and work faster with Unity Projects!
*free unity hub alternative

@unitycoder_com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.