So, I'm writing my own game to expand on my abilities as a programmer. However, I have come to a writer's-block of sorts. The game I am building uses tile collision, but allows the player to be in an unaligned space (like at the edge of a tile rather than directly above it).
The code I have written to determine which tile the player is standing on is failing. On certain edges, when standing on top of the tile, the player will fall through the tile. Here is an example of this occurrence: http://i.imgur.com/CACfhIP.gifv
I have narrowed this down to this specific segment of code: (Please note that SPRITE_WIDTH is 20, which also means 20 pixels)
BOOL changePos(Player* player, Level* level, int newX, int newY)
{
int roundedY;
int roundedX;
if (newX <= player->pos.x)
roundedX = roundDownTo(newX, SPRITE_WIDTH); //round down to a multiple of SPRITE_WIDTH
else if (newX > player->pos.x)
roundedX = roundUpTo(newX, SPRITE_WIDTH); //ditto but up
The problem seems to be that both parts of the if...else if...
statement require the equality symbol to work correctly. Meaning that in the provided example, the fall-through glitch will happen to the tile on the left instead if I move the equality symbol to the else if
portion.
I attempted to fix this issue by adding an else
clause and removing the equality from the if...else if...
parts. My method was to determine which half of the tile the player was on and determine if it required them to fall. So, my code became this:
BOOL changePos(Player* player, Level* level, int newX, int newY)
{
int roundedY;
int roundedX;
if (newX < player->pos.x)
roundedX = roundDownTo(newX, SPRITE_WIDTH);
else if (newX > player->pos.x)
roundedX = roundUpTo(newX, SPRITE_WIDTH);
else
if (newX%SPRITE_WIDTH >= SPRITE_WIDTH / 2)
roundedX = roundDownTo(newX, SPRITE_WIDTH);
else
roundedX = roundUpTo(newX, SPRITE_WIDTH);
But this created an even stranger case where the middle part of the tile would cause a fall-through but the edges would work correctly on both the left and the right tile. This can be seen here: http://i.imgur.com/lTaUuzh.gifv
I've been at this all day (literally), I appreciate any help you can provide.
If I have not provided enough information, please let me know and I will do my best to provide it.