3D Stars As Lines

I must have been really tired when I coded & posted the old 3D stars codes… Anyway, here’s code for 3D stars as lines.

Below the video:

To get the stars drawn as lines is really simple. In the 2D world to draw a line we need x1, y1, x2 and y2. In the projection from 3D space, we simple add for example 4 to the z-coordinate of a point so that, the other point is further away and we get two points to the 2D world.

Below is the main part of the Monkey X source code:

		' Projection from 3D space to 2D screen
		For Local i:Int = 0 To STARS - 1
			Local x1,x2,y1,y2:Float
			
			z[i] = z[i] - 1
			If z[i] < 10 Then z[i] = Rnd(50,200)
						
			sx = x[i] / z[i] * 200 + 320
			sy = y[i] / z[i] * 200 + 240
			
			shade = 1 - z[i] / 200
			canvas.SetColor shade,shade,shade
			
			x1 = x[i] / z[i] * 200 + 320
			x2 = x[i] / (z[i] + 4) * 200 + 320
			y1 = y[i] / z[i] * 200 + 240
			y2 = y[i] / (z[i] + 4) * 200 + 240
			
			canvas.DrawLine(x1,y1,x2,y2)
			
		Next

For the end the source code in full:

Import mojo2

Function Main:Int()
	New MyApp
	Return 0
End

Class MyApp Extends App

	Const STARS:Int = 280
		
	Field x:Float[STARS],y:Float[STARS],z:Float[STARS]
	
	Field canvas:Canvas
	Field sx:Float, sy:Float
	
	Method OnCreate()

		For Local i:Int = 0 To STARS - 1
			x[i] = Rnd(-50,50)
			y[i] = Rnd(-50,50)
			z[i] = Rnd(50,200)
		Next
		
		canvas = New Canvas()
		
		SetUpdateRate(60)
	End

	Method OnUpdate()
						
	End
	

	Method OnRender()
		
		Local shade:Float
		
		canvas.PushMatrix()

		canvas.Clear()

		' Projection from 3D space to 2D screen
		For Local i:Int = 0 To STARS - 1
			Local x1,x2,y1,y2:Float
			
			z[i] = z[i] - 1
			If z[i] < 10 Then z[i] = Rnd(50,200)
						
			sx = x[i] / z[i] * 200 + 320
			sy = y[i] / z[i] * 200 + 240
			
			shade = 1 - z[i] / 200
			canvas.SetColor shade,shade,shade
			
			x1 = x[i] / z[i] * 200 + 320
			x2 = x[i] / (z[i] + 4) * 200 + 320
			y1 = y[i] / z[i] * 200 + 240
			y2 = y[i] / (z[i] + 4) * 200 + 240
			
			canvas.DrawLine(x1,y1,x2,y2)
			
		Next
	
		canvas.Flush()
		
		canvas.PopMatrix()
		
	End

End Class

Feel free to use this code.