I've written a tile editor and game in XNA, with velocities and gravity, and am having trouble with some of my collision detection things. It works okay, but seems to glitch between just inside and outside the tile the player is on. Here's my collision detection function and the other functions it uses:
void SolveCollisions(List<Tile> tiles, Vector2 screensize)
{
if (position.X < 0)
{
position.X = 0;
}
if (position.X + 32 > screensize.X)
{
position.X = screensize.X - 32;
}
if (position.Y < 0)
{
position.Y = 0;
}
if (position.Y + 32 > screensize.Y)
{
position.Y = screensize.Y - 32;
}
foreach (Tile t in tiles)
{
if (absTilePos(position.X) == absTilePos(t.position.X))
{
if (intersect(position.Y, t.position.Y, 32, 32))
{
if (position.Y > 0)
{
velocity.Y = 0;
position.Y = tilePos(position.Y);
}
if (position.Y < 0)
{
velocity.Y = 0;
position.Y = tilePos(position.Y) + 32;
}
}
}
if (absTilePos(position.Y) == absTilePos(t.position.Y))
{
if (intersect(position.X, t.position.X, 32, 32))
{
if (position.X > 0)
{
velocity.X = 0;
position.X = tilePos(position.X);
}
if (position.X < 0)
{
velocity.X = 0;
position.X = tilePos(position.X) + 32;
}
}
}
}
}
bool intersect(float p1, float p2, float s1, float s2)
{
if (p1 < p2 && p1 + s1 > p2)
{
return true;
}
if (p2 < p1 && p2 + s2 > p1)
{
return true;
}
return false;
}
float tilePos(float f)
{
int i = (int)f;
i /= 32;
i *= 32;
return (float)i;
}
float absTilePos(float f)
{
int i = (int)f;
i /= 32;
return (float)i;
}
The player also glitches into blocks on it's top and right ( http://puu.sh/2cVQf ) when it hits them instead of bouncing off them - it just goes straight into them.
Does anyone know how to remedy this? Thanks!