Held Inputs - UQcsse3200/2024-studio-1 GitHub Wiki
Introduction
LibGDX doesn't have any built in method for determining if a keyboard button is being held down, as such this feature needed to be implemented primarily for using weapons
Implementation
Determining whether a button is being held can be found by keeping track of when a button has been pressed and checking if it has been released since then, which is why this feature was implemented in the KeyboardPlayerInputComponent
class. Continuously sending inputs was achieved using the Timer
and TimerTask
classes, where each method is allocated a Timer
which is given a unique TimerTask
when the keydown input is received and has it cancelled when the keyup input is received. The task repeatedly calls the method every few milliseconds, as determined by the inputDelay
constant (10ms), until it is cancelled when the button is released.
Example
Attacking with the melee weapon while the button is held
# Adding the method to the 'keyDown' actionMap
actionMap.put(MELEE, (i) -> holdMelee());
# Adding the method to the 'keyUp' actionMap
actionMap.put(MELEE, (i) -> unMelee());
private final Timer holdMelee = new Timer();
private RepeatMelee taskMelee;
private static final int inputDelay = 15;
private class RepeatMelee extends TimerTask{
# Task calls the 'melee' function when run
@Override
public void run() {
melee();
}
}
private boolean holdMelee(){
# Cancels old task if it somehow exists
if (this.taskMelee != null) {
this.taskMelee.cancel();
}
this.taskMelee = new RepeatMelee();
# Schedules the task to run repeatedly
this.holdMelee.scheduleAtFixedRate(taskMelee, inputDelay, inputDelay);
return true;
}
private boolean unMelee() {
# Cancels the task when the button is released
if (this.taskMelee != null) {
this.taskMelee.cancel();
}
return true;
}
Ranged weapon
Each ranged weapon can only fire in a single direction a time, as such each of the directional shoot buttons have only 1 timer between them with the task being updated on button press. The unShoot method is also modified from the example to only cancel if the task matches the button being unpressed.
Melee weapon
Follows the example code shown above
Other implementations
Player movement uses a different system involving addition/subtraction of vectors on keyDown/keyUp inputs.
No other current implementations (contact Jordamnmn for requests)