I am making a game in Kotlin.Using Libgdx and Box2d
1.function creates bodies via Box2d and adds these bodies in bodyArrayList:ArrayList
2.function creates textures and adds these textures in textureArrayList
3.function is matching items of bodyArrayList with items of textureArrayList. The function has for loop.
4.function is removing bodies when crash a wall.
5.function is removing textures when crash a wall.
All functions are working in update() method. All these are working perfectly. However because I cannot remove items of te ArrayLists while for loop works on these ArrayLists, items of ArrayList is increasing and the game is starting slowing downn 1 hour later. The ArrayLists' size is going up as you guess. If I try to remove items of ArrayLists I am taking exceptions in matching() function as you guess.
My question is how can I remove these items from ArrayLists while "for loop" is working in a safe manner.
1.function creates bodies
var body = makeBody()
bodyArray.add(body)
2.function creates textures
var texture=makeTexture()
textureArray.add(texture)
3.function is matching items of bodyArrayList with items of textureArrayList
for (i in 0..bodyArray.size-1) {
textureArray[i].setPosition(bodyArray[i].position.x, bodyArray[i].position.y)
}
4.funtion is removing bodies when crash a wall.
override fun beginContact(contact: Contact?) {
val userDataA = contact!!.fixtureA.userData.toString()
val userDataB = contact.fixtureB.userData.toString()
if ((userDataA == "ball" && userDataB == "wall")){
val bodyA=contact.fixtureA.body
Gdx.app.postRunnable(Runnable(){
run(){
world.destroyBody(bodyA) } })
}
5.function is removing textures when crash a wall.
for (texture: MyTextures in MyTextures.getList(Ball::class.java.canonicalName)) {
if (ball.overlaps(wall)) {
ball.remove() }
}