Search code examples
javaarraysfor-looplibgdx

For-loop gives only one value when iterating through an array of Vectors (libGDX)


I'm just a beginner, so here's probably some small mistake which I can recognize but yeah... I'm using libGDX library and here's code of my method:

public Vector2[] initCollisionStart() {

    int i = 0;

    for (int row = 0; row < currentMapHeightTiles; row++) {
        for (int col = 0; col < 9; col++) {
            if (currentMap[row][col] == 4) {
                i++;
            } else if (currentMap[row][col] == 3) {
                i++;
            }
        }
    }

    Gdx.app.log("initCollisionStart", "works");

    Vector2[] collisionStart = new Vector2[i];

    for (int row = 0; row < currentMapHeightTiles; row++) {
        for (int col = 0; col < 9; col++) {
            if (currentMap[row][col] == 4) {
                position.x = col * 40;
                position.y = row * 40;
                collisionStart[i - 1] = position;
                System.out.println("CollisionStart[" + i + "] = " + collisionStart[i - 1]);
                i--;
            } else if (currentMap[row][col] == 3) {
                position.x = col * 40;
                position.y = row * 40;
                collisionStart[i - 1] = position;
                System.out.println("CollisionStart[" + i + "] = " + collisionStart[i - 1]);
                i--;
            }
        }
    }

    collisionInitialized = true;
    System.out.print("\n");
    for (int z = 0; z < collisionStart.length; z++) {
        System.out.println("CollisionStart[" + z + "] = " + collisionStart[z]);
    }
    return collisionStart;
}

and my output looks like that:

initCollisionStart: works
CollisionStart[7] = [40.0:5760.0]
CollisionStart[6] = [80.0:5760.0]
CollisionStart[5] = [120.0:5760.0]
CollisionStart[4] = [160.0:5760.0]
CollisionStart[3] = [200.0:5760.0]
CollisionStart[2] = [240.0:5760.0]
CollisionStart[1] = [280.0:5760.0]

CollisionStart[0] = [280.0:5760.0]
CollisionStart[1] = [280.0:5760.0]
CollisionStart[2] = [280.0:5760.0]
CollisionStart[3] = [280.0:5760.0]
CollisionStart[4] = [280.0:5760.0]
CollisionStart[5] = [280.0:5760.0]
CollisionStart[6] = [280.0:5760.0]

and here's my question. Why does EVERY value of this collisionStart array equals [280.0:5760.0] when I use it outside of this double for-loop? I expect it to return same value which was initialized earlier. Is there a way to do this?

Thanks in advance for any help <3


Solution

  • In your second double for loop

     collisionStart[i - 1] = position;
    

    should be changed to

    collisionStart[i - 1] = new Vector2(...);
    

    I am not sure where you are getting position from.
    But I assume it is some Vector2 that you assign to every element of the Vector2 array.
    The entire array is pointing to the same object, and hence your output outside the for loop.