gpt4 book ai didi

java - 如何在 libgdx 中删除数组中的多个元素

转载 作者:搜寻专家 更新时间:2023-11-01 03:17:39 25 4
gpt4 key购买 nike

我正在使用 libgdx,我有一个由我创建的球类数组列表。我试图一次删除具有相同颜色的球。由于删除元素后数组中元素的位置发生变化,这会留下一些未删除的元素。所以我正在使用快照阵列 https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/SnapshotArray.html

根据文档,如果我们在 array.begin() 和 array.end() 方法之间编写循环,数组大小和索引将不会改变。所以我声明了快照数组

SnapshotArray<Ball> balls;

而我的删除方法是

 private void removeVillianGroups(int color){
Ball[] ball=balls.begin();
for(int i=0;i<balls.size;i++){

if(balls.get(i).getColor()==color){
ball.removeValue(balls[i],true);

}
}
balls.end();
}

我在转换时遇到错误

 java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lcom.mygames.haloween.Entity.Ball;

在上面这一行

Ball[] ball=balls.begin();

所以在这里我创建了我的数组,基本上我将我的屏幕宽度分成六等份,有 6 列球

 private void createVillians() {

for (int color=0;color<4;color++)//create 4 diffirent color balls in 4 rows
for(int i=0;i<6;i++)//each row contan 6 same color balls
{
balls.add(new Ball(viewport,new Vector2(i*viewport.getWorldWidth()/6,
0-c*viewport.getWorldWidth()/6),color));

//Ball class just draw balls according their color between 0 to 3.
}
}

this is what generate by this array

最佳答案

你不能只使用常规的 ArrayList 并向后迭代吗:

ArrayList<Ball> balls;

private void removeVillianGroups(int color){
for(int i = balls.size() - 1; i >= 0; i--){
if(balls.get(i).getColor()==color){
balls.remove(i);
}
}
}

关于java - 如何在 libgdx 中删除数组中的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com