Sunday, May 27, 2012

Clojure macro for LibGDX input polling

A very simple macro:
(defmacro when-pressed
  ([key form]
  `(when (.isKeyPressed Gdx/input (. com.badlogic.gdx.Input$Keys ~key))
     ~form))
  ([key form & rest]
     `(do
        (when-pressed ~key ~form)
        (when-pressed ~@rest))))
example usage:
 (when-pressed LEFT  (do-something)
               RIGHT (do-something-different)
               SPACE ( ... )
               ...)
expands to:
user=> (pprint (macroexpand-1 '(when-pressed LEFT (do-something))))
(clojure.core/when
 (.isKeyPressed Gdx/input (. com.badlogic.gdx.Input$Keys LEFT))
 (do-something))
nil
or
user=> (pprint (macroexpand-1 '(when-pressed LEFT (do-something)
                                             RIGHT (do-something-else))))
(do
 (when-pressed LEFT (do-something))
 (when-pressed RIGHT (do-something-else)))
nil

2 comments:

  1. Great stuff. Are you still working with LibGDX and Clojure?

    ReplyDelete
  2. Thanks, Thomas.
    Yeah, I'm still into Clojure/LibGDX, see here:

    https://github.com/thomas-villagers/clojurelibgdx
    and
    https://play.google.com/store/apps/details?id=com.friendlyvillagers.ballz

    :-)

    ReplyDelete