Gregg1989
Gregg1989

Reputation: 695

2d array squares initialization and selection

For code optimization purposes, I want to create a 2d array that contains 40 equal squares (10x10px). Each square represents 1\40 of the displayed window (400x400px).

I populate the 2d array with the standard double for-loop methodology.

    int col = 40;
    int row = 40;
    int boxPosition = 0; //Position of the box (coordinates)
    Integer[][] boxes = new Integer[40][40];

    for (int i = 0; i < col; i++) {
        for (int j = 0; j < row; j++) {
            boxes[i][j] = boxPosition;
            boxPosition += 10; //Creates a 10px box.
        }
        boxPosition = 0; //Resets box size for next column
    }

There are several circles in this program. We have a ship(circle) that fires missiles(circles) toward enemies(circles).

I want to run collision detection ONLY when there is a bullet + an enemy in one of the squares. This will greatly optimize the code.

The question is... how do I create these squares off of a 2d array? How do I select each square? How do I test if the missiles and the enemies are inside the same square?

Code examples are GREATLY appreicated.

Thanks.

Upvotes: 1

Views: 657

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42176

I'm not sure what you're doing with the 2D array or why it contains Integers or why it contains an increasing size in each column, but the general way to do grid-based collision is to have a 2D array of GameObjects. A GameObject in your case could be a Ship, a Missile, or an Enemy.

When one of your GameObjects wants to move, you simply check the 2D array of GameObjects to see what is already in the square you want to move to. If it's empty, you can do the move. If it's not empty, you've got a collision.

Upvotes: 2

Related Questions