So im making an RPG. For collision detection, I thought I would do it like this:
- Read text file containing collision data.
- Iterate through the list using nested for loops.
- When a value of 1 occurs (denoting an inpassable tile) add a rectangle to list 'badTiles', where the x and y pos of the rectangle is the x and y value from the nested for loop times the tile width and height.
- Now that all bad tiles are stored in a list of rectangles, we can check for collision.
- In player class, perform a foreach loop, checking all rectangles in badTiles list.
- If players rectangle intersects any member of the badTiles list, a collision has occured and perform an action (not the problem)
My problem is, collision detection is only working on the last 'badTile' in the list. I have added code so that when the badTiles are added to the list, and when the player collides with the badTiles, text on the console will appear, this all works fine and dandy. However, when it actually comes to preventing my player from walking through the tile, it only is prevented on the last badTile in the list..... huh?!
I have a hunch the probem lies with the actual reading of the file data. This is because I wanted to count how many rectangles were being added to the badTiles list (so I cross check with the data file and make sure the correct amount are being added in). I did this by creating a local int c = 1, and everytime the file parses a 1, c += 1. However the output in my console window only displays 1. The variable isnt incrementing?!
Here is the code for the loading of the data file:
// Reads collision map file.
public void LoadCollisionMap(string name)
{
string path = "C:/Users/Chris/Desktop/Documents/C# Projects/RPGEngine/Maps/" + name + ".txt";
// Width and height of our tile array
int width = 0;
int height = File.ReadLines(path).Count();
StreamReader sReader = new StreamReader(path);
string line = sReader.ReadLine();
string[] tileNo = line.Split(',');
width = tileNo.Count();
sReader.Close();
// Re-initialising sReader
sReader = new StreamReader(path);
for (int y = 0; y < height; y++)
{
line = sReader.ReadLine();
tileNo = line.Split(',');
for (int x = 0; x < width; x++)
{
if ((Convert.ToInt32(tileNo[x])) == 1)
{
int c = 1;
badTiles.Add(new Rectangle((x * Core.TILE_WIDTH), (y * Core.TILE_HEIGHT), 32, 32));
Console.WriteLine("New rectangle added, number: " + c + "."); // Adds some info to the console for easy viewing.
c++;
}
}
}
sReader.Close();
}
Any and all help will be appreciated!