About Monkey 2 › Forums › Monkey 2 Code Library › Control Manager
Tagged: controls conditions lambda
This topic contains 1 reply, has 2 voices, and was last updated by 
 regulark 1 year, 6 months ago.
- 
		AuthorPosts
 - 
		
			
				
October 8, 2017 at 12:40 pm #11040
I created a simple yet very flexible class to deal with controls, it can best be described as, “when a certain condition is met then perform an action”.
I’m using it for user controls, e.g. when you touch the screen or press a key or rotate the device, then do something to the player sprite, etc. But it’s not limited to user input, it works for any type of condition.
It’s basically just stuff you would otherwise put into the OnRender loop, which works just the same, but I prefer to have these conditions and commands packaged in one place. Plus, you add every control with a reference key, so you can then disable and enable the these controls easily. Again, nothing you couldn’t do in the OnRender loop, but I find this approach a bit cleaner. I’m using it with Lambda functions, but could be done otherwise as well.
Monkey12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152Class ControlField Condition:Bool()Field Callback:Void()Field Enabled:Bool = TrueEndClass ControlManagerField Controls := New Map<String,Control>Method Add ( key:String, condition:Bool(), callback:Void() )Local control := New Control()control.Condition = conditioncontrol.Callback = callbackControls.Add( key, control )EndMethod Remove ( key:String )Controls.Remove( key )EndMethod Disable ( key:String )Controls.Get( key ).Enabled = FalseEndMethod Enable ( key:String )Controls.Get( key ).Enabled = TrueEndMethod DisableAll ()For Local key := Eachin Controls.KeysDisable( key )NextEndMethod EnableAll ()For Local key := Eachin Controls.KeysEnable( key )NextEndMethod OnUpdate ()For Local control := Eachin Controls.ValuesIf control.Enabled And control.Condition()control.Callback()EndNextEndEndJust create an instance, …
Monkey1ControlManager = New ControlManager()… add controls …
Monkey123456789101112' conditionLocal rightArrowKeyDown := Lambda:Bool ()Return Keyboard.KeyDown( Key.Right )End' callback (action)Local spriteRotateRight := Lambda ()MySprite.Rotation += 0.05End' add the controlControlManager.Add( "rightArrowKeyDown", rightArrowKeyDown, spriteRotateRight )… and call …
Monkey1ControlManager.OnUpdate()… in the OnRender loop.
If you want to disable the control/s later you just do
Monkey1ControlManager.Disable( "rightArrowKeyDown" )for a specific control or for all
Monkey1ControlManager.DisableAll()and then enable them in the same way.
Here’s a demo with various control examples: https://github.com/anatolbogun/monkey2-utils/blob/master/demos/control_manager_demo/main.monkey2#L61-L121
October 9, 2017 at 3:08 am #11041Very nice, thanks for sharing Anatol.
 - 
		AuthorPosts
 
You must be logged in to reply to this topic.