Reputation: 118
here is the code, I noticed that the Getlength method returns 0 but I think its normal as the for loop wont go further than 0.. I've written
int yy = tile.GetLength(1);
and it throws the same exception as the code under :
TileData[][] tile = GameMain.Level.getCollisionTiles();
Rectangle tileRectangle;
for(int x = 0; x <= tile.GetLength(0); x++)
{
for (int y = 0; y <= tile.GetLength(1); y++) //EXCEPTION THROWN HERE AT GETLENGTH !!!!
{
tileRectangle = tile[x][y].Target;
if (tileRectangle.Contains(m_hitbox)) //Si il y a collision
{
if ((m_hitbox.X + m_hitbox.Width) > tileRectangle.X) //si le joueur percute par la gauche
{
m_hitbox.X--;
}
else if (m_hitbox.X < (tileRectangle.X + tileRectangle.Width)) //Droite
{
m_hitbox.X++;
}
if ((m_hitbox.Y + m_hitbox.Height) > tileRectangle.Y) //si le joueur percute par le haut
{
m_hitbox.Y--;
}
else if (m_hitbox.Y < (tileRectangle.Y + tileRectangle.Height)) //Bas
{
m_hitbox.Y++;
}
}
}
}
EDIT: I got it working by getting the tile info from the map object, but now it throws NullReferenceException
TileData[][] tile = GameMain.Level.getCollisionTiles();
int xMax = GameMain.Level.getMapHeight();
int yMax = GameMain.Level.getMapWidth();
for (int x = 0; x <= xMax; x++)
{
for (int y = 0; y <= yMax; y++)
{
Rectangle tileRectangle = tile[x][y].Target; //THIS LINE FAILS !!!!
if (tileRectangle.Contains(m_hitbox)) //Si il y a collision
{
if ((m_hitbox.X + m_hitbox.Width) > tileRectangle.X) //si le joueur percute par la gauche
{
m_hitbox.X--;
}
else if (m_hitbox.X < (tileRectangle.X + tileRectangle.Width)) //Droite
{
m_hitbox.X++;
}
if ((m_hitbox.Y + m_hitbox.Height) > tileRectangle.Y) //si le joueur percute par le haut
{
m_hitbox.Y--;
}
else if (m_hitbox.Y < (tileRectangle.Y + tileRectangle.Height)) //Bas
{
m_hitbox.Y++;
}
}
}
}
Sorry to ask you this question in the same topic, but i think you can help me resolving it fast.
Upvotes: 2
Views: 1427
Reputation: 67080
It's not a 2D array. TileData[][]
is a jagged array, TileData[,]
is a 2D array then, in your case, GetLength(1)
will always fail because tile has only one dimension.
EDIT
What to do to solve this? You can change tile from [][] to [,] (for example) and keep everything else as is (how getCollisionTiles()
works?) or you may update your code to get right size from jagged array, like this:
for (int y = 0; y < tile[x].GetLength(0); y++)
BTW you may even replace GetLength(0)
with a simple Length
:
for(int x = 0; x < tile.Length; x++)
{
for (int y = 0; y < tile[x].Length; y++)
Final note: for 0 based arrays Length is not inclusive for index so x <= tile.Length
must be replaced with x < tile.Length
.
Upvotes: 8