我正在开发一个游戏,其中敌方AI会从预设的一组动作中随机选择一个动作执行。我已经实现了随机选择动作的功能,但这意味着游戏每次更新时都会执行一个新动作。相反,我希望AI每隔1秒执行一次动作。例如,该如何实现呢?这是我的随机动作代码:
public class RandomAction implements Controller { Action action = new Action(); @Override public Action action() { Random rand = new Random(); action.shoot = rand.nextBoolean(); action.thrust = rand.nextInt(2); action.turn = rand.nextInt(3) - 1; return action; }}
回答:
我猜你的应用会反复调用不同对象的action()
方法,而你希望RandomAction的行为每秒只改变一次,而不是每次调用都改变。你可以这样做:
public class RandomAction implements Controller { Action action = new Action(); Random rand = new Random(); long updatedAt; public RandomAction() { updateAction(); // 进行首次初始化 } @Override public Action action() { if (System.currentTimeMillis() - updatedAt > 1000) { updateAction(); } return action; } private void updateAction() { action.shoot = rand.nextBoolean(); action.thrust = rand.nextInt(2); action.turn = rand.nextInt(3) - 1; updatedAt = System.currentTimeMillis(); }}
如你所见,只有在距离上次更新过去了1秒后,动作才会被随机值更新。更新时间变量会在更新后设置为当前时间。