Share My Creation Starfield 3D

Just a neat little 3d starfield effect
The current values ensure a fairly lightweight device usage

starfield.png


B4X:
' Starfield 3D - Jim Brown
' V1.2 - Tweaked for a smoother look + added screen stay wake
'
' NOTE: Ensure you enable the "Phone" library

Sub Process_Globals
   Dim time As Timer
   Dim awake As PhoneWakeState
End Sub

Sub Globals
   ' starfield control variables
   Type star (x As Float,y As Float,z As Float,sx As Float,sy As Float)
   Dim s(80) As star
   Dim spread As Int
   Dim speed As Float
   Dim cx,cy As Int
   Dim count As Int
   ' display-related variables
   Dim can As Canvas
   Dim paint As Int
   Dim rec As Rect
End Sub

Sub Activity_Create(FirstTime As Boolean)
   For n=0 To s.Length-1
      RandomPos(n)
   Next
   spread=52   ' the spread of the stars (smaller value narrows the field)
   speed=0.7   ' speed of starfield movement
   cx=Activity.Width/2 : cy=Activity.Height/2
   can.Initialize(Activity)
   time.Initialize("Timer1",4)
End Sub

Sub Activity_Resume
   time.Enabled=True
   awake.KeepAlive(True)
End Sub

Sub Activity_Pause (UserClosed As Boolean)
   time.Enabled=False
   awake.ReleaseKeepAlive
End Sub

Sub Timer1_Tick
   ' update stars
   For n=0 To s.Length-1
      If s(n).z<speed Then RandomPos(n)
      s(n).z=s(n).z-speed
      s(n).sx=(s(n).x*spread)/s(n).z + cx
      s(n).sy=(s(n).y*spread)/(4+s(n).z) + cy
      If s(n).sx<0 OR s(n).sx>Activity.Width Then RandomPos(n)
      If s(n).sy<0 OR s(n).sy>Activity.Height Then RandomPos(n)
   Next
   count=count+1
   ' draw stars
   If count Mod 4=0 Then 
      can.DrawColor(Colors.ARGB(90,0,0,0))
      For n=0 To s.Length-1
         paint=Colors.RGB(255-s(n).z,255-s(n).z,255-s(n).z)
         ' can.DrawPoint(s(n).sx,s(n).sy,paint)
         rec.Initialize(s(n).sx,s(n).sy,s(n).sx+5,s(n).sy+4)
         can.DrawRect(rec,paint,True,0)
      Next
      Activity.Invalidate
   End If
End Sub

Sub RandomPos(num)
   s(num).z=Rnd(230,255)
   s(num).x=Rnd(-1000,1000)
   s(num).y=Rnd(-1000,1000)
End Sub
 
Last edited:

Jim Brown

Active Member
Licensed User
You can also get a neat 'warp' effect by clearing the screen with
B4X:
can.DrawColor(Colors.ARGB(70,0,0,0))
 
Top