About Monkey 2 › Forums › Monkey 2 Code Library › Multiple loops at the same time (fast and slow)
This topic contains 0 replies, has 1 voice, and was last updated by 
 cocon 1 year, 6 months ago.
- 
		AuthorPosts
 - 
		
			
				
October 2, 2017 at 6:46 am #10922
This is one simple approach to have multiple loops in the game at the same time for drawing or updating operations. The basic idea is that not everything should be updated at the same time, some components need to be slow and others fast. For example casual AI decisions can run on 10 fps, animation update at 24, graphics rendering at 60 fps.
Apart from updating different modules, there can be other usages, where simply treated as a list of timers. For example if the application runs some sort of validation functions every one second, saves automatically every 10 seconds.
Perhaps the code might not be of a big deal, but the concept is a good idea, to avoid brute force updates and manage them in an organized different way.
Monkey123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102#Import "<std>"#Import "<mojo>"Using std..Using mojo..Class MultiLoopField Loops := New Map<String, LoopDetails>Class LoopDetailsField Frequency:DoubleField Time:DoubleField Callback:Void()EndMethod Add(name:String, fps:Int, callback:Void())Local details := New LoopDetailsdetails.Time = Now()details.Frequency = 1.0 / fpsPrint(details.Frequency)details.Callback = callbackLoops.Add(name, details)EndMethod Update()For Local loop := Eachin Loops.ValuesIf Now() > loop.Time + loop.Frequencyloop.Callback()loop.Time = Now()EndNextEndEndClass MyApp Extends WindowField item1:Item, item2:Item, item3:ItemField loops := New MultiLoopMethod New()Super.New("Monkey 2 Application", 800, 800)item1 = New Itemitem2 = New Itemitem3 = New Itemitem1.Color = New Color(0.8, 0.0, 0.0)item2.Color = New Color(0.0, 0.8, 0.0)item3.Color = New Color(0.0, 0.0, 0.8)loops.Add("Slow Red", 1, Lambda()item1.UpdateRandom()End)loops.Add("Medium Green", 10, Lambda()item2.UpdateRandom()End)loops.Add("Fast Blue", 60, Lambda()item3.UpdateFalling()End)EndMethod OnRender(canvas:Canvas) OverrideApp.RequestRender()loops.Update()canvas.Color = item1.Colorcanvas.DrawCircle(item1.Position.X, item1.Position.Y, 20)canvas.Color = item2.Colorcanvas.DrawCircle(item2.Position.X, item2.Position.Y, 20)canvas.Color = item3.Colorcanvas.DrawCircle(item3.Position.X, item3.Position.Y, 20)canvas.Flush()EndEndFunction Main()New AppInstanceNew MyAppApp.Run()EndClass ItemField Position := New Vec2fField Color:ColorMethod UpdateRandom()Position.X = Rnd(0, App.ActiveWindow.Width)Position.Y = Rnd(0, App.ActiveWindow.Height)EndMethod UpdateFalling()Position.Y += 20If Position.Y > App.ActiveWindow.Height + 10Position.X = Rnd(0, App.ActiveWindow.Width)Position.Y = -10EndEndEnd - 
		AuthorPosts
 
You must be logged in to reply to this topic.