Search code examples
javalistarraylisttilechunks

How do i get a vector2 from a list index?


Let's say I have an ArrayList with 32 objects in it, forming a 2d TileMap of 4x8.

And I want to get the position of 12th object. how do i get the vector2? And remember, objects doesn't have a vector2, i want to get positions from the index.


Solution

  • If what you are asking is "how do I calculate the position of eg. the 12th object in a 4x8 map" then the algorithm is something like this:

    (I assume vector2 is something that holds int, int as x, y positions and 0, 0 is the origin and we count tiles starting on 1):

    public class Test {
    
        private static final int xDimension = 4;
    
        public static void main(String[] args) {
            System.out.println(getPosition(1));
            System.out.println(getPosition(3));
            System.out.println(getPosition(4));
            System.out.println(getPosition(5));
            System.out.println(getPosition(12));
            System.out.println(getPosition(32));
        }
    
        public static Vector2 getPosition(int n) {
            int y = (n - 1) / xDimension;
            int x = (n - 1) % xDimension;
            return new Vector2(x, y);
        }
    
        public static class Vector2 {
            int x, y;
    
            public Vector2(int x, int y) {
                this.x = x;
                this.y = y;
            }
    
            @Override
            public String toString() {
                return "(" + x + ", " + y + ")";
            }
        }
    }
    

    Output:

    (0, 0)
    (2, 0)
    (3, 0)
    (0, 1)
    (3, 2)
    (3, 7)