# (SFML) Moving in one direction a time

so i've been making a pathfinder on a grid. I've succesfuly implemented the A* algorithm so the next step is making the AI follow a path. I got it to move to the desired destination but the thing is it moves diagonally and I dont want it to. I want to move vertically or horizontally. this is my current code:

void AIEnemy::AutoMotion(Gridspot& grid)

{

std::pair<int, int> ecn = getNodePosition();

sf::Time deltaTime = clock.getElapsedTime();

std::reverse(grid.Path.begin(), grid.Path.end());

for (auto path : grid.Path)

{

float rectx = rect.getPosition().x + rect.getOrigin().x / 2,

recty = rect.getPosition().y + rect.getOrigin().y / 2;
bool firm= true;

if (ecn.first == path.node.first && top >= path.rectCenter.y)

{

rect.move(0, -2);

}

if (ecn.second == path.node.second && left >= path.rectCenter.x)

{

rect.move(-2 , 0);

}

}

}


before i had a bool set that will ring true it is already in motion to so that it couldn't move in the x-axis in conjunction to th y. that didn't work, i also used if and elseif is before ut that didn't do anything. essentially I want it to move like pacman ghosts

## 1 Answer

What you need to do is, once you begin moving in one direction, make it impossible to to move in another direction until you complete the movement. It would look something like this in psuedocode:

if (!moveableObject.isMoving()) {
if (pathIsOpenUp()) {
moveableObject.setTrajectoryUp();
}
else if (pathIsOpenLeft()) {
moveableObject.setTrajectoryLeft();
}
// Repeat for bottom and right
}


Now your trajectory function needs to persist between frames and your isMoving() flag needs to be cleared and trajectory zero'd out when the end of a path is reached.

• thank you. that's another workaround i thought would work too ( and I think it will work) but i don't know how to detect speed/movement in sfml or I guess Apr 21 '19 at 0:19
• @YamaraiAkizuki it's an implementation detail. You use collision detection to determine if it is too close to an edge and if so stop movement. Apr 21 '19 at 0:41
• isMoving() is just a Boolean flag: mMoving or some such. When you setTrajectory you flip it true. And when it gets closer to the edge you clear it false. Apr 21 '19 at 0:43
• I used the boolean flags and everything but nothing changed. im guessing im not checking the right thing Apr 22 '19 at 12:17