# [XNA] Scrolling Tile-Based Map

This topic is 3847 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Well, I successfully created a tile-based map. And my little avatar can move around on it. But now I've decided that I want him to be in the center of the map and have the map scroll. Apparently XNA didn't like my implementation too much. First, Map.cs
public const int mapWidth = 20;
public const int mapHeight = 20;

public static int mapX = 0;
public static int mapY = 0;

//map stored in array

public void Draw(SpriteBatch sBatch)
{
//a pair of for loops to iterate through both dimensions
//of the array containing the map
for (int y = 0; y < mapHeight; y++)
{
for (int x = 0; x < mapWidth; x++)
{
sBatch.Draw(tiles[map[y + mapY, x + mapX]],
new Rectangle(x * tileWidth, y * tileHeight,
tileWidth, tileHeight), Color.White);
}
}


And the part that (I thought) would move the map in Main.cs
        protected override void Update(GameTime gameTime)
{
KeyboardState kState = Keyboard.GetState();
float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
totalTime += elapsedTime;

if (totalTime >= keyPressDelay)
{
if (kState.IsKeyDown(Keys.W))
{
TileMap.mapY--;
totalTime = 0.0f;
}
else if (kState.IsKeyDown(Keys.S))
{
TileMap.mapY++;
totalTime = 0.0f;
}
else if (kState.IsKeyDown(Keys.A))
{
TileMap.mapX--;
totalTime = 0.0f;
}
else if (kState.IsKeyDown(Keys.D))
{
TileMap.mapX++;
totalTime = 0.0f;
}
}
}


 I suppose the compiler error might help.
Quote:
 Original message from Compiler System.IndexOutOfRangeException was unhandled Message="Index was outside the bounds of the array."
Is the reason for this because I don't have a limit for the size of my map being shown to the viewer? That is, the entire map is drawn to fill up the entire window; however, the window is not large enough to fit the entire map. I have no boundaries set for the map, so it just tries to scroll beyond what my map's boundaries (the end of the map instead of the size of the window) are? This is such a difficult journey... [/edit]

##### Share on other sites
Yeah it looks like you are trying to draw a grid space outside of the legal bounds of your map array. Assuming you have your map tiles in a 2D array, in your draw loop make sure that:

- (y>=0) && (y<map_height)
- (x>=0) && (x<map_width)

##### Share on other sites
Wonderful! That's what I thought the problem was, but I was so vastly frustrated I couldn't bare (or is the correct homonym bear? I think it's bear...) to test it. Haha. Well, it works now. The only problem now is that when I reach the end of the map, it complains about the same problem. So I'm thinking I need a way to reset mapX and mapY if they get to a certain point...hmmm...maybe if x >= displaywidth then x = 0? I'll try it out later. Thanks so much for reaffirming my suspicions! :)