Created
June 26, 2014 10:49
-
-
Save eush77/9ad5343c67b0aef9f0b2 to your computer and use it in GitHub Desktop.
Helper function for Bit's Quest (bitsquest.bitbucket.org) that launches callbacks in a sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var phase = 0; | |
var bounce = (function () { | |
var nextPhaseToAssign = 0; | |
var opposite = { | |
top: 'bottom', | |
left: 'right', | |
bottom: 'top', | |
right: 'left' | |
}; | |
return function assign(direction) { | |
if (!direction) { | |
return; | |
} | |
var customHandler; | |
if (Array.isArray(direction)) { | |
customHandler = direction[1]; | |
direction = direction[0]; | |
} | |
var myPhase = nextPhaseToAssign++; | |
this.on('sensor:' + direction, function (contact) { | |
if (contact && phase == myPhase) { | |
if (customHandler) { | |
customHandler.call(this); | |
} | |
else { | |
// Default handler. | |
this.thrusters[opposite[direction]](false); | |
this.thrusters[direction](true); | |
} | |
phase += 1; | |
} | |
}); | |
assign.apply(this, [].slice.call(arguments, 1)); | |
}.bind(this); | |
}.call(this)); | |
// Example: solution for #5 "Going Up" | |
// http://bitsquest.bitbucket.org/index.html#5 | |
this.on('start', function () { | |
this.thrusters.left(true); | |
this.thrusters.top(true); | |
}); | |
bounce('bottom', | |
'right', | |
'top', | |
'left', | |
'bottom', | |
'right', | |
'top', | |
['bottom', function () { | |
this.thrusters.right(false); | |
this.thrusters.top(false); | |
this.thrusters.left(true); | |
this.thrusters.bottom(true); | |
}] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment