我正在打一场格斗游戏,我希望玩家的动作能够定时,这样你就不会发送攻击密钥并轻松获胜。
这是我做键盘和延迟的地方。它确实第一次延迟,但随后延迟缓慢减少并最终为0并让你垃圾密钥。正如你所看到的,我已经做了很多事情来尝试阻止密钥在延迟等方面注册。
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (isAction == false) {
if (key == KeyEvent.VK_LEFT) {
dx = -1;
if (nHeroX < -10) {
dx = 0;
}
isRight = false;
isMoving = true;
} else if (key == KeyEvent.VK_RIGHT) {
dx = 1;
if (nHeroX > 1200) {
dx = 0;
}
isRight = true;
isMoving = true;
} else if (key == KeyEvent.VK_C) {
dx = 0;
isAction = true;
isMoving = false;
isBlock = true;
nImage = 1;
} else if (key == KeyEvent.VK_X) {
dx = 0;
isAction = true;
isMoving = false;
isWeak = true;
nImage = 2;
} else if (key == KeyEvent.VK_Z) {
dx = 0;
isAction = true;
isMoving = false;
isStrong = true;
nImage = 3;
} else if (key == KeyEvent.VK_P) {
if (!pause) {
pause = true;
} else if (pause) {
pause = false;
}
}
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT && !isAction) {
dx = 0;
isMoving = false;
nState = nImage = 1;
} else if (key == KeyEvent.VK_C && !isWeak && !isStrong) {
delayTask = new DelayTask();
tmrDelay.schedule(delayTask, 0, 500);
} else if (key == KeyEvent.VK_X && !isBlock && !isStrong) {
z = new DelayTask();
tmrDelay.schedule(z, 0, 450);
} else if (key == KeyEvent.VK_Z && !isBlock && !isWeak) {
x = new DelayTask();
tmrDelay.schedule(x, 0, 1200);
}
nImgNum = (int) (Math.random() * 6 + 1);
nDelay = 0;
}
//http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-tmrDelay-java.html
class DelayTask extends TimerTask {
public int nTimes = 0;
@Override
public void run() {
nTimes++;
if (nTimes == 2) {
isAction = isBlock = isStrong = isWeak = false;
nState = nImage = 1;
}
}
}
有人可以解释为什么我的延迟搞砸了吗?谢谢。
此代码:
private class Keys extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
hero.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
hero.keyReleased(e);
if (hero.getPause()) {
repaint();
}
}
}
答案 0 :(得分:2)
最简单的方法就是记住最后一次。
所以:
private long lastTime = 0;
void doAction() {
long timeNow = System.currentTimeMillis()
if (lastTime + MIN_DELAY < timeNow) {
return;
}
lastTime = timeNow;
// Do action
}
所有带有计时器等的东西只是从一个比你需要的更复杂的架构接近它。