Sniff is a "Scratch-like" programming language that's designed to help Scratchers move gently from Scratch to more conventional languages. They can start writing programs, without having to learn a new language because Sniff is based on Scratch. They learn a little more about variables, compiling, syntax errors (!), and they can have fun controlling real hardware while they're doing it.

Sunday, 13 September 2015

Joysticks!

We've had a bit of a push on "games" this summer, and we've previously blogged about the Sprite device system we've built. We developed that using just keyboard input, but I thought it would be nice to add joystick support. This turned out to be pretty easy on most of the Sniff platforms - the javascript and Windows versions were the easiest, with Linux only slightly tricky. However Apple really don't want you using joysticks on your Mac, so for now the joystick device doesn't work on OS X.

Using the joystick device is pretty trivial. In fact here's the basic code:

make joystick device
make joyX number
make joyY number
make joyZ number
make joyButton boolean

when start
.forever
..tell joystick to "update"
..if joyButton
...say [joyX]
...say [joyY]
...say [joyZ]
...say ""
..wait 0.1 secs

We only support one button, and it shouldn't make any difference which one you press on the joystick. While it would be possible to expose more buttons we then run into the problem of mapping then, and joysticks and gamepads are just too varied to do that in a simple and consistent way.

We do support a third Z axis if your hardware has one, but most of the time you can just use the joyX and joyY values, which are scaled from -1 to +1.

Depending on your preferred coding style you can either call "update" in the main game loop, so like we did above or break the code so that the joystick is refreshed in a separate script, and then simply use the variables as you need them:

when start
.forever
..tell joystick to "update"
..wait 0.01 secs

when start
.forever
..if joyButton
...say [joyX]
...say [joyY]
...say [joyZ]
...say ""
...wait 0.1 secs

There's no smart device detection plug/unplug tracking, so just make sure your gamepad is plugged in before you start, and don't unplug it during the game.

It should only take a few seconds to modify existing games to use the new controllers.

No comments:

Post a Comment