Unfortunately, I think it is still quite hard to decipher what you are actually asking for. 'what I want is to move the sprite tile by tile' is not very descriptive.
You said earlier that the code provided Ixrec is "what I wanted". I note that his code contains several bugs; for instance, when checking the major axis, the absolute value of each axis should be taken. Also, his approach is not exempt from normalization, which in 1D amounts to taking the sign of the major axis.
Here is an attempt to resolve said bugs (although it may well contain several new bugs, because we have no way of testing against your codebase. Also because I couldn't resist flattening your control flow
). I have introduced a new parameter, 'axisLocked', which when true will lock movement to the current major axis as in Ixrec's code, otherwise it will allow arbitrary movement, as in your original code.
void PathFinder::moveToDestination( float dt, bool axisLocked = false )
{
if ( !_isPathFound ) {
return;
}
if ( (c + 1) < path.size() ) {
spriteNextTile = path[c + 1];
}
const float tilesize = static_cast<float>( tileset->getTilesize() );
targetPosition.x = spriteNextTile->getTileGridPositionX() * tilesize;
targetPosition.y = spriteNextTile->getTileGridPositionY() * tilesize;
spritePosition.x = movableObjects->getSpritePositionX();
spritePosition.y = movableObjects->getSpritePositionY();
delta = targetPosition - spritePosition;
// distance considered 'close enough' to target position.
const float tolerance = 1.0f;
// actual distance to target position.
const float distance = length( delta );
// amount of movement this time step.
const float displacement = movableObjects->getVelocity() * dt;
// direction of movement.
sf::Vector2f direction( 0.0f, 0.0f );
if ( axisLocked )
{
// movment restricted to major axis.
if( std::abs(delta.x) > std::abs(delta.y) )
{
// horizontal movement.
direction.x = (delta.x < 0.0f) ? -1.0f : 1.0f;
}
else
{
// vertical movement.
direction.y = (delta.y < 0.0f) ? -1.0f : 1.0f;
}
}
else
{
// movement in arbitrary direction.
direction = normalize( delta );
}
if ( distance <= tolerance || distance <= displacement )
{
// target position reached.
spritePosition = targetPosition;
if ( ++c >= path.size() - 1 )
{
// end of path reached.
_isPathFound = false;
c = 0;
reset();
}
}
else
{
// advance towards target position.
spritePosition += direction * displacement;
}
movableObjects->setSpritePosition( spritePosition.x, spritePosition.y );
}
Really though, this is no better than looking into a crystal ball. I could well be that you have competing forces which need resolving, or any other number of possibilities. AI code is notoriously fiddly, often leading straight to tweakers hell.