+1 vote
by (2.9k points)
So I have made a game but I am wondering if there is a way to bind keys to links in sugarcube.

I am not the best a explaining things but I'm trying to allow the player a way to make choices similar to Fallout 4 where you can use the arrow keys or the mouse.

If anyone knows hot to do so please comment.

2 Answers

+1 vote
by (240 points)

I found this solution on the old message board:


Since you're saying "arrow keys and mouse", you might mean more along the lines of an interface where you use the up and down keys to highlight a link and enter to activate it...if that's the case, you can always just use the tab key instead.

+2 votes
by (63.1k points)
edited by

It sounds like you want to control the focus of the links, not the links themselves.  This script will allow you to use the arrow keys to focus on different links, and then you'll be able to fire them with enter or space bar.  Put this in your JavaScript:

setup.optLinks = {
	arr   : [],
	i     : 0,
	first : false

postdisplay['option-link-array'] = function (t) {
	setup.optLinks.arr   = $('#options a').toArray();
	setup.optLinks.i     = 0; // reset iteration
	setup.optLinks.first = false; // reset flag

$(document).on('keyup', function (e) {
	var links = setup.optLinks;
	if (!links.first) {
		if (e.which === 37 ||
			  e.which === 38 ||
			  e.which === 39 ||
			  e.which === 40 ) {
			links.first = true; // set flag
	} else {
		if (e.which === 39 || e.which === 40) {
			if (links.i === links.arr.length - 1) {
				links.i = 0;
			} else {
		} else if (e.which === 37 || e.which === 38) {
			if (links.i === 0) {
				links.i = links.arr.length - 1;
			} else {

You'll probably also want to define styles for the focused links to make things easier to understand for the player.  Here's some example CSS for that:

#options a:focus {
  border: 1px solid #eee;

To use the script, place the links you want the player to navigate using the arrow keys inside an HTML element (a <span> or <div>) with the id 'options'.  For example, using HTML:

<span id='options'>\
<<link 'link3'>><<run UI.alert('Hi');>><</link>>\

Or, using Sugarcube's @@ markup:

<<link 'link3'>><<run UI.alert('Hi');>><</link>>

Then you can use the arrow keys to navigate the links, and press space or enter to activate the links.  You should only include one of these options segments in a given passage.

by (2.9k points)
Thanks this is really helpful, I really appreciate the kindness on this forum.

Have a good day. :)