I'v been trying to get collision detection between the tiled world and my free moving objects to work, I'v been through MANY hiccups but I finally found a way to do the collision detection right, the only problem is I don't know how to make the player slide alongside a wall if he is moving in more than one direction and the other one is collision free.
This is what I have so far...it's working on the top and bottom walls but not the right and left:
void Player::update(float dt, const Tiles& tiles)
{
float x = m_x;
float y = m_y;
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Up ) )
{
y -= m_speed;
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Down ) )
{
y += m_speed;
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Left ) )
{
x -= m_speed;
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Right ) )
{
x += m_speed;
}
/* Calculate the nerest tiles around the player. */
int startY = ( m_y - 32 ) / 32;
int startX = ( m_x - 32 ) / 32;
int endY = ( m_y + 64 ) / 32;
int endX = ( m_x + 64) / 32;
for( int sy = startY; sy < endY; sy++ )
{
for( int sx = startX; sx < endX; sx++ )
{
if( tiles[sx][sy] != 1 && tiles[sx][sy] != 5 )
{
sf::IntRect wall;
wall.top = sy * 32;
wall.left = sx * 32;
wall.width = 32;
wall.height = 32;
m_boundingbox.top = y+20;
m_boundingbox.left = x+8;
if(m_boundingbox.intersects(wall))
{
sf::IntRect xaxis(x+8,m_y+20,16,8);
sf::IntRect yaxis(m_x+8,y+20,16,8);
if( !xaxis.intersects(wall) )
{
m_x = x;
}
else if( !yaxis.intersects(wall) )
{
m_y = y;
}
return;
}
}
}
}
m_x = x;
m_y = y;
}
I'v been trying all day and I have no idea how to achieve this.