Skip to content

Instantly share code, notes, and snippets.

@boxmein
Last active December 18, 2015 05:09
Show Gist options
  • Save boxmein/5730768 to your computer and use it in GitHub Desktop.
Save boxmein/5730768 to your computer and use it in GitHub Desktop.
An element for the powder toy that senses key presses and dishes out sparks accordingly.
--VER 1.1 UPDATE http://pastebin.com/raw.php?i=8Zuy6iB7
-- Keyboard sensor element
-- As per request by thread: http://tpt.io/:17012
-- Set TMP to the key code(!) to enable
-- set TMP2 (optional) to the modifier code to set modifiers
-- Use DEBUG to see the values before setting them
-- by boxmein with tremendous help from cracker64 and jacob1
local el = elements.allocate("boxmein", "ksns")
local lastkeyn = 0
local lastmod = 0
local pressing = false
local DEBUG = true
local typ = ""
function update (index, partx, party, surround_space, nt)
local tmp = tpt.get_property("tmp", index)
local tmp2 = tpt.get_property("tmp2", index)
if pressing then
-- allow tmp2 to set key modifications (for the sake of shift, ctrl, etc)
if tmp2 > 0 and lastmod ~= tmp2 then return 0 end
if tmp == lastkeyn then
-- sparkle sparkle bitches
local t = {sim.partNeighbours(partx, party, 2)}
-- why the fork would t be nil with particles nearby ;_;
if t == nil then return 0 end
for _, v in ipairs(t) do
if bit.band(elements.property(tpt.get_property("type", v),"Properties"),32) == 32 then
local rx, ry = sim.partPosition(v)
tpt.create(rx, ry, 15) -- SPRK
end
end
end
end
end
function key (keys, keyn, mod, evt)
lastmod = mod
if evt == 1 then
-- pressed
lastkeyn = keyn
pressing = true
elseif evt == 2 then
-- released
lastkeyn = keyn
pressing = false
end
end
elements.element(el, elements.element(elements.DEFAULT_PT_DMND))
elements.property(el, "Name", "KSNS")
elements.property(el, "Colour", "0xDEADBEEF")
elements.property(el, "Description", "Keyboard Sensor. Set tmp to key code, (tmp2 to modifier code - optional) to use.")
elements.property(el, "MenuSection", SC_SENSOR)
tpt.register_keypress(key)
tpt.element_func(update, el)
-- # ====================================================================== # --
-- # Debugging
if DEBUG then
-- for the sake of debug only, some might find it of use
function getmodtext(lastmod)
modtext = ""
if lastmod - 256 > 0 then
modtext = modtext .. "ALT "
lastmod = lastmod-256
end
if lastmod - 64 > 0 then
modtext = modtext .. "CTRL "
lastmod = lastmod-64
end
if lastmod - 1 > 0 then
modtext = modtext .. "SHIFT "
lastmod = lastmod-1
end
return modtext
end
function debuglog ()
tpt.drawtext(20, 50,
"KSNS Debug: " ..
"\nkeycode: " .. lastkeyn ..
"\nmod: " .. lastmod .. " / " .. getmodtext(lastmod) ..
"\npressing: " .. tostring(pressing))
end
tpt.register_step(debuglog)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment