Collision Grid generation issue

Started by
2 comments, last by fastcall22 11 years, 8 months ago
I am trying to make a grid for a simple test collision system but when I actually generate the grid it seems that it make 1 less row and column of grids then it could have. I am not sure why so I was hoping you guys could help.

Here is the code
[source lang="csharp"]using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace GridSystem
{
public class Grid
{
public Rectangle[,] grid
{
get
{
return _grid;
}

private set
{
_grid = value;
}
}
Rectangle[,] _grid;
public int gridW;
public int gridH;

public Grid(int screenX, int screenY)
{
this.gridW = screenX / 32;
this.gridH = screenY / 32;
grid = new Rectangle[gridW, gridH];

for (int i = 0; i < (gridW) - 1; i++)
{
for (int j = 0; j < (gridH) - 1; j++)
{
if (i == 0)
{
grid[i, j] = new Rectangle(0, 0 + (32 * j), 32, 32);
}
else if (j == 0)
{
grid[i, j] = new Rectangle(i * 32, 0, 32, 32);
}
else
{
grid[i, j] = new Rectangle(grid[i, j - 1].X, grid[i, j - 1].Y + 32, 32, 32);
}
}
}
}
}
}
[/source]

thanks in advance,
Dartos
Advertisement
It seems this is the problem:

for (int i = 0; i < (gridW) - 1; i++) {
for (int j = 0; j < (gridH) - 1; j++) {


For example if gridW==3 then loop is executed only when i<2, because you are comparing i<gridW-1, not against i<gridW. Same thing happens with looping j.

It seems this is the problem:

for (int i = 0; i < (gridW) - 1; i++) {
for (int j = 0; j < (gridH) - 1; j++) {


For example if gridW==3 then loop is executed only when i<2, because you are comparing i<gridW-1, not against i<gridW. Same thing happens with looping j.


That is not the issue. I tried it without the " - 1" on both but nothing changed. Also if gridW == 3 then the array's index goes from 0-2. So I need to subtract one.
Either way it has the same result
Also if gridW == 3 then the array's index goes from 0-2. So I need to subtract one.

Yes, if N == 3, then indexes go from 0 to 2. Note the less-than equality operator, the body of the loop will not execute when idx == N-1 or idx > N-1.

Iterating through all elements in an array can be written as follows:
for ( int idx = 0; idx < N; ++idx )
for ( int idx = 0; idx <= N-1; ++idx )
But not:
for ( int idx = 0; idx < N-1; ++idx )

This topic is closed to new replies.

Advertisement