I’m trying to develop a falling sand game simulation with C++ and SFML, but i’m having a problem with a function that is acessing the matrix that represents the cell blocks from the game, here i have the Grid class:
#define NUM_GRID 200
class Grid
{
private:
Element* grid[NUM_GRID][NUM_GRID + 1];
std::array<std::array<int, NUM_GRID>, NUM_GRID + 1> privategrid;
public:
Grid();
~Grid();
int** get_privategrid();
void execute();
void place(int id, sf::Vector2i position);
void draw(Graphic_Manager* pGM);
void checkBelow(sf::Vector2i pos_grid);
};
privategrid represents the array of the last frame, and grid represents the array of the frame that is going to be drawn, in the execute() function, i call the update() function from the elements from the element grid if they are not empty,
void Grid::execute()
{
for(int i = 0; i < NUM_GRID; i++)
{
for(int j = 0; j < NUM_GRID; j++)
{
if(privategrid[i][j] == 1)
{
grid[i][j]->update(sf::Vector2i(i, j));
}
}
}
}
each element has a pointer to the Grid that is declared in a “World” class, where the game loop resides, and the update function simply calls the checkBelow() function of the grid, but there is the problem, everytime i try to access any matrix inside the checkBelow(), the element one or the int one, it crashes,
void Grid::checkBelow(sf::Vector2i pos_grid)
{
int i = pos_grid.x;
int j = pos_grid.y;
std::cout << "tste: " << privategrid[100][100] << std::endl;
//If block below is empty, continue downwards
if(privategrid[i][j + 1] == 0 && j < NUM_GRID - 30)
{
//Verifies blocks below to see if the element wouldn't pass right into another because of gravity (gravity makes the elements travel more than one block per frame)
int k = 1;
while(privategrid[i][j+k+1] == 0 && k <= grid[i][j]->getVel() && j+k < 170)
{
k++;
}
grid[i][j]->update_vel();
grid[i][j + k] = grid[i][j];
grid[i][j] = nullptr;
}
//If block below isn`t empty, check diagonally
else if(privategrid[i][j+1] != 0)
{
if(privategrid[i+1][j+1] == 0)
{
grid[i + 1][j + 1] = grid[i][j];
grid[i][j] = nullptr;
}
else if(privategrid[i-1][j+1] == 0)
{
grid[i - 1][j + 1] = grid[i][j];
grid[i][j] = nullptr;
}
}
}
it crashes right in the first if
std::cout << "tste: " << privategrid[100][100] << std::endl;
Before i was doing what the checkBelow does directly in the execute() function from the grid, and it worked, but after i change it to another function it does not work anymore.
Already tryed debugging and doing out-of-bounds checking.
Caique Ferraz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.