I am trying to fix the collision between my player and the tilemap that I am using to render my game. For whatever reason the collision is off when I start scrolling in the X-axis, the up and down collision doesn't really work at all with or without scrolling. The algorithm is supposed to take 2 points (the 2 points make a single side of the rectangle that represents the player) and then it checks to see if that side has made contact with a wall or not. I pasted the code below, any ideas?
public void checkCollisions() {
int top, bottom;
top = (int)(y + l.m.yOff) / l.getTileSize();
bottom = (int)(y + l.m.yOff + h) / l.getTileSize();
canLeft = l.m.getTile((int)(x + l.m.xOff) / l.getTileSize(), top) == 0 &&
l.m.getTile((int)(x + l.m.xOff) / l.getTileSize(), bottom) == 0;
canRight = l.m.getTile((int)(x + l.m.xOff + w) / l.getTileSize(), top) == 0 &&
l.m.getTile((int)(x + l.m.xOff + w) / l.getTileSize(), bottom) == 0;
canDown = l.m.getTile((int)(x + l.m.xOff) / l.getTileSize(), bottom) == 0 &&
l.m.getTile((int)(x + l.m.xOff + w) / l.getTileSize(), bottom) == 0;
canUp = l.m.getTile((int)(x + l.m.xOff) / l.getTileSize(), top) == 0 &&
l.m.getTile((int)(x + l.m.xOff + w) / l.getTileSize(), top) == 0;
}
The getTile method is defined as:
public int getTile(int x, int y){
return map[y][x];
}
and my map is defined as a 2D int array with 40 elements each:
int[][] map = new int[40][40];
and the l.m.xOff
and the l.m.yOff
variables control the scrolling
EDIT
public void checkCollisions() {
int top, bottom;
top = (int)(y) / l.getTileSize() - (l.m.yOff / l.getTileSize());
bottom = (int)(y + h) / l.getTileSize()- (l.m.yOff / l.getTileSize());
canLeft = l.m.getTile((int)(x) / l.getTileSize() - (l.m.xOff / l.getTileSize()), top) == 0 &&
l.m.getTile((int)(x) / l.getTileSize() - (l.m.xOff / l.getTileSize()), bottom) == 0;
canRight = l.m.getTile((int)(x + w) / l.getTileSize() - (l.m.xOff / l.getTileSize()), top) == 0 &&
l.m.getTile((int)(x + w) / l.getTileSize() - (l.m.xOff / l.getTileSize()), bottom) == 0;
canDown = l.m.getTile((int)(x - l.m.xOff) / l.getTileSize() - (l.m.xOff / l.getTileSize()), bottom) == 0 &&
l.m.getTile((int)(x + w) / l.getTileSize() - (l.m.xOff / l.getTileSize()), bottom) == 0;
canUp = l.m.getTile((int)(x) / l.getTileSize() - (l.m.xOff / l.getTileSize()), top) == 0 &&
l.m.getTile((int)(x + w) / l.getTileSize() - (l.m.xOff / l.getTileSize()), top) == 0;
}
I divided the offsets by the tilesize because the getTile method returns the value of the 2D integer array and the offsets are much larger than the length of the arrays. (for example the xOffset at one point was in the 700's and there are only 40 tiles).