Sunday, May 11, 2014

Unrealscript: repeatedly calling a function when button is down

I use the dpad on the xbox controller to increase/decrease max jump height.

There are 20 height levels. Making the player press up/down 20 times is not a good option. I needed to fire off the increase/decrease function as long as the button is held down.

I thought this was going to be very painful. It turned out to be really simple via timers.

The code I found on the web recommend 1 function that toggled on/off on press/release. Relying a pressed/released call every time is dangerous. I built a stop into the jump height logic itself in addition to reacting to the press/release to stop an out-of-control timer.

Here is the UDKInput.ini mapping:

Bindings=(Name="XboxTypeS_DPad_Up",Command="IncreaseJumpHeightViaButtonPressed | onrelease IncreaseJumpHeightViaButtonReleased")
Bindings=(Name="XboxTypeS_DPad_Down",Command="DecreaseJumpHeightViaButtonPressed | onrelease DecreaseJumpHeightViaButtonReleased")

Here is the Unrealscript called via the UDKInput.ini:

exec function IncreaseJumpHeightViaButtonPressed() {
IncreaseJumpHeight();
SetTimer(0.1, true, 'IncreaseJumpHeight');
}
exec function IncreaseJumpHeightViaButtonReleased() {
ClearTimer('IncreaseJumpHeight');
}

exec function DecreaseJumpHeightViaButtonPressed() {
DecreaseJumpHeight();
SetTimer(0.1, true, 'DecreaseJumpHeight');
}
exec function DecreaseJumpHeightViaButtonReleased() {
ClearTimer('DecreaseJumpHeight');
}

Here are the "private" methods called via timer:

exec function IncreaseJumpHeight() {

// do work here...

if (jumpLevel < maxLevel) {
jumpLevel++;
UpdateJumpHeight();
PlayJumpHeightSettingSound();
}
else {
// This prevents a runaway situation
ClearTimer('IncreaseJumpHeight');
}
}

exec function DecreaseJumpHeight() {

// do work here...

if (jumpLevel > 0) {
jumpLevel--;
UpdateJumpHeight();
PlayJumpHeightSettingSound();
}
else {
// This prevents a runaway situation
ClearTimer('DecreaseJumpHeight');
}
}

No comments:

Post a Comment