Hello.
I’ve tried my best to make this collision work, but I simply can’t. I tried every method, even copied the code from internet tutorial, but it simply won’t work. It seems as if when the player is in the middle of two tiles, it won’t work. Uh, I don’t know how to explain it right, so I’ll post some screenshots.
It works if the player is in a “full” tile.
Click here to see the screenshot.
But, if a player is kind of in a “half” tile, it doesn’t.
Click here to see the screenshot.
The code I use to check for the collision:
public void update(int delta, int direction, Map map){
speed = 0.2f; // Just for testing purposes. Will remove later.
switch(direction){
case 1: // Up
sprite = up;
if(!map.isBlocked(x, y - delta * speed)){
y -= delta * speed;
}
break;
case 2: // Down
sprite = down;
if(!map.isBlocked(x, y + Constants.TILE_SIZE + delta * speed)){
y += delta * speed;
}
break;
case 3: // Left
sprite = left;
if(!map.isBlocked(x - delta * speed, y)){
x -= delta * speed;
}
break;
case 4: // Right
sprite = right;
if(!map.isBlocked(x + Constants.TILE_SIZE + delta * speed, y)){
x += delta * speed;
}
break;
default:
System.err.println("Invalid direction.");
break;
}
}
My isBlocked(float, float) method (in Map class) is pretty simple:
public boolean isBlocked(float x, float y){
int xTile = (int) (x / 32);
int yTile = (int) (y / 32);
return blocked[xTile][yTile];
}
NOTE: In my map class I set up stuff with TiledMap, just so you know.