Log In  


I want my web export to support mobile. But if you're like me, you might find the API for controlling touch button inputs from a web page a bit esoteric, and not super easy to read/write. Why not write a tiny API wrapper that makes this much easier?

If you have a page that looks like this:

<!-- ... cart stuff -->
<button id="left"> < </button>
<button id="right"> > </button>
<button id="up"> /\ </button>
<button id="down"> \/ </button>
<button id="o"> O </button>
<button id="x"> X </button>
<! -- ... -->

Include this in your page...

(function() {
  var __btns = {};

  function update_btns(playerIndex) {
    pico8_buttons[playerIndex] =
      Object.keys(__btns[playerIndex]).reduce(function(val, btn) {
        return val | (__btns[playerIndex][btn] ? Math.pow(2, btn) : 0);
      }, 0);
  }

  function registerP8Btn(domElement, btnIndex, playerIndex) {
    playerIndex = playerIndex || 0;
    window.pico8_buttons = window.pico8_buttons || [];
    pico8_buttons[playerIndex] = pico8_buttons[playerIndex] || 0;
    __btns[playerIndex] = __btns[playerIndex] || {};
    domElement.addEventListener('touchstart', function() {
      __btns[playerIndex][btnIndex] = true;
      update_btns(playerIndex);
    });
    domElement.addEventListener('touchend', function() {
      __btns[playerIndex][btnIndex] = false;
      update_btns(playerIndex);
    });
  }

  window.registerP8Btn = registerP8Btn;
})();

Then later you can register buttons like this:

registerP8Btn(document.getElementById('left'), 0);
registerP8Btn(document.getElementById('right'), 1);
registerP8Btn(document.getElementById('up'), 2);
registerP8Btn(document.getElementById('down'), 3);
registerP8Btn(document.getElementById('o'), 4);
registerP8Btn(document.getElementById('x'), 5);

Are you trying to support multiple players? Then you can do:

registerP8Btn(document.getElementById('x-P1'), 5, 0 /* player 1 */);
registerP8Btn(document.getElementById('x-P2'), 5, 1 /* player 2 */);

That's it!

1


This is now on GitHub, by the way: https://github.com/benwiley4000/tiny-pico8-touch-ui

And there's a live example here: https://benwiley4000.github.io/tiny-pico8-touch-ui/



[Please log in to post a comment]