HTML5 3D Stars

The 3D stars are again embedded in this blog post and source code with old mojo is simplified.

The code is written in Monkey X Pro, which is nowadays available on itch.io.

Here’s the code:

Import mojo

Function Main:Int()
	New MyApp
	Return 0
End

Class MyApp Extends App

	Const STARS:Int = 200
	
	Field devWidth:Float, devHeight:Float, scaleX:Float, scaleY:Float
	Field x:Float[STARS],y:Float[STARS],z:Float[STARS]

	Method OnCreate()

		scaleX = DeviceWidth() / 640
		scaleY = DeviceHeight() / 480
		
		For Local i:Int = 0 To STARS - 1
			x[i] = Rnd(-50,50)
			y[i] = Rnd(-50,50)
			z[i] = Rnd(50,200)
		Next
		
		
		SetUpdateRate(60)
	End

	Method OnUpdate()
	
	End
	

	Method OnRender()
		
		Local shade:Float
		
		PushMatrix()
		Scale(scaleX,scaleY)
		Cls

		For Local i:Int = 0 To STARS - 1
			
			z[i] = z[i] - 1
			If z[i] < 10 Then z[i] = Rnd(50,200)
		
			shade = 255 - (z[i] / 200) * 255
			SetColor shade,shade,shade
		
			' Projection from 3D space to 2D screen	
				
			DrawOval(x[i] / z[i] * 200 + 320,y[i] / z[i] * 200 + 240,2,2)
			
		Next

		
		PopMatrix()
		
	End

End Class

Do use my code as you wish.

%d bloggers like this: