我有这种动画,我每秒在屏幕上产生并每秒移除它。问题出在我的计算上。我使用下面的条件每1.26秒产生一次:
if (TimeUtils.nanoTime() - longSpawn > 1260000000) spawnAnt();
这段代码要删除:
if (TimeUtils.nanoTime() - longRemoveAnt > 1000000000) IteratorCircle.remove();
问题是longRemoveAnt不能高于或等于longSpawn,否则不会删除。但更重要的是,我应该如何计算它以便动画完全运行,然后将被移除并且在它之后将再次生成?
动画代码:
TextureRegion[] antArr = {a, b, c, d, e, f, g, h, i};
animAnt = new Animation(0.07f, antArr);
animAnt.setPlayMode(Animation.PlayMode.LOOP_PINGPONG);
答案 0 :(得分:0)
我认为你需要跟踪每一个的经过时间(或者在我的例子中,倒数时间)。如果您不需要纳秒的精度,可以使用Gdx.graphics.getDeltaTime()
,但是您可以像这样跟踪自己经过的纳米时间。
从您的问题中不清楚您正在做什么,所以您可能需要修改下面的数学运算,让它按照您想要的方式运行。我每隔1.26秒生成一个动画,每1.0秒删除一个动画,但显然如果你移除它们的速度比产生它们的速度快,那么你的问题暗示你正在做这个问题。
//member variables
static final long SPAWN_TIME_NANOS = 1260000000;
static final long REMOVE_TIME_NANOS = 1000000000;
long timeToNextSpawn = SPAWN_TIME_NANOS;
long timeToRemoveAnt = SPAWN_TIME_NANOS + REMOVE_TIME_NANOS;
long previousTimeNanos= -1;
void spawnAnt(){
Ant ant = Pools.obtain(Ant.class);
ant.position.set(...); //however you are doing this.
ant.age = 0;
}
//In render():
long currentTimeNanos = TimeUtils.nanoTime();
long deltaNanos = (previousNanoTime==-1) ? 0 : currentTimeNanos - previousTimeNanos;
previousTimeNanos = currentTimeNanos;
timeToNextSpawn -= deltaNanos;
while (timeToNextSpawn <= 0){ //using while instead of if in case of long frame
spawnAnt();
timeToNextSpawn += SPAWN_TIME_NANOS;
}
timeToRemoveAnt -= deltaNanos;
while (timeToRemoveAnt <= 0){
IteratorCircle.remove();
timeToRemoveAnt += REMOVE_TIME_NANOS;
}
我上面的回答是基于对你的问题的字面解读,但如果你有一个可以跟踪自己年龄的“Ant”类,那么在我看来它更简单,更不容易出错,如下所示:
public class Ant {
float age;
Vector2 position = new Vector2();
}
//member variables
static final float SPAWN_TIME = 1.26f;
static final float REMOVE_TIME = 1.0f;
float timeToNextSpawn = SPAWN_TIME;
LinkedList<Ant> ants = new LinkedList<Ant>(); //LinkedList makes it low cost to remove oldest
void spawnAnt(){
Ant ant = Pools.obtain(Ant.class); //Use pooling to reduce GC activity
ant.age = 0;
ant.position.set(.......);//however you do this
ants.add(ant);
}
void removeOldestAnt(){
Ant ant = ants.removeFirst();
Pools.free(ant);
}
//In render():
float deltaTime = Gdx.graphics.getDeltaTime();
for (Ant ant : ants) {
ant.age += deltaTime;
}
while (ants.size()>0 && ants.getFirst().age >= REMOVE_TIME)
removeOldestAnt(); //Assumes ants are ordered by age, which they should be in this code
timeToNextSpawn -= deltaTime;
while (timeToNextSpawn <= 0){
spawnAnt();
timeToNextSpawn += SPAWN_TIME;
}