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
Collision Grid generation issue
Started by infectedbrain, Aug 15 2012 01:19 AM
3 replies to this topic
Sponsor:
#2 Members - Reputation: 539
Posted 15 August 2012 - 01:51 AM
It seems this is the problem:
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.
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.
#3 Members - Reputation: 157
Posted 15 August 2012 - 01:34 PM
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
#4 Members - Reputation: 1907
Posted 15 August 2012 - 01:57 PM
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.Also if gridW == 3 then the array's index goes from 0-2. So I need to subtract one.
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 )
Edited by fastcall22, 15 August 2012 - 01:58 PM.






