So, for my 4K game, I want the player to be able to move faster/slower based on how fast one or two keys are pressed repetitively(e.g. J and K, or just J). I don’t really know how to go about doing this. Any suggestions? I don’t absolutely need actual code.
Well, for one, you’d have to use a KeyListener. Make a class that implements a KeyListener.
Basically, every time a key you want to be included is pressed, add for example, 2 to the speed of the velocity in the keyPressed method. In your game logic, decrease the velocity by 1 or 1.5, as long as its greater than 0.
Tell me if this works.
Or get the time diff between key press and key release. (but I prefer Agro’s)
Since this is for a java 4k project, I would suggest that you do not use a key listener explicitly, rather extend applet and enable key events and capture thoese events. e.g.
public class a extends Applet implements Runnable {
// keys
private boolean[] a= new boolean[1]; // can be made larger and used by your game for storage.
public void start() {
enableEvents(8);
new Thread(this).start();
}
public run()
{
// your game here
// handle key press
switch (this.a[0])
{
case KEY_CODE:
....
}
// and more game here
}
public final boolean handleEvent(Event paramEvent)
{
switch (paramEvent.id)
{
case 403: // key press
this.a[0] = paramEvent.key;
}
return false;
}
}
Well, it would be better not to introduce a keystate system, because he’s trying to get how fast the keypresses are pressed repetitvely, not how long they’re pressed. But yeah, for the 4K game, just handle the keypresses inside that handleEvent thing
@Agro -
your system works, but it can be bypassed just by pressing down and holding the key. Any good (small) ways to prevent this?