Any way to bind keys to make a rhythm game?

Twine Version: 2.7.1

I want the game that I’m trying to make to have a battle system kind of based off of the gameplay in Friday Night Funkin’, where users would have to press certain keys (up, down, left, right arrows) at a certain time to battle their enemies.

I was wondering if there was a way to do this using Mousetrap (Mousetrap - Keyboard shortcuts in Javascript)

I know literally no javascript (I have dabbled in a bit of python though), so please keep in mind that I’m a complete beginner.

1 Like

There is a way to do this in Harlowe, but you might find SugarCube or Snowman much easier. Harlowe prevents authors from accessing story data or changing variables using JavaScript during run-time.

Setting up Mousetrap in Harlowe

To begin in Harlowe, you would want to load the remote JavaScript file using getScript() and then setup the bindings you want using Mousetrap.

One approach to this would be to use the following example (to be copied into the Story JavaScript window):

// Harlowe gives access to jQuery.
// (When loaded, the global value $ 
//  will contain its properties and methods.)

// We use getScript() to load a remote JavaScript file.
$.getScript( 'https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js?a4098' )
  .done(function( script, textStatus ) {
  	// If everything works, we call another function.
    bindKeys();
  })
  .fail(function( jqxhr, settings, exception ) {
    console.log("Error: " + exception);
});

// Once the remote JS is loaded, this will be called.
function bindKeys() {
	Mousetrap.bind('4', function() { console.log("Pressed 4"); });
	Mousetrap.bind('2', function() { console.log("Pressed 2"); });
}

In the above code, pressing 2 or 4 on the keyboard would show the message “Pressed 4” or “Pressed 2” to the player in the Console.

Timing in JavaScript

This is complicated. The most precise way to get timing from JavaScript in the browser is using requestAnimationFrame(). This runs at the refresh rate of the monitor. Generally, but not always at 60 frames-per-second.

Technically, it should be possible to use requestAnimationFrame() to setup a timer and then test if the keypress happened within a smaller window.

HaxeFlixel and Phaser

It looks like Friday Night Funkin’ is written in HaxeFlixel. Rhythm and music-based mechanics (what’s called quantization in music theory) are difficult to extremely difficult to implement in text-based tools like Twine. It is potentially possible, but hard and often requires a higher degree of technical knowledge.

Something to consider is a game engine like Phaser, which is made to run in web browsers. It would require knowing and using much more JavaScript, but could be easier than working around technical limitations of Twine and story formats like Harlowe.

2 Likes

Thank you! I decided to add a link to a Scratch project instead.