10
2014
Draw Ascii Sphere

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;
}
}
Related Posts
Leave a comment
Recent posts
- Favorites in PackageManager
- LudumDare59 : Signal
- Unity Editor: Tree Generator
- Leaf/Foliage Generator Tools (Runs in Browser)
- Testing Unity AI Beta
- Ways to Support UnityCoder Development
- Using UI Slider to Create 5-Star Rating Element
- Game Music Library For Unity (editor plugin)
- Fontastic : Easily Test Fonts in Unity Editor!
- GeoTiff Importer & Terrain Generator for Unity
- Create Baked DropShadow for UI images
- .JP2 Ortho Image Converter to PNG/JPG/TIFF
Recent Comments
- on Mesh Exploder (sources)
- on Sprite Sheet Flip Book Shader
- on Sprite Sheet Flip Book Shader
- on [Asset Store] PolygonCollider2D Optimizer
- on Trajectory Test Scene 2.0
- on Vector3 maths for dummies!
- on UnityHub 3.6.0: Remove Version Control & Cloud Dashboard columns
- on Using RenderDoc with Unity (graphics debugger)
Coin:
CUgDSbRqFcAumDSAcdKDvuXsw26VdkJe8C8WGUQHBAGS
An article by











