This is a read-only archive of the Framer Community on Facebook.

What is Framer? Join the Community
Return to index
Jacek Stryk
Posted May 02 - Read on Facebook

Trying to wrap my head around how to best manage states for a prototype controlled by a keyboard.

So far I've been trying to have one main control loop i.e.

window.onkeydown = (eventKeydown) -> #WATCH KEYDOWN
switch eventKeydown.keyCode

when 39 #right arrow
print "right arrow"
when 37 #left arrow
print "left arrow"
when 38 #up arrow
print "up arrow"
when 40 #down arrow
print "down arrow"

but managing it becomes somewhat complex when I have to track state of of a variety layers which have different states and behave differently do the same keyboard input based on their states etc.

Ideally I'd like layers to listen to the keyboard events and respond to them according with behavior defined on the layer level (not somewhere in the main loop)

Example (made up code)

layerA = new someLayer
if keyCode is 39 then right()
if keyCode is 37 then left()

layerB = new someOtherLayer
if keyCode is 40 then down()
if keyCode is 38 then up()


I can express this conceptually - can someone help me to put this into the code or advise on best practices for building keyboard controlled, multi-state prototypes?

Thanks a lot!


Jacek Stryk

I tried to bind a onkeydown event to a layer but to no avail, i.e.

layerA.onkeydown = (eventKeydown) ->
switch eventKeydown.keyCode
when 40 #down arrow
print "down arrow on layerA

layerB.addListener "keydown", (event) ->
keyCode = event.which
print keyCode

Brian Williams

create a class with delegates in it, assign those delegates to the functions that are relevent on each instance then switch out the instance of the object that is wired up to your event handlers.

Umm or write a method to assign the functions to the event handlers then pass it the instance.

This is where an understanding of programming to interfaces would help.

Brian Williams

Either that or you could have a dictionary of keycode:function()

and just iterate over it/ test for keys in the keydown event and if they exist call the function.

Key lookup is fast and this should be fine as I am pretty sure the event arguments can only contain a single key per event.

There are lots of ways to do it.

Jonas Treub

I added arrow key support with the VRComponent. You can check the source. If you like I can also make a more simple example

Read the entire post on Facebook