The lib I'm using is processing library. I'm currently making a game and I need to remove items from list every 2 seconds after adding it (item will be add by Keypressed SPACE). I've tried this:
List<String> items = new ArrayList<>();
boolean timeStarted;
int timeDuration = 2000;
int startTime = 0;
if (timeStarted) {
int currentDuration = millis() - startTime;
if (currentDuration >= timeDuration) {
items.remove(0);
startTime = millis();
timeStarted = false;
}
}
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
if (keycode == 32) { // SPACE
startTime = millis();
timeStarted = true;
items.add("new item");
}
But this only remove the first item in the list, and it will stuck if I press the SPACE too fast (add too many items at the same time).
Could anyone help me or give me some idea how to deal with this? Thanks in advance!
I personally wouldn't mix and match threading and Processing together.
If you're using Processing, and are doing this for a game (thus probably dont require milisecond precision), why not just use the framerate as a time measurement? Your Processing programs are always supposed to run at a set frameRate
(unless you have some performance issues). You also won't see anything happen untill the frame where the action happens has been drawn anyway, so it doesn't really matter if your action completed halfway between a frame, your end user won't see the difference.
The default frameRate
in Processing is 30fps. You can set a custom rate using the frameRate()
function (docs). frameCount
returns the number of frames drawn (0 on the first frame).
Thus, you can do something like the following pseudocode
int removeItemCheckpoint;
int removeItemDuration;
void setup()
{
// 30 frames per second
frameRate(30);
// window is two seconds, so this duration will last two times the frameRate
removeItemDuration = frameRate * 2;
}
void draw()
{
if (some input)
{
// set checkpoint to current frame count + the duration
removeItemCheckpoint = frameCount + removeItemDuration;
}
// if current frame count is larger than the checkpoint, perform action
if (frameCount > removeItemCheckpoint)
{
// set checkpoint to pseudo infinity
removeItemCheckpoint = Integer.MAX_VALUE;
// remove item here
}
}
If you want to handle this for multiple objects at a time, you could create something like a list of created list index/checkpoint pairs and loop over those instead.
List<Pair<int, int>> toBeRemoved = new List<Pair<int, int>>();
// add a new pair
toBeRemoved.add(new Pair(itemIndex, frameCount + removeItemDuration));
// loop over the list
foreach (Pair<int, int> item in toBeRemoved)
{
if (frameCount > item.getKey())
{
itemList.remove(item.getValue());
}
}